Search completed in 1.58 seconds.
Examples - Archive of obsolete content
this page contains the source code of the
examples related to the "properly using css and javascript in xhtml documents" article.
... please refer to the article to learn more about these
examples.
... if you wish to test these
examples by yourself, please read the important notes.
...And 6 more matches
Examples
these
examples demonstrate how to use js-ctypes.
... standard os libraries some
examples on how to get cursor position on each os.
... mac os x these
examples require mac os x to operate.
Examples and demos from articles - Archive of obsolete content
what follows is a brief list of
examples and demos from our theoretical articles.
...it guides you through the basic features of the language with practical
examples that you can try for yourself on your own computer and illustrates the standard features of css that work in modern browsers.
Rhino Examples
examples have been provided that show how to control the javascript engine and how to implement scriptable host objects.
... all the
examples are in the git tree at mozilla/js/rhino/
examples.
Address Book examples
note: thunderbird and seamonkey user interfaces now reference 'contacts' not 'cards' however, as the backend still uses the 'cards' terminology, that is what is used here this article provides
examples on accessing and manipulating thunderbird address books.
... in the following
examples: selectedab is the uri of an address book to default the dialog to saving the card in.
Gloda examples
this content covers features introduced in thunderbird 3 this page provides some
examples for using gloda.
... see creating a gloda message query for more
examples.
Examples
newpromise.then(null, components.utils.reporterror); note: more
examples for consuming promises are available in the promise object documentation.
Examples
there are several java test applications checked in to the tree that give
examples on how to embed gecko or init xpcom from within java.
Examples - MathML
below you'll find some
examples you can look at to help you to understand how to use mathml to display increasingly complex mathematical concepts in web content.
Install Manifests - Archive of obsolete content
examples <em:id>extensionname@example.org</em:id> <em:id>{daf44bf7-a45e-4450-979c-91cf07434c3d}</em:id> name the name of the add-on; intended for display in the ui.
...
examples <em:name>my extension</em:name> targetapplication an object specifying an application targeted by this add-on.
...
examples <em:targetapplication> <description> <em:id>{ec8030f7-c20a-464f-9b0e-13a3a9e97384}</em:id> <!--firefox--> <em:minversion>1.5</em:minversion> <em:maxversion>3.0.*</em:maxversion> </description> </em:targetapplication> gecko 1.9 based applications allow you to use the special targetapplication id toolkit@mozilla.org to say that the add-on is compatible with any toolkit app with a ...
...And 17 more matches
StringView - Archive of obsolete content
examples var mystringview1 = new stringview("hello world!"); // utf-8 alert(mystringview1) // "hello world!" var mystringview2 = new stringview(mystringview1, "utf-16"); alert(mystringview1.buffer.bytelength); // 12 alert(mystringview2.buffer.bytelength); // 24 stringview constructor's methods makefrombase64() syntax stringview.makefrombase64(base64string[, encoding][, byteoffset][, le...
...
examples var mystringview = stringview.makefrombase64("sgvsbg8gd29ybgqh"); alert(mystringview) // "hello world!" this function is useful in order to pass binary data containing strings.
...
examples var mystringview = new stringview("\u6432\u6432\u6432\u6432"); alert(mystringview.makeindex()) // 4 alert(mystringview.makeindex(2)) // 6 …using the startfrom argument… var mystringview = stringview.makefrombase64("5lit5pahigvzcghdsw9sievuz2xpc2gg4ks54ks/4kso4kwn4ksm4kwainin2ytyudix2kjzitipihbvcnr1z3xdqnmg4kas4ka+4kac4kay4ka+inga0yprgdgb0lrqunc5ioaxpeacroiqnidgqkrgqbdgqjzgql7gqkzgq...
...And 16 more matches
Index - Archive of obsolete content
184
examples and demos from articles no summary!
... 188 html in xul for rich tooltips code snippets,
examples, html, xul no summary!
...as a rough overview this is a version string split by periods, some
examples: 240 extensions support in seamonkey 2 add-ons, codingscripting, extensions, javascript, seamonkey, url, thunderbird starting with seamonkey 2 alpha 1 seamonkey supports toolkit/-style extensions.
...And 15 more matches
Reference - Archive of obsolete content
-- dria 04:27, 22 september 2005 (pdt) those
examples are not "bad
examples" per se.
...i was wondering what should be done about those
examples, since they would no longer be valid with fx 1.5+ and family.
...--maian 05:10, 22 september 2005 (pdt) if the
examples are there specifically to show the differences between two versions of js, and if we have a section in the reference that is dedicated to discussing these differences, i would think that those samples should be included in that section of the reference.
...And 11 more matches
Index
examples for the database files are key3.db and cert8.db, where the numbers are file version numbers.
...
examples are retrieving ocsp (online certificate status protocol) information or downloading a crl (certificate revocation list).
... this program shows the following: 177 nss sample code sample_1_hashing
examples, nss, security this is an example program that demonstrates how to compute the hash of a file and save it to another file.
...And 11 more matches
Index - Web APIs
45 aeskeygenparams api, aeskeygenparams, dictionary, reference, web crypto api see the
examples for subtlecrypto.generatekey().
...
examples include: 157 audionode.channelcount api, audionode, property, reference, web audio api, channelcount the channelcount property of the audionode interface represents an integer used to determine how many channels are used when up-mixing and down-mixing connections to any inputs to the node.
...the
examples provided should give you some clear ideas what you can do with canvas, and will provide code snippets that may get you started in building your own content.
...And 11 more matches
Proxy Auto-Configuration (PAC) file - HTTP
examples proxy w3proxy.netscape.com:8080; proxy mozilla.netscape.com:8081 primary proxy is w3proxy:8080; if that goes down start using mozilla:8081 until the primary proxy comes up again.
... the
examples at the end of this document are complete.
...ditions shexpmatch() time based conditions weekdayrange() daterange() timerange() logging utility alert() there was one associative array (object) already defined, because at the time javascript code was unable to define it by itself: proxyconfig.bindings note: pactester (part of the pacparser package) was used to test the following syntax
examples.
...And 11 more matches
Python binding for NSS
examples of this are the various callbacks which can be set and their parameters.
... example code the doc/
examples directory contains numerous
examples of python-nss programs and libraries you may wish to consult.
... test code in addition the test directory contains unit tests that also illustrate python-nss usage, however unlike the
examples the unit tests are geared towards testing rather than expository illustration.
...And 10 more matches
Index
3 account
examples extensions, thunderbird this article provides
examples on accessing and manipulating thunderbird accounts.
...see account
examples for
examples and code snippets.
...the functionality of the component is described on the activity manager page, and the activity manager
examples page has code snippets.
...And 9 more matches
ARIA Test Cases - Accessibility
for more up-to-date
examples, see the openajaxalliance aria
examples page.
... or copy-paste: http://oaa-accessibility.org/
examples/ for each example we test the "expected" results with assistive technologies, for each browser that at supports wai-aria in.
...also, as a clever feature for at testing, the firing of events (like event_object_statechange) can be invoked from the
examples.
...And 8 more matches
Writing WebSocket client applications - Web APIs
examples this simple example creates a new websocket, connecting to the server at wss://www.example.com/socketserver.
... var
examplesocket = new websocket("wss://www.example.com/socketserver", "protocolone"); on return,
examplesocket.readystate is connecting.
... 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.
...And 6 more matches
<input type="range"> - HTML: Hypertext Markup Language
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples while the number type lets users enter a number with optional constraints forcing their value to be between a minimum and a maximum value, it does require that they enter a specific value.
... a few
examples of situations in which range inputs are commonly used: audio controls such as volume and balance, or filter controls.
...And 6 more matches
MIME types (IANA media types) - HTTP
other common
examples include application/pdf, application/pkcs8, and application/zip.
...
examples include audio/mpeg, audio/vorbis.
... example reserved for use as a placeholder in
examples showing how to use mime types.
...And 6 more matches
Basic native form controls - Learn web development
they are a very convenient way to let the user enter any kind of data, and we've already seen a few simple
examples.
... note: you can find
examples of all the single line text field types on github at single-line-text-fields.html (see it live also).
... note: you can find the
examples from this section on github as checkable-items.html (see it live also).
...And 5 more matches
WebRequest.jsm
some
examples of using addlistener().
... see some
examples of using filter.
...see some
examples of canceling requests.
...And 5 more matches
Expressions and operators - JavaScript
consider these
examples: w = z = x = y is equivalent to w = (z = (x = y)) or x = y; z = y; w = y z += x *= y is equivalent to z += (x *= y) or tmp = x * y; x *= y; z += tmp (except without the tmp).
...the following table describes the comparison operators in terms of this sample code: var var1 = 3; var var2 = 4; comparison operators operator description
examples returning true equal (==) returns true if the operands are equal.
...so, when the bitwise operators are applied to these values, the results are as follows: bitwise operator
examples expression result binary description 15 & 9 9 1111 & 1001 = 1001 15 | 9 15 1111 | 1001 = 1111 15 ^ 9 6 1111 ^ 1001 = 0110 ~15 -16 ~ 0000 0000 ... 0000 1111 = 1111 1111 ... 1111 0000 ~9 -10 ~ 0000 0000 ... 0000 1001 = 1111 1111 ... 1111 0110 note that all 32 bits ...
...And 5 more matches
Client-side form validation - Learn web development
this article leads you through basic concepts and
examples of client-side form validation.
... built-in form validation
examples in this section, we'll test out some of the attributes that we discussed above.
...below are some
examples to give you a basic idea of how they work.
...And 4 more matches
Handling common accessibility problems - Learn web development
some
examples might include: users on mobile devices.
...
examples of bad and good html: <font size="7">my heading</font> <br><br> this is the first section of my document.
...see creating a cross-browser video player for some good
examples of this.
...And 4 more matches
Roll your own browser: An embedding how-to
do you have any simple
examples of embedding mozilla?
... there are many
examples of products already using gecko for embedding.
...the sections marked 'mozilla
examples' refer to clients and sample code to be found within the mozilla source tree.
...And 4 more matches
Using the CSS Painting API - Web APIs
css.paintworklet.addmodule('https://mdn.github.io/houdini-
examples/csspaint/intro/01partone/header-highlight.js'); reference the paint worklet in css once we have a registered paint worklet, we can use it in css.
... css.paintworklet.addmodule('https://mdn.github.io/houdini-
examples/csspaint/intro/02parttwo/header-highlight.js'); .fancy { background-image: paint(headerhighlight); } .half { width: 50%; } <h1 class="fancy">largest header</h1> <h6 class="fancy">smallest header</h6> <h3 class="fancy half">50% width header</h3> while you can't play with the worklet's script, you can alter the element's font-size and width to change the size of the background image.
... 2</li> <li>item 3</li> <li>item 4</li> <li>item 5</li> <li>item 6</li> <li>item 7</li> <li>item 8</li> <li>item 9</li> <li>item 10</li> <li>item 11</li> <li>item 12</li> <li>item 13</li> <li>item 14</li> <li>item 15</li> <li>item 16</li> <li>item 17</li> <li>item</li> </ul> css.paintworklet.addmodule('https://mdn.github.io/houdini-
examples/csspaint/intro/worklets/boxbg.js'); li { background-image: paint(boxbg); --boxcolor: hsla(55, 90%, 60%, 1.0); } li:nth-of-type(3n) { --boxcolor: hsla(155, 90%, 60%, 1.0); --widthsubtractor: 20; } li:nth-of-type(3n+1) { --boxcolor: hsla(255, 90%, 60%, 1.0); --widthsubtractor: 40; } in our worklet, we can reference those custom properties.
...And 4 more matches
Date and time formats used in HTML - HTML: Hypertext Markup Language
for <input>, the values of type that return a value which contains a string representing a date and/or time are: date datetime datetime-local month time week
examples before getting into the intricacies of how date and time strings are written and parsed in html, here are some
examples that should give you a good idea what the more commonly-used date and time string formats look like.
...
examples of valid week strings week string week and year (date range) 2001-w37 week 37, 2001 (september 10-16, 2001) 1953-w01 week 1, 1953 (december 29, 1952-january 4, 1953) 1948-w53 week 53, 1948 (december 27, 1948-january 2, 1949) 1949-w01 week 1, 1949 (january 3-9, 1949) 0531-w16 week 16, 531 (april 13-19, 531) 0042-w0...
...
examples of valid month strings month string month and year 17310-09 september, 17310 2019-01 january, 2019 1993-11 november, 1993 0571-04 april, 571 0001-07 july, 1 c.e.
...And 4 more matches
Cross-Origin Resource Sharing (CORS) - HTTP
examples of access control scenarios we present three scenarios that demonstrate how cross-origin resource sharing works.
... all these
examples use xmlhttprequest, which can make cross-site requests in any supporting browser.
... real request is sent: post /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 x-pingother: pingpong content-type: text/xml; charset=utf-8 referer: https://foo.example/
examples/preflightinvocation.html content-length: 55 origin: https://foo.example pragma: no-cache cache-control: no-cache <person><name>arun</name></person> http/1.1 200 ok date: mon, 01 dec 2008 01:15:40 gmt server: apache/2 access-control-allow-origin: https://foo.example vary: accept-encoding, origin content-encoding: gzip content-length: 235 keep-alive: timeout=2, max=99 connection: keep-alive cont...
...And 4 more matches
Index - MDN Web Docs Glossary: Definitions of Web-related terms
in other programming languages different numeric types can exist, for
examples: integers, floats, doubles, or bignums.
...the most common
examples of continuous media are audio and motion video.
...
examples of copyleft licenses are the gnu gpl (for software) and the creative commons sa (share alike) licenses (for works of art).
...And 3 more matches
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...
...in contrast, if you view one of our
examples hosted on github (or an example on some other remote server), the web address will start with http:// or https://, to show that the file has been received via http.
... the problem with testing local files some
examples won't run if you open them as local files.
...And 3 more matches
Third-party APIs - Learn web development
one of the most obvious
examples is using mapping apis to display custom maps on your pages.
... note: you might want to just get all our code
examples at once, in which case you can then just search the repo for the example files you need in each section.
... note: when creating your own
examples, you'll use your own api key in place of any placeholder.
...And 3 more matches
WebGL by example - Web APIs
the
examples are sorted according to topic and level of difficulty, covering the webgl rendering context, shader programming, textures, geometry, user interaction, and more.
...
examples by topic the
examples are sorted in order of increasing difficulty.
... instead of trying to juggle shaders, geometry, and working with gpu memory, already in the first program, the
examples here explore webgl in an incremental way.
...And 3 more matches
Web Video Text Tracks Format (WebVTT) - Web APIs
inner structure of a webvtt file let's re-examine one of our previous
examples, and look at the cue structure in a bit more detail.
... example 10 - basic cue timing
examples 00:00:22.230 --> 00:00:24.606 00:00:30.739 --> 00:00:34.074 00:00:34.159 --> 00:00:35.743 00:00:35.827 --> 00:00:40.122 example 11 - overlapping cue timing
examples 00:00:00.000 --> 00:00:10.000 00:00:05.000 --> 00:01:00.000 00:00:30.000 --> 00:00:50.000 example 12 - non-overlapping cue timing
examples 00:00:00.000 --> 00:00:10.000 00:00:10.000 --> 00:01:00.581 00:01:00.581 --> 00:02:00.100 ...
... table 2 - line
examples vertical omitted vertical:rl vertical:lr line:0 top right left line:-1 bottom left right line:0% top right left line:100% bottom left right position specifies where the text will appear horizontally.
...And 3 more matches
<angle> - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples: 0deg, 90deg, 14.23deg.
...
examples: 0grad, 100grad, 38.8grad.
...And 3 more matches
JavaScript modules - JavaScript
introducing an example to demonstrate usage of modules, we've created a simple set of
examples that you can find on github.
... these
examples demonstrate a simple set of modules that create a <canvas> element on a webpage, and then draw (and report information about) different shapes on the canvas.
... note: if you want to download the
examples and run them locally, you'll need to run them through a local web server.
...And 3 more matches
Intl.Collator() constructor - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples: a ≠ b, a = á, a = a.
...
examples: a ≠ b, a ≠ á, a = a.
...And 3 more matches
d - SVG: Scalable Vector Graphics
formula: pn = {xo + dx, yo + dy}
examples html,body,svg { height:100% } <svg viewbox="0 0 100 100" xmlns="http://www.w3.org/2000/svg"> <path fill="none" stroke="red" d="m 10,10 h 10 m 0,10 h 10 m 0,10 h 10 m 40,20 h 10 m 0,10 h 10 m 0,10 h 10 m 0,10 h 10 m 50,50 h 10 m-20,10 h 10 m-20,10 h 10 m-20,10 h 10" /> </svg> lineto path commands lineto instru...
... formula: po′ = pn = {xo, yo + dy}
examples html,body,svg { height:100% } <svg viewbox="0 0 200 100" xmlns="http://www.w3.org/2000/svg"> <!-- lineto commands with absolute coordinates --> <path fill="none" stroke="red" d="m 10,10 l 90,90 v 10 h 50" /> <!-- lineto commands with relative coordinates --> <path fill="none" stroke="red" d="m 110,10 l 80,80 v -80...
...
examples html,body,svg { height:100% } <svg viewbox="0 0 200 100" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> <!-- cubic bézier curve with absolute coordinates --> <path fill="none" stroke="red" d="m 10,90 c 30,90 25,10 50,10 s 70,90 90,90" /> <!-- cubic bézier curve with relative coordinates --> <path fill="none" stroke="red...
...And 3 more matches
Preferences - Archive of obsolete content
this article provides
examples for extension developers that wish to use the mozilla preferences system.
... here are two
examples: // get the root branch var prefs = components.classes["@mozilla.org/preferences-service;1"] .getservice(components.interfaces.nsiprefbranch); // get the "extensions.myext." branch var prefs = components.classes["@mozilla.org/preferences-service;1"] .getservice(components.interfaces.nsiprefservice); prefs = prefs.getbranch("extensions.myext."); simple ...
...// look in the above section for
examples of getting one.
...And 2 more matches
Adding HTML Elements - Archive of obsolete content
this may be clearer from the
examples below.
...some
examples of using html elements are shown below.
... <html:img src="banner.jpg"/> <html:input type="checkbox" value="true"/> <html:table> <html:tr> <html:td> a simple table </html:td> </html:tr> </html:table> these
examples will create an image from the file banner.jpg, a checkbox and a single-cell table.
...And 2 more matches
RDF in Mozilla FAQ - Archive of obsolete content
some
examples of datasources that exist today are "browser bookmarks", "browser global history", "imap mail accounts", "nntp news servers", and "rdf/xml files".
...
examples where can i find some (working)
examples?
... a few
examples are posted here.
...And 2 more matches
Windows Media in Netscape - Archive of obsolete content
this article explains how to embed the windows media player activex control in web pages to support netscape 7.1, how to control the windows media player activex control using javascript and provides working
examples.
...
examples in this article all assume that the user is running windows media player 7 and later, although netscape 7.1 supports the clsids of windows media player 6x and later.
...ymedia" value="play" onclick="startmediaup()"> <input type="button" name="stopmedia" value="stop" onclick="shutmediadown()"> <p>this example shows a minimally-functional player <script> <!-- function startmediaup () { document.player.url = "preludesteel.wma"; document.player.controls.play(); } function shutmediadown () { document.player.controls.stop(); } --> </script> more extensive
examples of working cross-browser code can be found in the
examples section at the end.
...And 2 more matches
CSS values and units - Learn web development
let's have a look at some of the types of value and unit you may frequently encounter, with
examples so that you can try out different possible values.
... the html is a set of nested lists — we have three lists in total and both
examples have the same html.
... color keywords quite often in
examples here in the learn section or elsewhere on mdn you will see the color keywords used, as they are a simple and understandable way of specifying color.
...And 2 more matches
SVG Guidelines
these rules are based on some real
examples seen in mozilla's code.
...no useless whitespaces or line breaks (see below for more details) adding a license header use double quotes whitespace and line breaks whitespace in addition to trailing whitespace at the end of lines, there are a few more cases more specific to svgs: trailing whitespaces in attribute values (usually seen in path definitions) excessive whitespace in path or polygon points definition
examples this path: <path d=" m5,5 l1,1z "> can be cut down to this: <path d="m5,5 l1,1z"> similarly, this polygon: <polygon points=" 0,0 4,4 4,0 "/> can be cut down to this: <polygon points="0,0 4,4 4,0"/> line breaks you should only use line breaks for logical separation or if they help make the file readable.
...typical
examples of this are <title> and <desc> tags.
...And 2 more matches
Index
52
examples javaxpcom, xpcom:language bindings no summary!
...some
examples are: 169 iaccessiblerelation interfaces, needscontent, xpcom, xpcom interface reference returns a localized version of the relation type.
...to create an instance, use: 821 nsiparserutils implemented by: @mozilla.org/parserutils;1 as a service: 822 nsipassword interfaces, login manager, needscontent, xpcom api reference see using nsipasswordmanager for
examples of nsipassword in use.
...And 2 more matches
<input>: The Input (Form Input) element - HTML: Hypertext Markup Language
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... the available types are as follows: type description basic
examples spec button a push button with no default behavior displaying the value of the value attribute, empty by default.
... <input type="datetime" name="datetime"/> html5 attributes the <input> element is so powerful because of its attributes; the type attribute, described with
examples above, being the most important.
...And 2 more matches
User-Agent - HTTP
see below for further details and
examples.
...
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.103 safari/537.36 opera ua string the opera browser is also based on the blink engine, which is why it almost looks the same, but adds "opr/<version>".
...And 2 more matches
Progressive web app structure - Progressive web apps (PWAs)
for working
examples and more information, see the streams api documentation.
...you can <a href="https://github.com/mdn/pwa-
examples/blob/master/js13kpwa">fork js13kpwa on github</a> to check its source code.</p> <button id="notifications">request dummy notifications</button> <section id="content"> // content inserted in here </section> </main> <footer> <p>© js13kgames 2012-2018, created and maintained by <a href="http://end3r.com">andrzej mazur</a> from <a href="http://enclavegames.com">enclave games</a>.</p> </footer>...
...hor) .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.requestpermission().then(function(result) { if(result === 'granted') { randomnotification(); } }); }); the last block creates notifications ...
...And 2 more matches
Structural overview of progressive web apps - Progressive web apps (PWAs)
for working
examples and more information, see the streams api documentation.
...you can <a href="https://github.com/mdn/pwa-
examples/blob/master/js13kpwa"> fork js13kpwa on github</a> to check its source code.</p> <button id="notifications">request dummy notifications</button> <section id="content"> // content inserted in here </section> </main> <footer> <p>© js13kgames 2012-2018, created and maintained by <a href="http://end3r.com"> andrzej mazur</a> from <a href="http://enclavegames.com">enclave games</a...
...thor) .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.
...And 2 more matches
Code snippets - Archive of obsolete content
these
examples demonstrate how to accomplish basic tasks that might not be immediately obvious.
... general
examples and demos from mdn articles a collection of
examples and demos from articles.
...ties svg animation animate svg using javascript and smil svg interacting with script using javascript and dom events to create interactive svg embedding svg in html and xul using svg to enhance html or xul based markup xul widgets html in xul for rich tooltips dynamically embed html into a xul element to attain markup in a tooltip label and description special uses and line breaking
examples tree setup and manipulation of trees using xul and js scrollbar changing style of scrollbars.
... external links the content at mozillazine example code is slowly being moved here, but you can still find useful
examples there for now.
Chapter 3: Introduction to XUL—How to build a more intuitive UI - Archive of obsolete content
you can type these
examples up and open them in firefox to see how they behave and appear.
... you can download a file with all the source code
examples from: fixme: attache the translated tarball - paul task !.
... general root elements window the window element that has appeared in
examples so far is a root element used to define an ordinary window.
... <vbox align="start"> <textbox/> <textbox multiline="true" rows="5" cols="15"/> </vbox> listing 16: textbox
examples figure 13: output from listing 16 autocomplete adding type="autocomplete" to a textbox element enables an automatic completion function for it.
Appendix D: Loading Scripts - Archive of obsolete content
the
examples below which make use of the services global assume that you're previously imported the services.jsm module.
...
examples the following code will execute a simple script in a sandbox with the privilege level of the current content page.
...
examples the following code will load a script into its own context.
...
examples the following code will import a module into the current global scope.
Index of archived content - Archive of obsolete content
code snippets alerts and notifications autocomplete bookmarks boxes canvas code snippets cookies customizing the download progress bar delayed execution dialogs and prompts downloading files drag & drop embedding svg
examples and demos from articles file i/o finding window handles forms related code snippets html in xul for rich tooltips html to dom isdefaultnamespace js xpcom javascript debugger service javascript timers javascript daemons management ...
... learn xpi installer scripting by example installer script using xpinstall to install plugins install script template xpinstall api reference
examples file.macalias file.windowsshortcut install.adddirectory install.addfile installtrigger.installchrome installtrigger.startsoftwareupdate trigger scripts and install scripts windows install file o...
... liveconnect liveconnect overview liveconnect reference jsexception jsobject msx emulator (jsmsx) old proxy api parallelarray properly using css and javascript in xhtml documents
examples reference server-side javascript back to the server: server-side javascript on the rise sharp variables in javascript standards-compliant authoring tools stopiteration styling the amazing netscape fish cam page using javascript generators in firef...
... for enhancement rfe to the custom controls rfe to the custom controls interfaces rfe to the xforms api troubleshooting xforms forms using xforms and php xforms api reference xforms config variables xforms custom controls xforms custom controls
examples xforms styling background-size foreach beginner tutorials creating reusable content with css and xbl underscores in class and id names xml data xul user interfaces case sensitivity in class and id names creating a dynamic ...
Index - Archive of obsolete content
it explains the concept of dom documents, demonstrates a few simple
examples of using dom calls to perform basic manipulations on a document, and then demonstrates working with anonymous xbl content using mozilla-specific methods.
... 971 widget cheatsheet see the periodic table of xul for more
examples.
...here, we'll find out some more details with some
examples.
... 1079 xpcom
examples tutorials, xul, xul_tutorial this section provides some
examples of using xpcom along with some additional interfaces.
What is RSS - Archive of obsolete content
</item> <item> <title>hello</title> <guid>http://katetv.example.com/show/1</guid> <pubdate>tue, 2 aug 2005 18:22:14 -0400</pubdate> <enclosure url="http://katetv.example.com/show/1" length="17442215" type="application/ogg"/> </item> </channel> </rss> the observant reader may have noticed that the news web site and blogger
examples were the same type of rss.
... and also that the internet radio and internet television
examples were the same type of rss.
... note: these rss
examples are very very simple.
...all these rss
examples are very minimal.
HTML: A good basis for accessibility - Learn web development
html and accessibility as you learn more about html — read more resources, look at more
examples, etc.
... note: it is a good idea to have a screen reader set up on your local computer so that you can do some testing of the
examples shown below.
...you can also see some good and bad
examples at good-links.html and bad-links.html.
... note: you can see some good and bad form
examples in good-form.html and bad-form.html.
HTML: A good basis for accessibility - Learn web development
html and accessibility as you learn more about html — read more resources, look at more
examples, etc.
... note: it is a good idea to have a screen reader set up on your local computer so that you can do some testing of the
examples shown below.
...you can also see some good and bad
examples at good-links.html and bad-links.html.
... note: you can see some good and bad form
examples in good-form.html and bad-form.html.
WAI-ARIA basics - Learn web development
good
examples are jquery ui (see about jquery ui: deep accessibility support), extjs, and dojo/dijit.
... practical wai-aria implementations in the next section we'll look at the four areas in more detail, along with practical
examples.
... before you continue, you should get a screenreader testing setup put in place, so you can test some of the
examples as you go through.
...you can see a number of useful
examples in the deque university code library, to give you an idea of how such controls can be made accessible.
How CSS is structured - Learn web development
here are three
examples: <!-- inside a subdirectory called styles inside the current directory --> <link rel="stylesheet" href="styles/style.css"> <!-- inside a subdirectory called general, which is in a subdirectory called styles, inside the current directory --> <link rel="stylesheet" href="styles/general/style.css"> <!-- go up one directory level, then inside a subdirectory called styles --> <link rel="stylesheet"...
...all the
examples below are valid selectors, or lists of selectors.
...dding-top: 10px; padding-right: 15px; padding-bottom: 15px; padding-left: 5px; this one line: background: red url(bg-graphic.png) 10px 10px repeat-x fixed; is equivalent to these five lines: background-color: red; background-image: url(bg-graphic.png); background-position: 10px 10px; background-repeat: repeat-x; background-attachment: fixed; later in the course, you will encounter many other
examples of shorthand properties.
...although the two
examples work the same, the one below is more difficult to read.
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).
... let's look at some
examples to make this clearer.
...
examples of absolute urls full url (the same as the one we used before) https://developer.mozilla.org/docs/learn implicit protocol //developer.mozilla.org/docs/learn in this case, the browser will call that url with the same protocol as the one used to load the document hosting that url.
...
examples of relative urls to better understand the following
examples, let's assume that the urls are called from within the document located at the following url: https://developer.mozilla.org/docs/learn sub-resources skills/infrastructure/understanding_urls because that url does not start with /, the browser will attempt to find the document in a sub-directory of the one containing the current resource.
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...
...along the way, you saw a few code
examples and learned how javascript fits in with the rest of the code on your website, amongst other things.
...each page on mdn has more
examples of usage for you to play with and enhance your knowledge.
... 150 practical positioning
examples article, beginner, css, codingscripting, guide, layout, learn, absolute, fixed, relative so that rounds off our look at positioning — by now, you should have an idea of how the basic mechanics work, as well as understanding how to start applying these to build some interesting ui features.
Basic math in JavaScript — numbers and operators - Learn web development
try entering the
examples below into your developer tools javascript console to familiarize yourself with the syntax.
... first try entering some simple
examples of your own, such as 10 + 7 9 * 8 60 % 3 you can also try declaring and initializing some numbers inside variables, and try using those in the sums — the variables will behave exactly like the values they hold for the purposes of the sum.
...try the above
examples again, but this time use ++num1 and --num2.
...e x -= 3; x = x - 3; *= multiplication assignment multiplies the variable value on the left by the value on the right, and returns the new variable value x *= 3; x = x * 3; /= division assignment divides the variable value on the left by the value on the right, and returns the new variable value x /= 5; x = x / 5; try typing some of the above
examples into your console, to get an idea of how they work.
What is JavaScript? - Learn web development
examples of popular server-side web languages include php, python, ruby, asp.net and...
... in the above code
examples, in the internal and external
examples the javascript is loaded and run in the head of the document, before the html body is parsed.
...along the way, you saw a few code
examples and learned how javascript fits in with the rest of the code on your website, amongst other things.
...in the next article, we will plunge straight into the practical, getting you to jump straight in and build your own javascript
examples.
Aprender y obtener ayuda - Learn web development
many mdn web docs reference pages provide interactive
examples too, where you can alter the code and see how the live result changes.
... and there is also nothing wrong with creating your own code
examples on your computer, or in an online code editor like jsbin, codepen, or glitch.
... when you find solutions to such problems, it is worth writing down notes on what you did, and keeping some minimal code
examples in a directory somewhere so you can look back on previous work.
...other good
examples include: mdn discourse sitepoint forums webdeveloper.com forums however, it also makes sense to find useful groups on social networking sites such as twitter or facebook.
Introduction to the server side - Learn web development
server-side code can be written in any number of programming languages —
examples of popular server-side web languages include php, python, ruby, c#, and nodejs(javascript).
... real world
examples include: social networks like facebook allow users to fully control their own data but only allow their friends to view or comment on it.
... note: consider other real
examples where access to content is controlled.
... a few
examples include: facebook and twitter send emails and sms messages to notify you of new communications.
Setting up your own test automation environment - Learn web development
for more complete details, you should consult the selenium-webdriver javascript api reference for a detailed reference, and the selenium main documentation's selenium webdriver and webdriver: advanced usage pages, which contain multiple
examples to learn from written in different languages.
...you can see useful common
examples starting at getting text values on the webdriver docs.
... in addition, we should mention test results/reporting — we've been reporting results in our above
examples using simple console.log() statements, but this is all done in javascript, so you can use whatever test running and reporting system you want, be it mocha, chai, or some other tool.
... note: saucelabs-sample-test-frameworks contains several useful
examples showing how to set up different combinations of test/assertion tools.
Sqlite.jsm
examples open, execute, close in this example, we open a connection, execute a simple statement, then close the connection.
... bound parameters here are some
examples demonstrating bound parameters.
... let datatoinsert = [ {parama: "foo", paramb: "bar"}, {parama: "biz", paramb: "baz"}, {parama: "yo", paramb: "ho"}, ]; async function doinsert() { for (let data of datatoinsert) { await conn.executecached("insert into mytable values (:parama, :paramb)", data); } }); transactions these
examples demonstrate how transactions work.
...}); selecting and returning data these
examples demonstrate how to access the data that is returned.
NSS API Guidelines
examples of these data in structures may include things like the pkcs #7 contentinfo structure.
...
examples of hash tables can be found in security/nss/lib/certdb/pcertdb.c lock over the entire search: for small linked listed, queues, or arrays, you can lock over the entire search.
...
examples of the previous strategies can be found in security/nss/lib/pk11wrap/pk11slot.c.
...
examples: pk11_slotgetseries(), pk11_symkeygetseries(), cert_certificateextractpublickey() parameter ordering most functions will have a 'natural' ordering for parameters.
Introduction to the DOM - Web APIs
dom and javascript the short example above, like nearly all of the
examples in this reference, is javascript.
...these common apis are used in the longer
examples in the dom
examples chapter at the end of this book.
... there are some cases, however, when the
examples are more concise.
... to run
examples that only demonstrate the basic relationship of the interface to the html elements, you may want to set up a test page in which interfaces can be easily accessed from scripts.
KeyboardEvent - Web APIs
examples include alphanumeric keys on the standard pc 101 us keyboard, the numlock key, and the space bar.
...
examples include the left control key, the left command key on a macintosh keyboard, or the left shift key.
...
examples include the right shift key and the right alt key (option on a mac keyboard).
...
examples include the digits on the numeric keypad, the keypad's enter key, and the decimal point on the keypad.
Using the User Timing API - Web APIs
a live version of the
examples is available on github, as is the source code.
...the following
examples shows how to use each of these methods (performance.getentries(), performance.getentriesbytype(entrytype), and performance.getentriesbyname(name, entrytype) ) to retrieve one or more marks.
...the following
examples shows how to use each of these methods (performance.getentries(), performance.getentriesbytype(entrytype), and performance.getentriesbyname(name, entrytype)) to retrieve one or more measures.
...the following
examples shows both uses of this method.
WebGL model view projection - Web APIs
in the previous
examples the corners of the cube occasionally get clipped.
...the math also starts to get a bit more involved and won't be fully explained in these
examples.
... in short, it combines dividing by w (as done with the previous
examples) with some ingenious manipulations based on similar triangles.
...in these
examples, that's the window's width divided by the window height.
Visualizations with Web Audio API - Web APIs
note: you can find working
examples of all the code snippets in our voice-change-o-matic demo.
... let's go on to look at some specific
examples.
... draw(); this code gives us a result like the following: note: the
examples listed in this article have shown usage of analysernode.getbytefrequencydata() and analysernode.getbytetimedomaindata().
... for working
examples showing analysernode.getfloatfrequencydata() and analysernode.getfloattimedomaindata(), refer to our voice-change-o-matic-float-data demo (see the source code too) — this is exactly the same as the original voice-change-o-matic, except that it uses float data, not unsigned byte data.
Using XMLHttpRequest - Web APIs
examples of both common and more obscure use cases for xmlhttprequest are included.
...*/ } oreq.open("get", url); oreq.responsetype = "arraybuffer"; oreq.send(); for more
examples check out the sending and receiving binary data page monitoring progress xmlhttprequest provides the ability to listen to various events that can occur while the request is being processed.
...if you are using the post method the server will receive a string similar to one of the following three
examples, depending on the encoding type you are using: method: post; encoding type: application/x-www-form-urlencoded (default): content-type: application/x-www-form-urlencoded foo=bar&baz=the+first+line.%0d%0athe+second+line.%0d%0a method: post; encoding type: text/plain: content-type: text/plain foo=bar baz=the first line.
...for
examples, and explanations of how one can utilize formdata with xmlhttprequests, see the using formdata objects page.
Text labels and names - Accessibility
examples the following example show a simple image map (taken from h24: providing text alternatives for the area elements of image maps): <img src="welcome.gif" usemap="#map1" alt="areas in the library.
...
examples the following example shows a simple dialog box, defined as such using role="dialog" and labelled using aria-labelledby.
...
examples the title for the reference article about the <title> element is as follows: <title><title>: the document title element - html: hypertext markup language</title> another example might look like so: <title>fill in your details to register — mygov services</title> to help the user, you can update the page title value to reflect significant page state changes (such as form validation pr...
...
examples <form> <fieldset> <legend>choose your favorite monster</legend> <input type="radio" id="kraken" name="monster"> <label for="kraken">kraken</label><br/> <input type="radio" id="sasquatch" name="monster"> <label for="sasquatch">sasquatch</label><br/> <input type="radio" id="mothman" name="monster"> <label for="mothman">mothman</label> </fieldset> </form> you can...
Realizing common layouts using CSS Grid Layout - CSS: Cascading Style Sheets
as you can see from this set of
examples, there is often more than one way to achieve the result you want with grid layout.
... further exploration the best way to learn to use grid layout is to continue to build
examples like the ones we have covered here.
...don’t forget to find
examples that are impossible to build with current methods.
... for additional common layout patterns see grid by example, where there are many smaller
examples of grid layout and also some larger ui patterns and full page layouts.
box-decoration-break - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... formal definition initial valuesliceapplies toall elementsinheritednocomputed valueas specifiedanimation typediscrete formal syntax slice | clone
examples inline box fragments an inline element that contains line breaks styled with: .example { background: linear-gradient(to bottom right, yellow, green); box-shadow: 8px 8px 10px 0px deeppink, -5px -5px 5px 0px blue, 5px 5px 15px 0px yellow; padding: 0em 1em; border-radius: 16px; border-style: solid; margin-left: 10px; font: 24px sans-serif; line-height: 2; } ...
...results in: you can try the two inline
examples above in your browser.
... you can try the block
examples above in your browser.
Applying color to HTML elements using CSS - HTML: Hypertext Markup Language
while we won't use every single property mentioned previously, we'll look at a couple of
examples.
... a few
examples (all free to use as of the time this list was last revised): mdn's color picker tool paletton adobe color cc online color wheel when designing your palette, be sure to keep in mind that in addition to the colors these tools typically generate, you'll probably also need to add some core neutral colors such as white (or nearly white), black (or nearly black), and some number of shades of gra...
...lots of good
examples of martian coloration there.
...it's easy to go too far in one way or another so be sure to get feedback on your colors once you've selected them and have
examples of them in use available.
<input type="checkbox"> - HTML: Hypertext Markup Language
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... for example, in the following demo we include multiple checkboxes to allow the user to select their interests (see the full version in the
examples section).
...ow example: <fieldset> <legend>choose your interests</legend> <div> <input type="checkbox" id="coding" name="interest" value="coding" checked> <label for="coding">coding</label> </div> <div> <input type="checkbox" id="music" name="interest" value="music"> <label for="music">music</label> </div> </fieldset> providing a bigger hit area for your checkboxes in the above
examples, you may have noticed that you can toggle a checkbox by clicking on its associated <label> element as well as on the checkbox itself.
...
examples the following example is an extended version of the "multiple checkboxes" example we saw above — it has more standard options, plus an "other" checkbox that when checked causes a text field to appear to enter a value for the "other" option.
<input type="file"> - HTML: Hypertext Markup Language
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...see htmlinputelement.webkitdirectory for additional details and
examples.
...some
examples: accept="image/png" or accept=".png" — accepts png files.
...
examples in this example, we'll present a slightly more advanced file chooser that takes advantage of the file information available in the htmlinputelement.files property, as well as showing off a few clever tricks.
itemprop - HTML: Hypertext Markup Language
examples the example below shows the source for a set of elements marked up with itemprop attributes, followed by a table showing the resulting structured data.
... same structured data marked up in two different ways there is no semantic difference between 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, hav...
... names
examples item itemprop name itemprop value itemprop country ireland itemprop option 2 itemprop https://www.flickr.com/photos/nlireland/6992065114/ ring of kerry itemprop img https://www.flickr.com/photos/nlireland/6992065114/ itemprop website flickr itemprop (token) (token) token...
...v> the following is equivalent <div itemscope> <p itemprop="b">test</p> <p itemprop="a">1</p> <p itemprop="a">2</p> </div> as is the following <div itemscope> <p itemprop="a">1</p> <p itemprop="b">test</p> <p itemprop="a">2</p> </div> and the following <div id="x"> <p itemprop="a">1</p> </div> <div itemscope itemref="x"> <p itemprop="b">test</p> <p itemprop="a">2</p> </div> other
examples html <dl itemscope itemtype="http://vocab.example.net/book" itemid="urn:isbn:0-330-34032-8"> <dt>title <dd itemprop="title">the reality dysfunction <dt>author <dd itemprop="author">peter f.
Grammar and types - JavaScript
some
examples of legal names are number_hits, temp99, $credit, and _name.
... /** * example 1 */ console.log(x === undefined); // true var x = 3; /** * example 2 */ // will return a value of undefined var myvar = 'my value'; (function() { console.log(myvar); // undefined var myvar = 'local value'; })(); the above
examples will be interpreted the same as: /** * example 1 */ var x; console.log(x === undefined); // true x = 3; /** * example 2 */ var myvar = 'my value'; (function() { var myvar; console.log(myvar); // undefined myvar = 'local value'; })(); because of hoisting, all var statements in a function should be placed as near to the top of the function as possible.
... some
examples of numeric literals are: 0, 117, -345, 123456789123456789n (decimal, base 10) 015, 0001, -0o77, 0o777777777777n (octal, base 8) 0x1123, 0x00111, -0xf1a7, 0x123456789abcdefn (hexadecimal, "hex" or base 16) 0b11, 0b0011, -0b11, 0b11101001010101010101n (binary, base 2) for more information, see numeric literals in the lexical grammar reference.
... the following are
examples of string literals: 'foo' "bar" '1234' 'one line \n another line' "john's cat" you can call any of the string object's methods on a string literal value.
Functions - JavaScript
for more
examples and explanations, see also the javascript guide about functions.
... as we can see, both
examples do not start with the function keyword.
... // source element x = 10; // not a source element function boo() {} // not a source element } function foo() { // source element var y = 20; // source element function bar() {} // source element while (y === 10) { // source element function blah() {} // not a source element y++; // not a source element } }
examples // function declaration function foo() {} // function expression (function bar() {}) // function expression x = function hello() {} if (x) { // function expression function world() {} } // function declaration function a() { // function declaration function b() {} if (0) { // function expression function c() {} } } block-level functions in strict mode, star...
... a safer way to define functions conditionally is to assign a function expression to a variable: var zero; if (shoulddefinezero) { zero = function() { console.log("this is zero."); }; }
examples returning a formatted number the following function returns a string containing the formatted representation of a number padded with leading zeros.
Date.parse() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... other
examples: new date('foo-bar 2014').tostring(); // returns: "invalid date" date.parse('foo-bar 2014'); // returns: nan differences in assumed time zone this section contains implementation-specific behavior that can be inconsistent across implementations.
...
examples using date.parse() the following calls all return 1546300800000.
... if ipodate is an existing date object, it can be set to august 9, 1995 (local time) as follows: ipodate.settime(date.parse('aug 9, 1995')); some other
examples of parsing non-standard date strings: date.parse('aug 9, 1995'); returns 807937200000 in time zone gmt-0300, and other values in other time zones, since the string does not specify a time zone and is not iso format, therefore the time zone defaults to local.
String.prototype.substring() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using substring() the following example uses substring() to display characters from the string 'mozilla': let anystring = 'mozilla' // displays 'm' console.log(anystring.substring(0, 1)) console.log(anystring.substring(1, 0)) // displays 'mozill' console.log(anystring.substring(0, 6)) // displays 'lla' console.log(anystring.substring(4)) console.log(anystring.substring(4, 7)) console.log(an...
...this method may be easier to remember, given that you don't need to know the starting and ending indices as you would in the above
examples.
... console.log(text.slice(-5, 2)) // => "" console.log(text.slice(-5, -2)) // => "zil" see the slice() page for more
examples with negative numbers.
Iteration protocols - JavaScript
}, [symbol.iterator]: function() { return this; } };
examples using the iteration protocols a string is an example of a built-in iterable object: let somestring = 'hi'; console.log(typeof somestring[symbol.iterator]); // "function" string's default iterator returns the string's code points one by one: let iterator = somestring[symbol.iterator](); console.log(iterator + ''); // "[object string iterator]" console.log(iterator.next()); // { value: "h", d...
...{ value: 'bye', done: (this._first = false) } : { done: true } }, _first: true }; }; notice how redefining @@iterator affects the behavior of built-in constructs that use the iteration protocol: console.log([...somestring]); // ["bye"] console.log(somestring + ''); // "hi" iterable
examples built-in iterables string, array, typedarray, map, and set are all built-in iterables, because each of their prototype objects implements an @@iterator method.
...some
examples include: new map([iterable]) new weakmap([iterable]) new set([iterable]) new weakset([iterable]) new map([[1, 'a'], [2, 'b'], [3, 'c']]).get(2); // "b" let myobj = {}; new weakmap([ [{}, 'a'], [myobj, 'b'], [{}, 'c'] ]).get(myobj); // "b" new set([1, 2, 3]).has(3); // true new set('123').has('2'); // true new weakset(function* () { yield {} yield myobj yield {} }()).has(myobj); // true see also promise.all(iterable) promise...
... using one is likely to result in runtime errors or buggy behavior: let nonwellformediterable = {}; nonwellformediterable[symbol.iterator] = () => 1; [...nonwellformediterable]; // typeerror: [] is not a function iterator
examples simple iterator function makeiterator(array) { let nextindex = 0 return { next: function() { return nextindex < array.length ?
Making PWAs work offline with Service workers - Progressive web apps (PWAs)
registering the service worker we'll start by looking at the code that registers a new service worker, in the app.js file: note : we're using the es6 arrow functions syntax in the service worker implementation if('serviceworker' in navigator) { navigator.serviceworker.register('./pwa-
examples/js13kpwa/sw.js'); }; if the service worker api is supported in the browser, it is registered against the site using the serviceworkercontainer.register() method.
... var cachename = 'js13kpwa-v1'; var appshellfiles = [ '/pwa-
examples/js13kpwa/', '/pwa-
examples/js13kpwa/index.html', '/pwa-
examples/js13kpwa/app.js', '/pwa-
examples/js13kpwa/style.css', '/pwa-
examples/js13kpwa/fonts/graduate.eot', '/pwa-
examples/js13kpwa/fonts/graduate.ttf', '/pwa-
examples/js13kpwa/fonts/graduate.woff', '/pwa-
examples/js13kpwa/favicon.ico', '/pwa-
examples/js13kpwa/img/js13kgames.png', '/pwa-
examples/js13kpwa/img/bg.png', '/pwa...
...-
examples/js13kpwa/icons/icon-32.png', '/pwa-
examples/js13kpwa/icons/icon-64.png', '/pwa-
examples/js13kpwa/icons/icon-96.png', '/pwa-
examples/js13kpwa/icons/icon-128.png', '/pwa-
examples/js13kpwa/icons/icon-168.png', '/pwa-
examples/js13kpwa/icons/icon-192.png', '/pwa-
examples/js13kpwa/icons/icon-256.png', '/pwa-
examples/js13kpwa/icons/icon-512.png' ]; next, the links to images to be loaded along with the content from the data/games.js file are generated in the second array.
...the version number in the cache name is key to this: var cachename = 'js13kpwa-v1'; when this updates to v2, we can then add all of our files (including our new files) to a new cache: contenttocache.push('/pwa-
examples/js13kpwa/icons/icon-32.png'); // ...
How to make PWAs re-engageable using Notifications and Push - Progressive web apps (PWAs)
the technology is still at a very early stage — some working
examples use the google cloud messaging platform, but are being rewritten to support vapid (voluntary application identification), which offers an extra layer of security for your app.
... you can examine the service workers cookbook
examples, try to set up a push messaging server using firebase, or build your own server (using node.js for example).
... feel free to explore the rest of the
examples in the service worker cookbook if you want to know how they are handled — the full source code is available on github.
... there's a big collection of working
examples showing general use, but also web push, caching strategies, performance, working offline, and more.
Same-origin policy - Web security
(a "tuple" is a set of items that together comprise a whole — a generic form for double/triple/quadruple/quintuple/etc.) the following table gives
examples of origin comparisons with the url http://store.company.com/dir/page.html: url outcome reason http://store.company.com/dir2/other.html same origin only the path differs http://store.company.com/dir/inner/another.html same origin only the path differs https://store.company.com/page.html failure different protocol http://store.co...
...
examples are links, redirects, and form submissions.
...(
examples are listed below.) cross-origin reads are typically disallowed, but read access is often leaked by embedding.
... here are some
examples of resources which may be embedded cross-origin: javascript with <script src="…"></script>.
Finding window handles - Archive of obsolete content
os specific
examples using javascript (js-ctypes) nsibasewindow -> nativehandle in all of the
examples below, the native handle to the most recent navigator:browser is obtained and then it is focused.
...libgtk-x11-2.0.so.0'); var gtk_widget_get_window = gtk.declare('gtk_widget_get_window', ctypes.default_abi, gdkwindow.ptr, gtkwidget.ptr); // for getgdkwindowfromgtkwindow var gtkwidgetptr = ctypes.cast(gtkwinptr, gtkwidget.ptr); var backto_gdkwinptr = gtk_widget_get_window(gtkwidgetptr); working with xid xid to gdkwindow* // soon to come xid to gtkwindow* // soon to come now onto the
examples!
...
examples gdk components.utils.import('resource://gre/modules/services.jsm'); var browserwindow = services.wm.getmostrecentwindow('navigator:browser'); if (!browserwindow) { throw new error('no browser window found'); } var basewindow = browserwindow.queryinterface(ci.nsiinterfacerequestor) .getinterface(ci.nsiwebnavigation) .queryinterface(ci.nsidocshelltreeitem) .treeowner .queryinterface(ci.nsiinterfacerequestor) .getinterface(ci.nsibasewindow); var gdkwindowptrstring = basewindow.nativehandle; components.utils.import('resource://gre/modules/ctypes.jsm'); var gdk = ctypes.open('libgdk-x11-2.0.so.0'); // types let guint32 = ctypes.uint3...
How to convert an overlay extension to restartless - Archive of obsolete content
step 1: use services.jsm if you load one of mozilla's internal jsm files, for example services.jsm, you'll do so via privileged javascript code like this: components.utils.import("resource://gre/modules/services.jsm"); from here on out, it is assumed you've imported services.jsm somewhere at the top of whatever file you're in and will be using it in all code
examples.
... the
examples will also assume that you know how to properly add instructions to your add-on's chrome.manifest to add and remove resource, chrome, locale, & etc.
...tom 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.
XPCOM Objects - Archive of obsolete content
using xpcom components is relatively simple, as you've seen in previous
examples.
...you'll usually know what string to use by reading
examples and documentation.
... we included a constant, an attribute and a method to display
examples of the 3, but this is clearly an overly elaborate way to keep a simple counter.
Menu - Archive of obsolete content
the api is fairly comprehensive, so you may want to start by reading through some
examples.
...
examples: "a[href]", "a[href] > img", "a[href], img".
...
examples before running any
examples, import the api from the future: jetpack.future.import("menu"); snippets add a single, static menuitem to the jetpack menu that doesn't do anything: jetpack.menu.add("two drink holders and a captain's chair"); add a menuitem to the jetpack menu that displays the current date and time each time it's opened: jetpack.menu.add(function () new date().tostring()); click a...
Priority Content - Archive of obsolete content
mathieu deaudelin 15:22, 17 may 2005 (pdt) mostly completed: netscape gecko compatibility handbook original: netscape gecko compatibility handbook wiki location: gecko compatibility handbook migrators: mathieu deaudelin there are inline
examples on this page that cannot be migrated.
...dependant on: updating dhtml web pages for next generation browsers on devedge the tune-up wizard (see below, in the wishlist section) mostly completed: popup window controls devedge article migrators: mathieu deaudelin there are inline
examples on this page that cannot be migrated.
...keller equivalents security developer central -> security plugins central -> plugins devedge community -> mozilla web developer community notes from devmo wishlist devedge toolbox tools on devedge
examples on devedge started: devedge sidebar completed: standards-compliant authoring tools on devedge mostly completed: tools:validators on devedge dependant on the sidebar tabs and the tune-up wizard.
Remote debugging - Archive of obsolete content
examples: 367650, 374356, 393325, 418139 debugging over irc find the developer on irc and explain that you've caught the bug in a debugger.
...
examples: 391851 share your computer with remote desktop offer to let a developer control your computer using remote desktop software such as vnc or fog creek copilot.
...
examples: 496391, 476241 ...
The Implementation of the Application Object Model - Archive of obsolete content
examples of these interfaces include nsidomelement, nsidomnode, nsixmlcontent, and nsicontent.
...
examples of tags that can reference local data are menu, menuitem, menubar, toolbox, toolbar, treebody, and treeitem.
...todo: more
examples talk about data sources original document information written by: dave hyatt last modified on: 1/31/99 ...
menupopup - Archive of obsolete content
« xul reference home [
examples | attributes | properties | methods | related ] a container used to display the contents of a popup menu.
... attributes ignorekeys, left, onpopuphidden, onpopuphiding, onpopupshowing, onpopupshown, position, top properties accessibletype, anchornode, popupboxobject, position, state, triggernode methods hidepopup, moveto, openpopup, openpopupatscreen, setconsumerollupevent, showpopup, sizeto
examples the following example shows how a menupopup may be attached to a menulist.
... for more details, including
examples, please see popup positioning top type: integer overrides the vertical position of the popup specified by the showpopup method.
panel - Archive of obsolete content
« xul reference home [
examples | attributes | properties | methods | related ] a panel is a used as a temporary floating popup window that may contain any type of content.
... attributes backdrag, close, consumeoutsideclicks, fade, flip, ignorekeys, label, left, level, noautofocus, noautohide, norestorefocus, onpopuphidden, onpopuphiding, onpopupshowing, onpopupshown, position, titlebar, top, type properties accessibletype, label, popupboxobject, popup, state methods hidepopup, moveto, openpopup, openpopupatscreen, sizeto
examples the following example shows how a panel may be attached to a label.
... for more details, including
examples, please see popup positioning titlebar type: string set the panel's titlebar attribute to the value normal to display a panel with a titlebar.
preference - Archive of obsolete content
« xul reference home [
examples | attributes | properties | methods | related ] declares a preference that may be adjusted in a prefpane.
... attributes disabled, instantapply, inverted, name, onchange, readonly, tabindex, type properties defaultvalue, disabled, hasuservalue, inverted, locked, name, preferences, readonly, tabindex, type, value, valuefrompreferences methods reset
examples <preferences> <preference id="pref_id" name="preference.name" type="int"/> </preferences> see preferences system for a complete example.
... related preferences system documentation: introduction: getting started |
examples | troubleshooting reference: prefwindow | prefpane | preferences | preference | xul attributes ...
preferences - Archive of obsolete content
« xul reference home [
examples | attributes | properties | methods | related ] overview <preferences> is a container for <preference> elements.
...
examples <preferences> <preference id="pref_one" name="extensions.myextension.one" type="bool"/> <preference id="pref_two" name="extensions.myextension.two" type="string"/> ...
...amenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata related preferences system documentation: introduction: getting started |
examples | troubleshooting reference: prefwindow | prefpane | preferences | preference | xul attributes ...
prefpane - Archive of obsolete content
« xul reference home [
examples | attributes | properties | methods | related ] a single preference panel in a prefwindow.
... attributes helpuri, image, label, onpaneload, selected, src properties image, label, preferenceelements, preferences, selected, src
examples methods preferenceforelement <prefpane id="panegeneral" label="general" src="chrome://path/to/paneoverlay.xul"/> or <prefpane id="panegeneral" label="general" onpaneload="ongeneralpaneload(event);"> <preferences> <preference id="pref_one" name="extensions.myextension.one" type="bool"/> ...
....js"> <script type="application/javascript" src="chrome://myext/content/script1.js"> </prefwindow> when opening a dialog with multiple panes you must include the toolbar feature in the call to opendialog, for example: window.opendialog("chrome://example/content/prefwin.xul", "", "chrome,toolbar"); related prefwindow preferences system documentation: introduction: getting started |
examples | troubleshooting reference: prefwindow | prefpane | preferences | preference | xul attributes ...
prefwindow - Archive of obsolete content
« xul reference home [
examples | attributes | properties | methods | related ] a specialized window used for preference dialogs.
...n, buttondir, buttonorient, buttonpack, buttons, defaultbutton, lastselected, onbeforeaccept, ondialogaccept, ondialogcancel, ondialogdisclosure, ondialoghelp, onload, onunload, title, type properties buttons, currentpane, defaultbutton, lastselected, preferencepanes, type methods acceptdialog, addpane, canceldialog, centerwindowonscreen, getbutton, opensubdialog, openwindow, showpane
examples <?xml version="1.0"?> <?xml-stylesheet href="chrome://global/skin/" type="text/css"?> <prefwindow xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <prefpane id="saveoptions" label="backups"> <preferences> <preference id="pref-backup" name="myapp.mybackups" type="bool"/> <preference id="pref-backupduration" name="myapp.mybackups.duration" type="int"/> <...
...ld not: <prefwindow> <script src="config.js"/> <prefpane label="pane1" src="pane1.xul"/> <prefpane label="pane2" src="pane2.xul"/> </prefwindow> should: <prefwindow> <prefpane label="pane1" src="pane1.xul"/> <prefpane label="pane2" src="pane2.xul"/> <script src="config.js"/> </prefwindow> related prefpane preferences system documentation: introduction: getting started |
examples | troubleshooting reference: prefwindow | prefpane | preferences | preference | xul attributes ...
toolbarbutton - Archive of obsolete content
« xul reference home [
examples | attributes | properties | methods | related ] a button that appears on a toolbar.
... attributes accesskey, autocheck, checkstate, checked, command, crop, dir, disabled, dlgtype, group, image, label, oncommand, open, orient, tabindex, title, type, validate properties accesskey, accessibletype, autocheck, checkstate, checked, command, crop, dir, disabled, dlgtype, group, image, label, open, orient, tabindex, type
examples <toolbar id="test-toolbar"> <toolbarbutton accesskey="p" label="plain"/> <toolbarbutton accesskey="c" label="checkbox" type="checkbox"/> <toolbarbutton accesskey="b" label="menu-button" type="menu-button"> <menupopup> <menuitem label="menu item 1"/> <menuitem label="menu item 2"/> </menupopup> </toolbarbutton> <toolbarbutton accesskey="m" label="menu" type="menu">...
...
examples: type value <toolbarbutton > menu menu-button checkbox radio validate type: one of the values below this attribute indicates whether to load the image from the cache or not.
tooltip - Archive of obsolete content
« xul reference home [
examples | attributes | properties | methods | related ] this element is used for the tooltip popups.
... attributes crop, default, label, noautohide, onpopuphidden, onpopuphiding, onpopupshowing, onpopupshown, page, position properties accessibletype, label, popupboxobject, position, state methods hidepopup, moveto, openpopup, openpopupatscreen, showpopup, sizeto
examples <tooltip id="moretip" orient="vertical" style="background-color: #33dd00;"> <label value="click here to see more information"/> <label value="really!" style="color: red;"/> </tooltip> <vbox> <button label="simple" tooltiptext="a simple popup"/> <button label="more" tooltip="moretip"/> </vbox> attributes crop type: one of the values below if the label of the el...
... for more details, including
examples, please see popup positioning properties accessibletype type: integer a value indicating the type of accessibility object for the element.
tree - Archive of obsolete content
« xul reference home [
examples | attributes | properties | methods | related ] a container which can be used to hold a tabular or hierarchical set of rows of elements.
...attributes disablekeynavigation, disabled, editable, enablecolumndrag, flags, hidecolumnpicker, onselect, rows, seltype, statedatasource, tabindex, treelines properties accessibletype, builderview, columns, contentview, currentindex, disablekeynavigation, disabled, editingcolumn, editingrow, enablecolumndrag, firstordinalcolumn, inputfield, seltype, selstyle, tabindex, treeboxobject, view
examples a tree with several columns <tree flex="1" rows="2"> <treecols> <treecol id="sender" label="sender" flex="1"/> <treecol id="subject" label="subject" flex="2"/> </treecols> <treechildren> <treeitem> <treerow> <treecell label="joe@somewhere.com"/> <treecell label="top secret plans"/> </treerow> </treeitem> <treeitem> <treerow> ...
... interfaces nsiaccessibleprovider, nsidomxultreeelement, nsidomxulmultiselectcontrolelement script
examples to have alternating colors for each row, use the style rules like the following: treechildren::-moz-tree-row(selected) { background-color: #ffffaa; } treechildren::-moz-tree-row(odd) { background-color: #eeeeee; } treechildren::-moz-tree-row(odd, selected) { background-color: #ffffaa; } treechildren::-moz-tree-cell-text(selected) { color: #000000; } treechildren::-moz-tree-cell-text(odd, select...
Introduction to Public-Key Cryptography - Archive of obsolete content
examples: a bank gives a customer a client ssl certificate that allows the bank's servers to identify that customer and authorize access to the customer's accounts.
...
examples: a company deploys combined s/mime and ssl certificates solely for the purpose of authenticating employee identities, thus permitting signed email and client ssl authentication but not encrypted email.
...three
examples of binary formats are der-encoded certificates, pkcs #7 certificate chains, and netscape certificate sequence.
Browser Detection and Cross Browser Support - Archive of obsolete content
geckogetrv()
examples branch tag geckogetrv() 0.9.2 0.0902 0.9.4 0.0904 0.9.4.1 0.090401 0.9.4.2 0.090402 1.0.1 1.0001 1.0.2 1.0002 2.2.0 2.02 2.12.36 2.1236 geckogetrv() returns values which can be compared using greater than, less than, etc.
...6.1 netscape6 6.1 netscape 6.2 netscape6 6.2 netscape 6.2.1 netscape6 6.2.1 netscape 6.2.2 netscape6 6.2.2 netscape 6.2.3 netscape6 6.2.3 compuserve 7.0 cs 2000 7.0 7.0 netscape 7 preview release 1 netscape 7.0b1 netscape 7.0 netscape 7.0 netscape 7.01 netscape 7.01
examples if you are like me, you learn best from
examples.
...
examples from devedge * xbdom * xbmarquee * xbpositionableelement * xbanimatedelement conclusion as we have seen in this article, the browser detection story is still quite complicated due to differences between the modern browsers such as gecko/internet explorer 6 and the older or non-standard browsers such as netscape navigator 4.
Back to the Server: Server-Side JavaScript On The Rise - Archive of obsolete content
let's take a look at various ssjs implementations and some
examples of putting them to use.
...let's take a tour through some of the top features of jaxer through code
examples.
... listing 6 - creating the user interface <link href="/jaxer_
examples/js/ext-2.1/resources/css/ext-all.css" type="text/css" rel="stylesheet"/> <script src="/jaxer_
examples/js/ext-2.1/adapter/ext/ext-base.js"/> <script src="/jaxer_
examples/js/ext-2.1/ext-all.js"/> <link href="/jaxer_
examples/css/main.css" type="text/css" rel="stylesheet"/> <script runat="both" src="/jaxer_
examples/js/validatecomments.js"/> <script> var txt_name; var txt_email; var txt_message; va...
XForms Custom Controls - Archive of obsolete content
this is required for all
examples here to run!
...so you can always refer to our source code to get some great
examples of how xforms controls can be written.
...example a collection of custom control
examples can be found on xforms:custom controls
examples, and you can also see the blog post "understanding xforms: customization".
Mobile accessibility - Learn web development
here are a few
examples of the options available: speaking rate: change the speaking rate.
... note: you can also see fully functional
examples showing how to implement different control mechanisms at implementing game control mechanisms.
...see html5-form-
examples.html for some
examples (see the html5 form
examples live) — try loading these and manipulating them on mobile devices.
Advanced styling effects - Learn web development
you can find the
examples in this section at box-shadow.html (see the source code too).
... you can find a lot more
examples than are available here in our blend-modes.html example page (see source code), and on the <blend-mode> reference page.
... background-blend-mode again, let's look at some
examples so we can understand this better.
Pseudo-classes and pseudo-elements - Learn web development
take a look at some other
examples on mdn: :last-child :only-child :invalid note: it is valid to write pseudo-classes and elements without any element selector preceding them.
...
examples include: :hover — mentioned above; this only applies if the user moves their pointer over an element, typically a link.
... ::pseudo-element-name note: some early pseudo-elements used the single colon syntax, so you may sometimes see this in code or
examples.
Introduction to CSS layout - Learn web development
grid-template-columns: 1fr 1fr 1fr; grid-template-rows: 100px 100px; grid-gap: 10px; } .box1 { grid-column: 2 / 4; grid-row: 1; } .box2 { grid-column: 1; grid-row: 1 / 3; } .box3 { grid-row: 2; grid-column: 3; } <div class="wrapper"> <div class="box1">one</div> <div class="box2">two</div> <div class="box3">three</div> </div> note: these two
examples are just a small part of the power of grid layout; to find out more see our grid layout article.
... simple positioning example to provide familiarity with these page layout techniques, we'll show you a couple of quick
examples.
... our
examples will all feature the same html, which is as follows: <h1>positioning</h1> <p>i am a basic block level element.</p> <p class="positioned">i am a basic block level element.</p> <p>i am a basic block level element.</p> this html will be styled by default using the following css: body { width: 500px; margin: 0 auto; } p { background-color: rgb(207,232,220); border: 2px solid rgb(79,185,227); padding: 10px; margin: 10px; border-radius: 5px; } the rendered output is as follows: relative positioning relative positioning allows you to offset an item from the position in normal flow it would have by default.
create fancy boxes - Learn web development
we are about to see many
examples, but we will always work on the most simple piece of html possible, a simple element: <div class="fancy">hi!
... before we jump to some practical
examples, let's step back a bit as there are two things you should know about backgrounds.
...if you want to see some crazy
examples, take a look at lea verou's css patterns.
Styling links - Learn web development
default styles the following example illustrates what a link will behave like by default (the css is simply enlarging and centering the text to make it stand out more.) <p><a href="#">a simple link</a></p> p { font-size: 2rem; text-align: center; } note: all the links in the
examples in this page are fake links — a # (hash, or pound sign) is put in place of the real url.
... this is because if the real links were included, clicking on them would break the
examples (you'd end up with an error, or a page loaded in the embedded example that you couldn't get back from.) # just links to the current page.
... the fourth rule — which styles the <a> element — is the most complicated here; let's go through it step by step: as in previous
examples, we start by turning off the default text-decoration and outline — we don't want those spoiling our look.
What do common web layouts contain? - Learn web development
here are some
examples (1 represents header, 2 footer; a main content; b1, b2 things on the side): 1-column layout.
...(even many desktop-users prefer viewing things in small windows rather than full-screen.) the real fun begins when you start mixing them all together: … these are just
examples and you're quite free to lay things out as you want.
... deeper dive let's study some more concrete
examples taken from well-known websites.
The HTML5 input types - Learn web development
see the firefox for android keyboard screenshot below for an example: note: you can find
examples of the basic text input types at basic input
examples (see the source code also).
... let's look at some
examples.
...note that the usage of these types is quite complex, especially considering browser support (see below); to find out the full details, follow the links below to the reference pages for each type, including detailed
examples.
Other form controls - Learn web development
note: you can find
examples of all the drop-down box types on github at drop-down-content.html (see it live also).
...if the value attribute is omitted, as with the
examples above, the content of the <option> element is used as the value.
... note: you can find the
examples from this section on github as other-
examples.html (see it live also).
JavaScript basics - Learn web development
is the standard for introductory programming
examples.) important: if you haven't been following along with the rest of our course, download this example code and use it as a starting point.
... let myvariable = document.queryselector('h1'); all of the above
examples too.
...in the following table you can see some of the simplest operators, along with some
examples to try in the javascript console.
HTML table advanced features and accessibility - Learn web development
to give you some interesting
examples, in the case of a long table you could make the table header and footer repeat on every printed page, and you could make the table body display on a single page and have the contents available by scrolling up and down.
...to check this, open up one of your previous
examples that doesn't include <tbody> and look at the html code in your browser developer tools — you will see that the browser has added this tag for you.
... note: you can check your work against our finished
examples — see items-sold-scope.html (also see this live) and items-sold-headers.html (see this live too).
Making asynchronous programming easier with async and await - Learn web development
you can find both of these
examples on github: simple-fetch-async-await-try-catch.html (see source code) simple-fetch-async-await-promise-catch.html (see source code) awaiting a promise.all() async/await is built on top of promises, so it's compatible with all the features offered by promises.
...let's have a look at some
examples that prove the concept.
... we've got two
examples available — slow-async-await.html (see source code) and fast-async-await.html (see source code).
Graceful asynchronous programming with Promises - Learn web development
later on in the chapter, we'll look at how to write your own promise, but for now, we'll look at some simple
examples that you'll encounter in web apis.
... note: you will probably notice that these
examples are somewhat contrived.
...take our fetchanddecode() function from the previous
examples, for example.
Test your skills: Events - Learn web development
note: in the
examples below, if there is an error in your code it will be outputted into the results panel on the page, to help you try to figure out the answer (or into the browser's javascript console, in the case of the downloadable version).
... we haven't explicitly taught this yet in the course, but you'll have seen some
examples that make use of it, and we'd like you to do some research into what dom apis you need to successfully answer the questions.
... assessment or further help you can practice these
examples in the interactive editors above.
Test your skills: Functions - Learn web development
note: in the
examples below, if there is an error in your code it will be outputted into the results panel on the page, to help you try to figure out the answer (or into the browser's javascript console, in the case of the downloadable version).
... we haven't explicitly taught this yet in the course, but you'll have seen some
examples that make use of it, and we'd like you to do some research into what dom apis you need to successfully answer the questions.
... assessment or further help you can practice these
examples in the interactive editors above.
Introduction to web APIs - Learn web development
examples include jquery, mootools and react.
...
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).
...for example, some of the more modern webapis will only work on pages served over https due to them transmitting potentially sensitive data (
examples include service workers and push).
Handling text — strings in JavaScript - Learn web development
note: try entering the below
examples into your browser's javascript console, to see what results you get.
...many of our
examples still use standard string literals, but we will include more template literals going forward.
... see our template literals reference page for more
examples and details of advanced features.
Adding a new CSS property
see the documentation at the top of the file and the other entries for
examples.
... again, see the documentation at the top of the file and the other entries for
examples, and also see the next section for details about parsing.
... for
examples of how to write this computation code, see other
examples in nsrulenode.cpp.
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 proces...
...for example: nsipromptservice nsifilepicker nsixul* <need more
examples> services some services will not work in frame scripts.
...for example: nsisessionstore nsiwindowmediator <need more
examples> places api the places api can't be used inside a frame script.
Localization content best practices
examples from other languages: gender in german: nouns can be either masculine, feminine or neuter.
...some
examples: ok in english becomes ceart ma-thà in gaelic.
...some
examples: hard-coded strings, implicit grammar structure in the code, lack of plural forms support, ui that breaks with long strings, etc.
Creating localizable web applications
note: most of the code snippets used in the
examples below come from an early version of the getpersonas.com website.
... see
examples of the addons.mozillaorg code at /addons/trunk/site/app/config/language.php and /addons/trunk/site/app/config/language.inc.php.
...
examples include long paragraphs or e-mail bodies.
MathML Demo: <mo> - operator, fence, separator, or accent
here are
examples of the standard latex fences ( x ) [ y ] { 1 } ⟨ t ⟩ ⌊ a ⌋ ⌈ .
...here are some
examples with a bit more stretching ( k 1 2 2 ) [ k 1 2 2 ] { k 1 2 2 } ⟨ k 1 2 2 ⟩ ⌊ k 1 2 2 ⌋ ⌈ k 1 2 2 ⌉ | k 1 2 2 | ∥ k 1 2 2 ∥ and / k 1 2 2 / \ k 1 2 2 \ ↕ k 1 2 2 ↕ ⇕ k 1 2 2 ⇕ ↑ k 1 2 2 ↑ ⇑ k 1 2 2 ⇑ ↓ k 1 2 2 ↓ ⇓ k 1 2 2 ⇓ generally, it is safest to script all attributes that configure an <mo> as a fence (fence, stretchy, symmetric, lspace, rspace).
...some
examples of inline fractions ( 8 - 5 8 ) + [ 1 2 ] + ⌊ 1 2 2 ⌋ + ⌈ 1 x y x + 1 ⌉ + | e - 2 π t θ | with built in fences.
Research and prep
examples from various localizations some
examples from en-us web service provider rationale global search google best user experience and broadest results.
... some
examples from es-es web service provider rationale global search google best user experience and broadest results.
... some
examples from wo web service provider rationale global search google best user experience and broadest results.
nss tech note5
see wrapmechanismlist in security/nss/lib/pk11wrap/pk11slot.c and security/nss/lib/ssl/ssl3con.c for
examples of wrapping mechanisms.
...see wrapmechanismlist in security/nss/lib/pk11wrap/pk11slot.c and security/nss/lib/ssl/ssl3con.c for
examples of wrapping mechanisms.
...see wrapmechanismlist in security/nss/lib/pk11wrap/pk11slot.c and security/nss/lib/ssl/ssl3con.c for
examples of wrapping mechanisms.
Tutorial: Embedding Rhino
fully compilable
examples are provided along the way.
... the
examples live in the rhino/
examples directory in the distribution and in mozilla/js/rhino/
examples in cvs.
...(note that because the java -jar option preempts the rest of the classpath, we can't use that and access the counter class.) $ java -cp "js.jar;
examples" org.mozilla.javascript.tools.shell.main js> defineclass("counter") js> c = new counter(7) [object counter] js> c.count 7 js> c.count 8 js> c.count 9 js> c.resetcount() js> c.count 0 counter's constructors the zero-argument constructor is used by rhino runtime to create instances.
Rhino shell
examples invocation here the shell is invoked three times from the command line.
... js> function test(x) { print("entry"); java.lang.thread.sleep(x*1000); print("exit"); } js> var o = { f : sync(test) }; js> spawn(function() {o.f(5);}); thread[thread-0,5,main] entry js> spawn(function() {o.f(5);}); thread[thread-1,5,main] js> exit entry exit runcommand here are a few
examples of invoking runcommand under linux.
...pt) js: "<stdin>", line 18: uncaught javascript exception: java.io.ioexception: bad_command: not found js> // passing explicit environment to the system shell js> runcommand("sh", "-c", "echo $env1 $env2", { env: {env1: 100, env2: 200}}) 100 200 0 js> // use args option to provide additional command arguments js> var arg_array = [1, 2, 3, 4]; js> runcommand("echo", { args: arg_array}) 1 2 3 4 0
examples for windows are similar: js> // invoke shell command js> runcommand("cmd", "/c", "date /t") 27.08.2005 0 js> // run sort collectiong the output js> var opt={input: "c\na\nb", output: 'sort output:\n'} js> runcommand("sort", opt) 0 js> print(opt.output) sort output: a b c js> // invoke notepad and wait until it exits js> runcommand("notepad") 0 ...
XML Extras
see also: xml in mozilla document.load() a few
examples dealing with xml from mozillazine knowledge base.
... documentation probably the best way to learn how to use these technologies is through
examples.
...if you follow that link to look at the
examples you will need to look at page source for the html documents.
Xptcall Porting Guide
here are
examples of this implementation for win32 and linux x86, netbsd x86, and freebsd.
...here are
examples of this implementation for win32 and linux x86, netbsd x86, and freebsd.
... both of these
examples use inline assembly language.
Using js-ctypes
examples can be found here: bugzilla :: bug 505907 - support c++ calling from jsctypes library search paths if you specify a full path, that path is used to load the library.
...
examples these
examples offer a quick look at how js-ctypes is used.
... see js-ctypes
examples for more intricate
examples.
Break on DOM mutation - Firefox Developer Tools
examples for when this breakpoint is triggered are calling node.appendchild() and node.removechild(), calling childnode.remove() or setting element.innerhtml on one of the subnodes.
...
examples for when this breakpoint is triggered are calling element.setattribute(), element.removeattribute(), and element.classlist.add(), or setting element.id.
...
examples for when this breakpoint is triggered are calling element.remove() or node.removechild() on its parent node.
Applying styles and colors - Web APIs
each of the following
examples describe the same color.
... you'll get a better understanding of what these do by looking at the
examples below.
... screenshotlive sample patterns in one of the
examples on the previous page, we used a series of loops to create a pattern of images.
Document: keypress event - Web APIs
examples of keys that produce a character value are alphabetic, numeric, and punctuation keys.
...
examples of keys that don't produce a character value are modifier keys such as alt, shift, ctrl, or meta.
... interface keyboardevent bubbles yes cancelable yes default action varies: keypress event; launch text composition system; blur and focus events; domactivate event; other event
examples addeventlistener keypress example this example logs the keyboardevent.code value whenever you press a key.
Element: keypress event - Web APIs
examples of keys that produce a character value are alphabetic, numeric, and punctuation keys.
...
examples of keys that don't produce a character value are modifier keys such as alt, shift, ctrl, or meta.
... interface keyboardevent bubbles yes cancelable yes default action varies: keypress event; launch text composition system; blur and focus events; domactivate event; other event
examples addeventlistener keypress example this example logs the keyboardevent.code value whenever you press a key after focussing the <input> element.
MediaDevices.getUserMedia() - Web APIs
plain values are inherently ideal, which means that the first of our resolution
examples above could have been written like this: { audio: true, video: { width: { ideal: 1280 }, height: { ideal: 720 } } } not all constraints are numbers.
...the following are
examples of situations in which getusermedia() is not permitted to be called: a document loaded into a sandboxed <iframe> element cannot call getusermedia() unless the <iframe> has its sandbox attribute set to allow-same-origin.
...
examples width and height this example gives a preference for camera resolution, and assigns the resulting mediastream object to a video element.
Streams API concepts - Web APIs
examples include video streams and tcp/web sockets.
...
examples include a file access operation via a fetch or xhr call.
...you can find more useful ideas and
examples in the spec — see transform streams for ideas, and this web sockets example.
Using readable streams - Web APIs
finding some
examples we will look at various
examples in this article, taken from our dom-
examples/streams repo.
... you can find the full source code there, as well as links to the
examples.
...current chunk = ' + chunk; list2.appendchild(listitem); result += chunk; // read some more, and call this function again return reader.read().then(processtext); }); } closing and cancelling streams we’ve already shown
examples of using readablestreamdefaultcontroller.close() to close a reader.
Streams API - Web APIs
examples we have created a directory of
examples to go along with the streams api documentation — see mdn/dom-
examples/streams.
... the
examples are as follows: simple stream pump: this example shows how to consume a readablestream and pass its data to another.
...
examples from other developers: progress indicators with streams, service workers, & fetch.
SubtleCrypto.importKey() - Web APIs
see the
examples section for more concrete guidance.
... see the
examples section for more concrete guidance.
... a json web key looks something like this (this is an ec private key): { "crv": "p-384", "d": "wouctu7nw4e8_7n5c1-xbjb4xqsb_lizhymsy8mggxuny6q8ncoh9xsiviwlffk_", "ext": true, "key_ops": ["sign"], "kty": "ec", "x": "szrrxmyi8vwfjg1dpunbfcc9jzvjzefh7ulki1ukxaltd7rgwrcffxqygpcwu6aq", "y": "hhuag3ovdzer0uuqnd4pxhqtxp5idgdyhjhl-wlkjngjqaw0rngy5v29-av-ysew" };
examples note: you can try the working
examples on github.
WebGL: 2D and 3D graphics for the web - Web APIs
guides and tutorials below, you'll find an assortment of guides to help you learn webgl concepts and tutorials that offer step-by-step lessons and
examples.
...
examples a basic 2d webgl animation example this example demonstrates the simple animation of a one-color shape.
...the
examples are sorted according to topic and level of difficulty, covering the webgl rendering context, shader programming, textures, geometry, user interaction, and more.
WebSocket: close event - Web APIs
bubbles no cancelable no interface closeevent event handler property onclose
examples you might want to know when the connection has been closed so that you can update the ui or, perhaps, save data about the closed connection.
... given that you have a variable called
examplesocket that refers to an opened websocket, this handler would handle the situation where the socket has been closed.
...
examplesocket.addeventlistener('close', (event) => { console.log('the connection has been closed successfully.'); )}; you can perform the same actions using the event handler property, like this:
examplesocket.onclose = function (event) { console.log('the connection has been closed successfully.'); }; specifications specification status html living standardthe definition of 'websocket close' in that specification.
Using Web Workers - Web APIs
it accepts zero or more uris as parameters to resources to import; all of the following
examples are valid: importscripts(); /* imports nothing */ importscripts('foo.js'); /* imports just "foo.js" */ importscripts('foo.js', 'bar.js'); /* imports two scripts */ importscripts('//example.com/hello.js'); /* you can import scripts from other origins */ the browser loads each listed script and executes it.
... passing data
examples example #1: advanced passing json data and creating a switching system if you have to pass some complex data and have to call many different functions both on the main page and in the worker, you can create a system which groups everything together.
...for example: function fn2workerurl(fn) { var blob = new blob(['('+fn.tostring()+')()'], {type: 'application/javascript'}) return url.createobjecturl(blob) } further
examples this section provides further
examples of how to use web workers.
Using the aria-describedby attribute - Accessibility
the
examples section below provides more information about how to use the attribute in these cases.
...
examples example 1: application landmark descriptions in the example below, an introductory paragraph describes a calendar application.
... <div id="descriptionclose">closing this window will discard any information entered and return you back to the main page</div> working
examples: checkbox example uses aria-describedby tooltip example uses aria-describedby notes the aria-describedby attributed is not designed to reference descriptions on an external resource—since it is an id, it must reference an element in the same dom document.
Using the slider role - Accessibility
see the
examples section below for more information.
...
examples example 1: simple numerical range in the example below, a simple slider is used to select a value between 1 and 100.
... 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 at product combinations additional resources wai-aria specification for the slider role ...
ARIA annotations - Accessibility
below we'll introduce the new features associated with aria annotations, and have a look at some code
examples that show them in action.
... note: you can find all the
examples discussed in this article in a demo file at aria-annotations.
...you’ll see
examples of most of these later on in the article, but briefly: aria-label="" can be set on an element to provide a brief descriptive label when it isn't appropriate to have the label actually appearing in the ui, for example a search input in a horizontal nav bar.
ARIA: article role - Accessibility
see the
examples for specific use cases.
...
examples of appropriate uses of the role="article", or preferably <article>, include blog posts, forum posts, a comment to a forum or blog post, a comment to a comment to a forum or blog post, any an item in a social media feed.
...
examples the restaurant recommendations feed display along with its separate documentation from the wai-aria 1.1 authoring practices feed design pattern specifications specification status accessible rich internet applications (wai-aria) 1.1the definition of 'article' in that specification.
ARIA: listbox role - Accessibility
examples example 1: a single select listbox that uses aria-activedescendant the snippet below shows how the listbox role is added directly into the html source code.
...e="option" id="listbox1-6">periwinkle</div> </div> this could have more easily been handled with the native html <select> and <label> elements <label for="listbox1">select a color:</label> <select id="listbox1"> <option selected>green</option> <option>orange</option> <option>red</option> <option>blue</option> <option>violet</option> <option>periwinkle</option> </select> more
examples scrollable listbox example: single-select listbox that scrolls to reveal more options, similar to html select with size attribute greater than one.
... example listboxes with rearrangeable options:
examples of both single-select and multi-select listboxes with accompanying toolbars where options can be added, moved, and removed.
Cognitive accessibility - Accessibility
examples of timed content include forms, timed reading exercises, and training materials.
...
examples of headings include chapters, sections and subsections of content, and so on.
...
examples of this are checking a checkbox, entering data or changing a select option.
Accessibility documentation index - Accessibility
examples of common problems include e-mail addresses which are not valid, or a name field which does not contain at least a first name or a surname.
...
examples of an article include web log posts, newspaper or magazine articles and use-submitted comments.
... 80 overview accessibility, javascript, landing, needsupdate here's a look at working
examples and best practices in building accessible javascript widgets.
OpenType font features guide - CSS: Cascading Style Sheets
some fonts will have one or more of these features enabled by default (kerning and default ligatures are common
examples), while others are left to the designer or developer to choose to enable in specific scenarios.
... note: the
examples below show the properties and some example combinations, along with the lower-level syntax equivalents.
...you can see
examples of a number of them above, and there are several resources available for finding more of them.
Basic Concepts of grid layout - CSS: Cascading Style Sheets
as we saw in our earlier
examples, once a grid is defined as a parent the child items will lay themselves out in one cell each of the defined grid.
...at the present time, some browsers do not support the unprefixed versions which is why the live
examples in this guide use grid- prefixed versions.
...have a play with the code
examples, and then move onto the next part of this guide where we will really start to dig into the detail of css grid layout.
Grid template areas - CSS: Cascading Style Sheets
.wrapper { grid-template-areas: "hd hd hd hd hd hd hd hd hd" "sd sd main main main main main ft ft"; } } <div class="wrapper"> <div class="header">header</div> <div class="sidebar">sidebar</div> <div class="content">content</div> <div class="footer">footer</div> </div> using grid-template-areas for ui elements many of the grid
examples you will find online make the assumption that you will use grid for main page layout, however grid can be just as useful for small elements as those larger ones.
...however they are part of the specification and it is likely you will come across them in
examples or in use by other developers, even if you choose not to use them.
...as you develop
examples, you are likely to come up with some questions and use cases for things we haven't covered yet.
Line-based placement with CSS Grid - CSS: Cascading Style Sheets
class="wrapper"> <div class="box1">one</div> <div class="box2">two</div> <div class="box3">three</div> <div class="box4">four</div> </div> .box1 { grid-column: 1 / 2; grid-row: 1 / 4; } .box2 { grid-column: 3 / 4; grid-row: 1 / 3; } .box3 { grid-column: 2 / 3; grid-row: 1 / 2; } .box4 { grid-column: 2 / 4; grid-row: 3 / 4; } default spans in the above
examples i specified every end row and column line, in order to demonstrate the properties, however in practice if an item only spans one track you can omit the grid-column-end or grid-row-end value.
...at the present time, some browsers do not support the unprefixed versions, which is why the live
examples in this guide use grid- prefixed versions.
...the following two
examples will create the same grid area.
Logical properties for margins, borders and padding - CSS: Cascading Style Sheets
margin
examples the mapped margin properties of margin-inline-start, margin-inline-end, margin-block-start, and margin-inline-end can be used instead of their physical counterparts.
... padding
examples the mapped padding properties of padding-inline-start, padding-inline-end, padding-block-start, and padding-inline-end can be used instead of their physical counterparts.
... border
examples the border properties are the main reason that logical properties and values seems to have so many properties, as we have the longhands for the color, width, and style of the border on each side of a box, along with the shorthand to set all three at once for each side.
Using CSS transitions - CSS: Cascading Style Sheets
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.
...ansition() { var el = document.queryselector("div.box"); if (el) { el.classname = "box1"; } else { el = document.queryselector("div.box1"); el.classname = "box"; } return el; } var intervalid = window.setinterval(updatetransition, 7000); the shorthand css syntax is written as follows: div { transition: <property> <duration> <timing-function> <delay>; }
examples simple example this example performs a four-second font size transition with a two-second delay between the time the user mouses over the element and the beginning of the animation effect: #delay { font-size: 14px; transition-property: font-size; transition-duration: 4s; transition-delay: 2s; } #delay:hover { font-size: 36px; } multiple animated properties example html content ...
... 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.
Scaling of SVG backgrounds - CSS: Cascading Style Sheets
source image
examples before diving in to look at the results of using different kinds of source images and seeing how they look when used with background-size, it would be helpful to look at a few example source images that have different dimensions and sizing settings.
... svg source scaling
examples now let's see some
examples of what happens as we apply different scaling to these images.
... in each of the
examples below, the enclosing rectangles are 300 pixels wide and 200 pixels tall.
animation-fill-mode - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... formal definition initial valuenoneapplies toall elements, ::before and ::after pseudo-elementsinheritednocomputed valueas specifiedanimation typediscrete formal syntax <single-animation-fill-mode>#where <single-animation-fill-mode> = none | forwards | backwards | both
examples you can see the effect of animation-fill-mode in the following example.
...lass="grows">this just grows.</div> </div> css .demo { border-top: 100px solid #ccc; height: 300px; } @keyframes grow { 0% { font-size: 0; } 100% { font-size: 40px; } } .demo:hover .grows { animation-name: grow; animation-duration: 3s; } .demo:hover .growsandstays { animation-name: grow; animation-duration: 3s; animation-fill-mode: forwards; } see css animations for more
examples.
animation-timing-function - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... a single component">[0,1]>, <number>, <number <a href="/docs/css/value_definition_syntax#brackets" title="brackets: enclose several entities, combinators, and multipliers to transform them as a single component">[0,1]>, <number>)<step-timing-function> = step-start | step-end | steps(<integer>[, <step-position>]?)where <step-position> = jump-start | jump-end | jump-none | jump-both | start | end
examples cubic-bezier
examples <div class="parent"> <div class="ease">ease</div> <div class="easein">ease-in</div> <div class="easeout">ease-out</div> <div class="easeinout">ease-in-out</div> <div class="linear">linear</div> <div class="cb">cubic-bezier(0.2,-2,0.8,2)</div> </div> .parent > div[class] { animation-name: changeme; animation-duration: 10s; animation-iteration-coun...
...a; color: yellow; border: 1px solid orange; } } .ease { animation-timing-function: ease; } .easein { animation-timing-function: ease-in; } .easeout { animation-timing-function: ease-out; } .easeinout { animation-timing-function: ease-in-out; } .linear { animation-timing-function: linear; } .cb { animation-timing-function: cubic-bezier(0.2,-2,0.8,2); } step
examples <div class="parent"> <div class="jump-start">jump-start</div> <div class="jump-end">jump-end</div> <div class="jump-both">jump-both</div> <div class="jump-none">jump-none</div> <div class="start">start</div> <div class="end">end</div> <div class="step-start">step-start</div> <div class="step-end">step-end</div> </div> .parent > div[class] { animation-name: changeme; ani...
animation - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... a single component">[0,1]>, <number>, <number <a href="/docs/css/value_definition_syntax#brackets" title="brackets: enclose several entities, combinators, and multipliers to transform them as a single component">[0,1]>, <number>)<step-timing-function> = step-start | step-end | steps(<integer>[, <step-position>]?)where <step-position> = jump-start | jump-end | jump-none | jump-both | start | end
examples cylon eye <div class="view_port"> <div class="polling_message"> listening for dispatches </div> <div class="cylon_eye"></div> </div> .polling_message { color: white; float: left; margin-right: 2%; } .view_port { background-color: black; height: 25px; width: 100%; overflow: hidden; } .cylon_eye { background-color: red; background-image: linear-gradient(to right, ...
...75%); color: white; height: 100%; width: 20%; -webkit-animation: 4s linear 0s infinite alternate move_eye; animation: 4s linear 0s infinite alternate move_eye; } @-webkit-keyframes move_eye { from { margin-left: -20%; } to { margin-left: 100%; } } @keyframes move_eye { from { margin-left: -20%; } to { margin-left: 100%; } } see using css animations for additional
examples.
background-position - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...] ]where <length-percentage> = <length> | <percentage>
examples positioning background images each of these three
examples uses the background property to create a yellow, rectangular element containing a star image.
... html <div class="exampleone">example one</div> <div class="exampletwo">example two</div> <div class="examplethree">example three</div> css /* shared among all <div>s */ div { background-color: #ffee99; background-repeat: no-repeat; width: 300px; height: 80px; margin-bottom: 12px; } /* these
examples use the `background` shorthand property */ .exampleone { background: url("https://mdn.mozillademos.org/files/11987/startransparent.gif") #ffee99 2.5cm bottom no-repeat; } .exampletwo { background: url("https://mdn.mozillademos.org/files/11987/startransparent.gif") #ffee99 left 4em bottom 1em no-repeat; } /* multiple background images: each image is matched with the corresponding position,...
clamp() - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... note that using clamp() for font sizes, as in these
examples, allows you to set a font-size that grows with the size of the viewport, but doesn't go below a minimum font-size or above a maximum font-size.
... formal syntax clamp( <calc-sum>#{3} )where <calc-sum> = <calc-product> [ [ '+' | '-' ] <calc-product> ]*where <calc-product> = <calc-value> [ '*' <calc-value> | '/' <number> ]*where <calc-value> = <number> | <dimension> | <percentage> | ( <calc-sum> )
examples min, max, and clamp comparison in this example we have a simple responsive example that makes use of min(), max(), and clamp() for some of the sizes.
<color> - CSS: Cascading Style Sheets
examples color value tester in this example we provide a <div> and a text input.
...51, 170, 51, .4) /* 40% opaque green */ rgba(51, 170, 51, .7) /* 70% opaque green */ rgba(51, 170, 51, 1) /* full opaque green */ /* whitespace syntax */ rgba(51 170 51 / 0.4) /* 40% opaque green */ rgba(51 170 51 / 40%) /* 40% opaque green */ /* functional syntax with floats value */ rgba(255, 0, 153.6, 1) rgba(1e2, .5e1, .5e0, +.25e2%) hsl syntax variations /* these
examples all specify the same color: a lavender.
... */ hsl(270,60%,70%) hsl(270, 60%, 70%) hsl(270 60% 70%) hsl(270deg, 60%, 70%) hsl(4.71239rad, 60%, 70%) hsl(.75turn, 60%, 70%) /* these
examples all specify the same color: a lavender that is 15% opaque.
conic-gradient() - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... mdn understanding wcag, guideline 1.1 explanations understanding success criterion 1.1.1 | w3c understanding wcag 2.0
examples gradient at 40-degrees div { width: 100px; height: 100px; } <div></div> div { background-image: conic-gradient(from 40deg, #fff, #000); } off-centered gradient div { width: 100px; height: 100px; } <div></div> div { background: conic-gradient(from 0deg at 0% 25%, blue, green, yellow 180deg); } gradient pie-chart this example uses multi-position color stops, wi...
... } <div></div> div { background: conic-gradient( red 36deg, orange 36deg 170deg, yellow 170deg); border-radius: 50% } checkerboard div { width: 100px; height: 100px; } <div></div> div { background: conic-gradient(#fff 0.25turn, #000 0.25turn 0.5turn, #fff 0.5turn 0.75turn, #000 0.75turn) top left / 25% 25% repeat; border: 1px solid; } more conic-gradient
examples please see using css gradients for more
examples.
display - CSS: Cascading Style Sheets
global /* global values */ display: inherit; display: initial; display: unset; description the individual pages for the different types of value that display can have set on it feature multiple
examples of those values in action — see the syntax section.
...&& list-item<display-internal> = table-row-group | table-header-group | table-footer-group | table-row | table-cell | table-column-group | table-column | table-caption | ruby-base | ruby-text | ruby-base-container | ruby-text-container<display-box> = contents | none<display-legacy> = inline-block | inline-list-item | inline-table | inline-flex | inline-grid
examples display value comparison in this example we have two block-level container elements, each one with three inline children.
...0px; border-radius: 7px; } article, div { margin: 20px; } javascript const articles = document.queryselectorall('.container'); const select = document.queryselector('select'); function updatedisplay() { articles.foreach((article) => { article.style.display = select.value; }); } select.addeventlistener('change', updatedisplay); updatedisplay(); result note: you can find more
examples in the pages for each separate display data type, linked above.
<easing-function> - CSS: Cascading Style Sheets
examples easing function comparison this example creates an animation that can be started and stopped again using the provided button, and a select menu that can be used to switch its easing function between the available keywords, plus a couple of cubic-bezier() and steps() options.
...em.style.animationname = 'move-right'; startbtn.textcontent = 'stop animation'; divelem.style.animationtimingfunction = selectelem.value; } else { 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.
...*/ cubic-bezier(-1.9, 0.3, -0.2, 2.1) steps() function
examples these easing functions are valid: /* there is 5 treads, the last one happens right before the end of the animation.
filter - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...)where <alpha-value> = <number> | <percentage><hue> = <number> | <angle>
examples applying filter functions
examples of using the predefined functions are shown below.
... .mydiv { filter: grayscale(50%); } /* gray all images by 50% and blur by 10px */ img { filter: grayscale(0.5) blur(10px); } applying svg filters
examples of using the url function with an svg resource are as follows: .target { filter: url(#c1); } .mydiv { filter: url(commonfilters.xml#large-blur); } specifications specification status comment filter effects module level 1the definition of 'filter' in that specification.
float - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... formal definition initial valuenoneapplies toall elements, but has no effect if the value of display is none.inheritednocomputed valueas specifiedanimation typediscrete formal syntax left | right | none | inline-start | inline-end
examples how floated elements are positioned as mentioned above, when an element is floated, it is taken out of the normal flow of the document (though still remaining part of it).
...see clear for
examples.
font-kerning - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... in the image below, for instance, the
examples on the left do not use kerning, while the ones on the right do: syntax the font-kerning property is specified as one of the keyword values listed below.
...it also applies to ::first-letter and ::first-line.inheritedyescomputed valueas specifiedanimation typediscrete formal syntax auto | normal | none
examples enabling and disabling kerning html <div id="kern"></div> <div id="nokern"></div> <textarea id="input">av t.
<frequency> - CSS: Cascading Style Sheets
examples: 0hz, 1500hz, 10000hz.
...
examples: 0khz, 1.5khz, 10khz.
...
examples valid frequency values 12hz positive integer 4.3hz non-integer 14khz the unit is case-insensitive, though non-si capitalization is not recommended.
<gradient> - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...(be aware that older browsers may not use this behavior when using the transparent keyword.)
examples linear gradient example a simple linear gradient.
... <div class="radial-gradient">radial gradient</div> div { width: 240px; height: 80px; } .radial-gradient { background: radial-gradient(red, yellow, rgb(30, 144, 255)); } repeating gradient
examples simple repeating linear and radial gradient
examples.
linear-gradient() - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples gradient at a 45-degree angle body { width: 100vw; height: 100vh; } body { background: linear-gradient(45deg, red, blue); } gradient that starts at 60% of the gradient line body { width: 100vw; height: 100vh; } body { background: linear-gradient(135deg, orange 60%, cyan); } gradient with multi-position color stops this example uses multi-position color stops, with adj...
... body { width: 100vw; height: 100vh; } body { background: linear-gradient(to right, red 20%, orange 20% 40%, yellow 40% 60%, green 60% 80%, blue 80%); } more linear-gradient
examples please see using css gradients for more
examples.
radial-gradient() - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples simple gradient <div class="radial-gradient"></div> .radial-gradient { width: 240px; height: 120px; } .radial-gradient { background-image: radial-gradient(cyan 0%, transparent 20%, salmon 40%); } non-centered gradient <div class="radial-gradient"></div> .radial-gradient { width: 240px; height: 120px; } .radial-gradient { background-image: radial-gradient(farthest-corn...
...er at 40px 40px, #f35 0%, #43e 100%); } more radial-gradient
examples please see using css gradients for more
examples.
repeating-conic-gradient() - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... mdn understanding wcag, guideline 1.1 explanations understanding success criterion 1.1.1 | w3c understanding wcag 2.0
examples black and white starburst div { width: 200px; height: 200px; } <div></div> div { background-image: repeating-conic-gradient(#fff 0 9deg, #000 9deg 18deg); } off-centered gradient this gradient repeats 18 times, but since we only see the right half, we only see 9 repeats.
... div { width: 200px; height: 200px; } <div></div> div { background: repeating-conic-gradient( from 3deg at 25% 25%, green, blue 2deg 5deg, green, yellow 15deg 18deg, green 20deg); } more repeating-conic-gradient
examples please see using css gradients for more
examples.
repeating-linear-gradient() - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... and <color-stop-length> = [ <percentage> | <length> ]{1,2} and <color-hint> = [ <percentage> | <length> ]
examples zebra stripes body { width: 100vw; height: 100vh; } body { background-image: repeating-linear-gradient(-45deg, transparent, transparent 20px, black 20px, black 40px); /* with multiple color stop lengths */ background-image: repeating-linear-gradient(-45deg, transparent 0 20px, black 20px 40px); } ten repeating horizontal bars body { width...
... note: please see using css gradients for more
examples.
repeating-radial-gradient() - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... and <color-stop-length> = [ <percentage> | <length> ]{1,2} and <color-hint> = [ <percentage> | <length> ]
examples black and white gradient <div class="radial-gradient"></div> .radial-gradient { width: 120px; height: 120px; } .radial-gradient { background: repeating-radial-gradient(black, black 5px, white 5px, white 10px); } farthest-corner <div class="radial-gradient"></div> .radial-gradient { width: 240px; height: 120px; } .radial-gradient { background: repeating-radial-gradient...
... note: please see using css gradients for more
examples.
<time> - CSS: Cascading Style Sheets
examples: 0s, 1.5s, -60s.
...
examples: 0ms, 150.25ms, -60000ms.
...
examples valid times 12s positive integer -456ms negative integer 4.3ms non-integer 14ms the unit is case-insensitive, although capital letters are not recommended.
scaleZ() - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... in the above interactive
examples, perspective: 550px; (to create a 3d space) and transform-style: preserve-3d; (so the children, the 6 sides of the cube, are also positioned in the 3d space), have been set on the cube.
... 10001000s 1000010000s00001
examples html <div>normal</div> <div class="perspective">translated</div> <div class="scaled-translated">scaled</div> css div { width: 80px; height: 80px; background-color: skyblue; } .perspective { /* includes a perspective to create a 3d space */ transform: perspective(400px) translatez(-100px); background-color: limegreen; } .scaled-translated { /* includes a perspective to create a...
translateZ() - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... in the above interactive
examples, perspective: 550px; (to create a 3d space) and transform-style: preserve-3d; (so the children, the 6 sides of the cube, are also positioned in the 3d space), have been set on the cube.
... 10000100001t0001
examples in this example, two boxes are created.
transition-timing-function - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... a single component">[0,1]>, <number>, <number <a href="/docs/css/value_definition_syntax#brackets" title="brackets: enclose several entities, combinators, and multipliers to transform them as a single component">[0,1]>, <number>)<step-timing-function> = step-start | step-end | steps(<integer>[, <step-position>]?)where <step-position> = jump-start | jump-end | jump-none | jump-both | start | end
examples cubic-bezier
examples <div class="parent"> <div class="ease">ease</div> <div class="easein">ease-in</div> <div class="easeout">ease-out</div> <div class="easeinout">ease-in-out</div> <div class="linear">linear</div> <div class="cb">cubic-bezier(0.2,-2,0.8,2)</div> </div> .parent {} .parent > div[class] { width: 12em; min-width: 12em; margin-bottom: 4px; background-...
... intervalid = window.setinterval(updatetransition, 10000); .ease { transition-timing-function: ease; } .easein { transition-timing-function: ease-in; } .easeout { transition-timing-function: ease-out; } .easeinout { transition-timing-function: ease-in-out; } .linear { transition-timing-function: linear; } .cb { transition-timing-function: cubic-bezier(0.2,-2,0.8,2); } step
examples <div class="parent"> <div class="jump-start">jump-start</div> <div class="jump-end">jump-end</div> <div class="jump-both">jump-both</div> <div class="jump-none">jump-none</div> <div class="step-start">step-start</div> <div class="step-end">step-end</div> </div> .parent {} .parent > div[class] { width: 12em; min-width: 12em; margin-bottom: 4px; background-color: blac...
Index - Developer guides
4 getting started ajax, api, advanced, javascript, webmechanics, xmlhttprequest this article guides you through the ajax basics and gives you some simple hands-on
examples to get you started.
... 16 audio and video manipulation audio, canvas,
examples, guide, html5, media, video, web audio api, webgl, developer recommendation the ability to read the pixel values from each frame of a video can be very useful.
...this article provides recommendations for managing user input and implementing controls in open web apps, along with faqs, real-world
examples, and links to further information for anyone needing more detailed information on the underlying technologies.
User input and controls - Developer guides
this article provides recommendations for managing user input and implementing controls in open web apps, along with faqs, real-world
examples, and links to further information for anyone needing more detailed information on the underlying technologies.
...</div> note: compatibility information,
examples and other resources can be found in the content editable guide.
...
examples tracking multiple touch points at a time this example tracks multiple touch points at a time, allowing the user to draw in a <canvas> with more than one finger at a time.
<h1>–<h6>: The HTML Section Heading elements - HTML: Hypertext Markup Language
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples all headings the following code shows all the heading levels, in use.
... <h1>heading elements</h1> <h2>summary</h2> <p>some text here...</p> <h2>
examples</h2> <h3>example 1</h3> <p>some text here...</p> <h3>example 2</h3> <p>some text here...</p> <h2>see also</h2> <p>some text here...</p> here is the result of this code: accessibility concerns navigation a common navigation technique for users of screen reading software is jumping from heading to heading to quickly determine the content of the page.
<article>: The Article Contents element - HTML: Hypertext Markup Language
examples include: a forum post, a magazine or newspaper article, or a blog entry.
...if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples <article class="film_review"> <header> <h2>jurassic park</h2> </header> <section class="main_review"> <p>dinos were great!</p> </section> <section class="user_reviews"> <article class="user_review"> <p>way too scary for me.</p> <footer> <p> posted on <time datetime="2015-05-16 19:00">may 16</time> by lisa.
<dl>: The Description List element - HTML: Hypertext Markup Language
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples single term and description <dl> <dt>firefox</dt> <dd> a free, open source, cross-platform, graphical web browser developed by the mozilla corporation and hundreds of volunteers.
... </dd> <!-- other terms and descriptions --> </dl> multiple terms and descriptions it is also possible to define multiple terms with multiple corresponding descriptions, by combining the
examples above.
<img>: The Image Embed element - HTML: Hypertext Markup Language
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...explainer,
examples ismap this boolean attribute indicates that the image is part of a server-side map.
...
examples alternative text the following example embeds an image into the page and includes alternative text for accessibility.
<input type="email"> - HTML: Hypertext Markup Language
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... some
examples of valid strings when multiple is specified: "" "me@example" "me@example.org" "me@example.org,you@example.org" "me@example.org, you@example.org" "me@example.org,you@example.org, us@example.org" some
examples of invalid strings: "," "me" "me@example.org you@example.org" placeholders sometimes it's helpful to offer an in-context hint as to what form the input data should take.
...
examples here we have an email input with the id emailaddress which is allowed to be up to a maximum of 256 characters long.
<input type="hidden"> - HTML: Hypertext Markup Language
let's look at some
examples that illustrate its use.
... you can see a full example of what this might look like in the
examples section below.
...
examples let's look at how we might implement a simple version of the edit form we described earlier (see tracking edited content), using a hidden input to remember the id of the record being edited.
<input type="search"> - HTML: Hypertext Markup Language
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...the following example is from firefox: different messages will be shown when you try to submit the form with different types of invalid data contained inside the inputs; see the below
examples.
...ur numbers" required size="30" pattern="[a-z]{2}[0-9]{4}"> <button>search</button> <span class="validity"></span> </div> </form> input { margin-right: 10px; } input:invalid ~ span:after { content: '✖'; padding-left: 5px; position: absolute; } input:valid ~ span:after { content: '✓'; padding-left: 5px; position: absolute; } this renders like so:
examples you can see a good example of a search form used in context at our website-aria-roles example (see it live).
<input type="tel"> - HTML: Hypertext Markup Language
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples of custom keyboards on mobile devices.
...
examples in this example, we present a simple interface with a <select> element that lets the user choose which country they're in, and a set of <input type="tel"> elements to let them enter each part of their phone number; there is no reason why you can't have multiple tel inputs.
<link>: The External Resource Link element - HTML: Hypertext Markup Language
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples including a stylesheet to include a stylesheet in a page, use the following syntax: <link href="style.css" rel="stylesheet"> providing alternative stylesheets you can also specify alternative style sheets.
... preload
examples you can find a number of <link rel="preload">
examples in preloading content with rel="preload".
<nav>: The Navigation Section element - HTML: Hypertext Markup Language
common
examples of navigation sections are menus, tables of contents, and indexes.
...if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples in this example, a <nav> block is used to contain an unordered list (<ul>) of links.
<rb>: The Ruby Base element - HTML: Hypertext Markup Language
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples in this example, we provide an annotation for the original character equivalent of "kanji": <ruby> <rb>漢<rb>字 <rp>(</rp><rt>kan<rt>ji<rp>)</rp> </ruby> note how we've included two <rb> elements, to delimit the two separate parts of the ruby base text.
...</rt><rp>)</rp> 字 <rp>(</rp><rt>ji</rt><rp>)</rp> </ruby> <ruby> <rb>漢<rb>字 <rp>(</rp><rt>kan<rt>ji<rp>)</rp> </ruby> body { font-size: 22px; } the output looks like so: the html above might look something like this when rendered by a browser without ruby support: 漢字 (kan ji) body { font-size: 22px; } note: see the article about the <ruby> element for further
examples.
<rp>: The Ruby Fallback Parenthesis element - HTML: Hypertext Markup Language
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples this example uses ruby annotations to display the romaji equivalents for each character.
... <ruby> 漢 <rp>(</rp><rt>kan</rt><rp>)</rp> 字 <rp>(</rp><rt>ji</rt><rp>)</rp> </ruby> css body { font-size: 22px; } the result looks like this in your browser: the html above rendered by a browser without ruby support might look like this: 漢 (kan) 字 (ji) body { font-size: 22px; } see the article about the <ruby> element for further
examples.
<rt>: The Ruby Text element - HTML: Hypertext Markup Language
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... see the article about the <ruby> element for more
examples.
...
examples this simple example provides romaji transliteration for the kanji characters within the <ruby> element: <ruby> 漢 <rt>kan</rt> 字 <rt>ji</rt> </ruby> body { font-size: 22px; } the output looks like this in your browser: on a browser without ruby support, this example might look like this: 漢 kan 字 ji body { font-size: 22px; } specifications specificat...
<select>: The HTML Select element - HTML: Hypertext Markup Language
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... for further
examples, see the native form widgets: drop-down content.
... for more useful information on styling <select>, see: styling html forms advanced styling for html forms
examples basic select the following example creates a very simple dropdown menu, the second option of which is selected by default.
<source>: The Media or Image Source element - HTML: Hypertext Markup Language
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples video example this example demonstrates how to offer a video in ogg format for users whose browsers support ogg format, and a quicktime format video for users whose browsers support that.
...</video> for more
examples, the learning area article video and audio content is a great resource.
<tbody>: The Table Body element - HTML: Hypertext Markup Language
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples below are some
examples showing the use of the <tbody> element.
... for more
examples of this tag in use, see the
examples for <table>.
<tr>: The Table Row element - HTML: Hypertext Markup Language
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...we have some
examples below, but for more
examples and an in-depth tutorial, see the html tables series in our learn web development area, where you'll learn how to use the table elements and their attributes to get just the right layout and formatting for your tabular data.
...
examples see <table> for
examples on <tr>.
<u>: The Unarticulated Annotation (Underline) element - HTML: Hypertext Markup Language
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples indicating a spelling error this example uses the <u> element and some css to display a paragraph which includes a misspelled error, with the error indicated in the red wavy underline style which is fairly commonly used for this purpose.
...here are some
examples that show what you should do instead in several cases.
<video>: The Video Embed element - HTML: Hypertext Markup Language
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...explainer,
examples loop a boolean attribute; if specified, the browser will automatically seek back to the start upon reaching the end of the video.
...
examples simple video example this example plays a video when activated, providing the user with the browser's default video controls to control playback.
Content-Location - HTTP
this distinction may seem abstract without
examples.
...
examples requesting data from a server in different formats let's say a site's api can return data in json, xml, or csv formats.
...return different urls for content-location depending on the request's accept header: request header response header accept: application/json, text/json content-location: /documents/foo.json accept: application/xml, text/xml content-location: /documents/foo.xml accept: text/plain, text/* content-location: /documents/foo.txt these urls are
examples — the site could serve the different filetypes with any url patterns it wishes, such as a query string parameter: /documents/foo?format=json, /documents/foo?format=xml, and so on.
CSP: script-src-attr - HTTP
examples: http://*.example.com: matches all attempts to load from any subdomain of example.com using the http: url scheme.
...
examples fallback to script-src if script-src-attr is absent, user agent falls back to the script-src directive, and if that is absent as well, to default-src.
... todo: add comprehensive
examples.
CSP: script-src-elem - HTTP
examples: http://*.example.com: matches all attempts to load from any subdomain of example.com using the http: url scheme.
...
examples fallback to script-src if script-src-elem is absent, user agent falls back to the script-src directive, and if that is absent as well, to default-src.
... todo: add comprehensive
examples.
Details of the object model - JavaScript
javascript (using this may cause an error for the following
examples) class employee { constructor() { this.name = ''; this.dept = 'general'; } } javascript ** (use this instead) function employee() { this.name = ''; this.dept = 'general'; } java public class employee { public string name = ""; public string dept = "general"; } the manager and workerbee definitions show the difference in how to specify the next object higher in...
... specifying properties in a constructor, take 1 the following pairs of
examples show the java and javascript definitions for these objects.
... as these
examples show, if you want to have default values for object properties and you want to be able to change the default values at run time, you should set the properties in the constructor's prototype, not in the constructor function itself.
Array.prototype.every() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... if (!testresult) { return false; } } k++; } return true; }; }
examples testing size of all array elements the following example tests whether all elements in the array are bigger than 10.
... [12, 5, 8, 130, 44].every(x => x >= 10); // false [12, 54, 18, 130, 44].every(x => x >= 10); // true affecting initial array (modifying, appending, and deleting) the following
examples tests the behaviour of the every method when the array is modified.
Array.prototype.filter() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...i, t)){ res[c++] = kvalue; } } } } else{ while (++i !== len){ // checks to see if the key was set if (i in this){ kvalue = t[i]; if (func.call(thisarg, t[i], i, t)){ res[c++] = kvalue; } } } } res.length = c; // shrink down array to proper size return res; }; }
examples filtering out all small values the following example uses filter() to create a filtered array that has all elements with values less than 10 removed.
... /** * filter array items based on search criteria (query) */ const filteritems = (arr, query) => { return arr.filter(el => el.tolowercase().indexof(query.tolowercase()) !== -1) } console.log(filteritems(fruits, 'ap')) // ['apple', 'grapes'] console.log(filteritems(fruits, 'an')) // ['banana', 'mango', 'orange'] affecting initial array (modifying, appending and deleting) the following
examples tests the behavior of the filter method when the array is modified.
Array.prototype.find() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples find an object in an array by one of its properties const inventory = [ {name: 'apples', quantity: 2}, {name: 'bananas', quantity: 0}, {name: 'cherries', quantity: 5} ]; function ischerries(fruit) { return fruit.name === 'cherries'; } console.log(inventory.find(ischerries)); // { name: 'cherries', quantity: 5 } using arrow function and destructuring const inventory = [ {name: 'app...
...e array that is a prime number (or returns undefined if there is no prime number): function isprime(element, index, array) { let start = 2; while (start <= math.sqrt(element)) { if (element % start++ < 1) { return false; } } return element > 1; } console.log([4, 6, 8, 12].find(isprime)); // undefined, not found console.log([4, 5, 8, 12].find(isprime)); // 5 the following
examples show that nonexistent and deleted elements are visited, and that the value passed to the callback is their value when visited: // declare array with no elements at indexes 2, 3, and 4 const array = [0,1,,,,5,6]; // shows all indexes, not just those with assigned values array.find(function(value, index) { console.log('visited index ', index, ' with value ', value); }); // shows all indexes, i...
Date.prototype.toLocaleString() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using tolocalestring() in basic use without specifying a locale, a formatted string in the default locale and with default options is returned.
... for this reason, you cannot expect to be able to compare the results of tolocalestring() to a static value: "1/1/2019, 01:00:00" === new date("2019-01-01t01:00:00z").tolocalestring("en-us"); // true in firefox and others // false in ie and edge note: see also this stackoverflow thread for more details and
examples.
Function.prototype.apply() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using apply to append an array to another you can use push to append an element to an array.
...to illustrate this latter case: if such an engine had a limit of four arguments (actual limits are of course significantly higher), it would be as if the arguments 5, 6, 2, 3 had been passed to apply in the
examples above, rather than the full array.
Intl.DateTimeFormat.prototype.format() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using format use the format getter function for formatting a single date, here for serbia: var options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' }; var datetimeformat = new intl.datetimeformat('sr-rs', options); console.log(datetimeformat.format(new date())); // → "недеља, 7.
...alue: let d = new date("2019-01-01t00:00:00.000000z"); let formatteddate = intl.datetimeformat(undefined, { year: 'numeric', month: 'numeric', day: 'numeric', hour: 'numeric', minute: 'numeric', second: 'numeric' }).format(d); "1.1.2019, 01:00:00" === formatteddate; // true in firefox and others // false in ie and edge note: see also this stackoverflow thread for more details and
examples.
Intl.Locale.prototype.maximize() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples of these subtags include locale.hourcycle, locale.calendar, and locale.numeric.
...
examples using maximize let mylocale = new intl.locale("fr", {hourcycle: "h24", calendar: "gregory"}); console.log(mylocale.basename); // prints "fr" console.log(mylocale.tostring()); // prints "fr-u-ca-gregory-hc-h24" let mylocmaximized = mylocale.maximize(); // prints "fr-latn-fr".
Intl.Locale.prototype.minimize() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples of these subtags include locale.hourcycle, locale.calendar, and locale.numeric.
...
examples using minimize let mylocale = new intl.locale("fr-latn-fr", {hourcycle: "h24", calendar: "gregory"}); console.log(mylocale.basename); // prints "fr-latn-fr" console.log(mylocale.tostring()); // prints "fr-latn-fr-u-ca-gregory-hc-h24" let mylocminimized = mylocale.minimize(); // prints "fr", since french is only written in the latin script // and is most likely to be spoken in france.
Number.parseFloat() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... polyfill if (number.parsefloat === undefined) { number.parsefloat = parsefloat; }
examples number.parsefloat vs parsefloat this method has the same functionality as the global parsefloat() function: number.parsefloat === parsefloat; // true this method is also part of ecmascript 2015.
... (its purpose is modularization of globals.) see parsefloat() for more detail and
examples.
Number.parseInt() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... polyfill if (number.parseint === undefined) { number.parseint = window.parseint }
examples number.parseint vs parseint this method has the same functionality as the global parseint() function: number.parseint === parseint // true and is part of ecmascript 2015 (its purpose is modularization of globals).
... please see parseint() for more detail and
examples.
Promise.prototype.catch() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... note the
examples below are throwing instances of error.
...
examples using and chaining the catch method var p1 = new promise(function(resolve, reject) { resolve('success'); }); p1.then(function(value) { console.log(value); // "success!" throw new error('oh, no!'); }).catch(function(e) { console.error(e.message); // "oh, no!" }).then(function(){ console.log('after a catch the chain is restored'); }, function () { console.log('not fired due to the ca...
Promise.race() - JavaScript
if you'd like to contribute to the interactive demo project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
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(...
... console.log(p); console.log(p2); settimeout(function(){ console.log('the stack is now empty'); console.log(p); console.log(p2); }); // logs, in order: // promise { <state>: "pending" } // promise { <state>: "pending" } // the stack is now empty // promise { <state>: "fulfilled", <value>: 100 } // promise { <state>: "fulfilled", <value>: "non-promise value" } using promise.race –
examples with settimeout var p1 = new promise(function(resolve, reject) { settimeout(() => resolve('one'), 500); }); var p2 = new promise(function(resolve, reject) { settimeout(() => resolve('two'), 100); }); promise.race([p1, p2]) .then(function(value) { console.log(value); // "two" // both fulfill, but p2 is faster }); var p3 = new promise(function(resolve, reject) { settimeout(() => ...
RegExp.prototype[@@match]() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... for example, the following two
examples return same result.
...
examples direct call this method can be used in almost the same way as string.prototype.match(), except the different this and the different arguments order.
RegExp.prototype[@@matchAll]() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...for example, the following two
examples return same result.
...
examples direct call this method can be used in almost the same way as string.prototype.matchall(), except for the different value of this and the different order of arguments.
RegExp.prototype[@@replace]() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... for example, following two
examples return same result.
...
examples direct call this method can be used in almost the same way as string.prototype.replace(), except the different this and the different arguments order.
RegExp.prototype[@@search]() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...for example, the following two
examples return the same result.
...
examples direct call this method can be used in almost the same way as string.prototype.search(), except the different this and the different arguments order.
RegExp.prototype[@@split]() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...for example, the following two
examples return the same result.
...
examples direct call this method can be used in almost the same way as string.prototype.split(), except the different this and the different order of arguments.
RegExp.prototype.sticky - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using a regular expression with the sticky flag var str = '#foo#'; var regex = /foo/y; regex.lastindex = 1; regex.test(str); // true regex.lastindex = 5; regex.test(str); // false (lastindex is taken into account with sticky flag) regex.lastindex; // 0 (reset after match failure) anchored sticky flag for several versions, firefox's spidermonkey engine had a bug with regard to the ^ assertio...
...
examples of correct behavior: var regex = /^foo/y; regex.lastindex = 2; regex.test('..foo'); // false - index 2 is not the beginning of the string var regex2 = /^foo/my; regex2.lastindex = 2; regex2.test('..foo'); // false - index 2 is not the beginning of the string or line regex2.lastindex = 2; regex2.test('.\nfoo'); // true - index 2 is the beginning of a line specifications specificat...
String.prototype.charCodeAt() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...see
examples 2 and 3 (below).
...
examples using charcodeat() the following example returns 65, the unicode value for a.
Symbol.prototype.description - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...see the
examples.
...
examples using description symbol('desc').tostring(); // "symbol(desc)" symbol('desc').description; // "desc" symbol('').description; // "" symbol().description; // undefined // well-known symbols symbol.iterator.tostring(); // "symbol(symbol.iterator)" symbol.iterator.description; // "symbol.iterator" // global symbols symbol.for('foo').tostring(); // "symbol(foo)" symbol.for('foo').description; // "foo" specifications specification ecmascript (ecma-262)the definition of 'get symbol.prototype.description' in that specification.
Symbol.matchAll - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...the following two
examples return same result: 'abc'.matchall(/a/); /a/[symbol.matchall]('abc'); this method exists for customizing match behavior within regexp subclasses.
... property attributes of symbol.matchall writable no enumerable no configurable no
examples using symbol.matchall let re = /[0-9]+/g; let str = '2016-01-02|2019-03-07'; const numbers = { *[symbol.matchall] (str) { for (const n of str.matchall(/[0-9]+/g)) yield n[0]; } }; console.log(array.from(str.matchall(numbers))); // array ["2016", "01", "02", "2019", "03", "07"] see string.prototype.matchall() and regexp.prototype[@@matchall]() for more
examples.
parseFloat() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples parsefloat returning a number the following
examples all return 3.14: parsefloat(3.14); parsefloat('3.14'); parsefloat(' 3.14 '); parsefloat('314e-2'); parsefloat('0.0314e+2'); parsefloat('3.14some non-digit characters'); parsefloat({ tostring: function() { return "3.14" } }); parsefloat returning nan the following example returns nan: parsefloat('ff2'); parsefloat and bigint the foll...
...owing
examples both return 900719925474099300, losing precision as the integer is too large to be represented as a float: parsefloat(900719925474099267n); parsefloat('900719925474099267n'); specifications specification ecmascript (ecma-262)the definition of 'parsefloat' in that specification.
parseInt() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...21')) // 421 console.log(filterint('-421')) // -421 console.log(filterint('+421')) // 421 console.log(filterint('infinity')) // infinity console.log(filterint('421e+0')) // nan console.log(filterint('421hop')) // nan console.log(filterint('hop1.61803398875')) // nan console.log(filterint('1.61803398875')) // nan
examples using parseint the following
examples all return 15: parseint('0xf', 16) parseint('f', 16) parseint('17', 8) parseint(021, 8) parseint('015', 10) // but `parseint(015, 10)` will return 13 parseint(15.99, 10) parseint('15,123', 10) parseint('fxx123', 16) parseint('1111', 2) parseint('15 * 3', 10) parseint('15e2', 10) parseint('15px', 10) parseint('12', 13) the following
examples all return...
... nan: parseint('hello', 8) // not a number at all parseint('546', 2) // digits other than 0 or 1 are invalid for binary radix the following
examples all return -15: parseint('-f', 16) parseint('-0f', 16) parseint('-0xf', 16) parseint(-15.1, 10) parseint('-17', 8) parseint('-15', 10) parseint('-1111', 2) parseint('-15e1', 10) parseint('-12', 13) the following
examples all return 4.
Logical AND (&&) - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples of expressions that can be converted to false are: null; nan; 0; empty string ("" or '' or ``); undefined.
... true || false && false // returns true, because && is executed first (true || false) && false // returns false, because operator precedence cannot apply
examples using and the following code shows
examples of the && (logical and) operator.
Logical NOT (!) - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples of expressions that can be converted to false are: null; nan; 0; empty string ("" or '' or ``); undefined.
...
examples using not the following code shows
examples of the !
Logical OR (||) - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples of expressions that can be converted to false are: null; nan; 0; empty string ("" or '' or ``); undefined.
... true || false && false // returns true, because && is executed first (true || false) && false // returns false, because operator precedence cannot apply
examples using or the following code shows
examples of the || (logical or) operator.
Nullish coalescing operator (??) - JavaScript
see below for more
examples.
...if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...rightexpr
examples using the nullish coalescing operator in this example, we will provide default values but keep values other than null or undefined.
Object initializer - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples creating objects an empty object with no properties can be created like this: let object = {} however, the advantage of the literal or initializer notation is, that you are able to quickly create objects with properties inside the curly braces.
... } }; for more information and
examples about methods, see method definitions.
Operator precedence - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...some more
examples follow.
...(b || c); // evaluate `a` first, then produce `a` if `a` is not `null` and not `undefined` a?.b.c; // evaluate `a` first, then produce `undefined` if `a` is `null` or `undefined`
examples 3 > 2 && 2 > 1 // returns true 3 > 2 > 1 // returns false because 3 > 2 is true, then true is converted to 1 // in inequality operators, therefore true > 1 becomes 1 > 1, which // is false.
this - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... to set the value of this to a particular value when calling a function, use call(), or apply() as in the
examples below.
... class base {} class good extends base {} class alsogood extends base { constructor() { return {a: 5}; } } class bad extends base { constructor() {} } new good(); new alsogood(); new bad(); // referenceerror
examples this in function contexts // an object can be passed as the first argument to call or apply and this will be bound to it.
break - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples break in while loop the following function has a break statement that terminates the while loop when i is 3, and then returns the value 3 * x.
... block_1: { console.log('1'); break block_2; // syntaxerror: label not found } block_2: { console.log('2'); } break within functions syntaxerrors are also generated in the following code
examples which use break statements within functions that are nested within a loop, or labeled block that the break statements are intended to break out of.
The "codecs" parameter in common media types - Web media technologies
the table below shows some
examples:
examples of classic webm mime types with codecs parameter mime type description video/webm;codecs="vp8" a webm video with vp8 video in it; no audio is specified.
...following the table are some
examples.
... webm media type
examples video/webm;codecs="vp08.00.41.08,vorbis" vp8 video, profile 0 level 4.1, using 8-bit yuv with 4:2:0 chroma subsampling, using bt.709 color primaries, transfer function, and matrix coefficients, with the luminance and chroma values encoded within the legal ("studio") range.
<feComposite> - SVG: Scalable Vector Graphics
example svg <svg width="330" height="195" viewbox="0 0 1100 650" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> <title>example fecomposite -
examples of fecomposite operations</title> <desc>four rows of six pairs of overlapping triangles depicting the six different fecomposite operators under different opacity values and different clearing of the background.</desc> <defs> <desc>define two sets of six filters for each of the six compositing operators.
...e transform="translate(650,25)" xlink:href="#twobluetriangles"/> <use transform="translate(775,25)" xlink:href="#twobluetriangles"/> <use transform="translate(900,25)" xlink:href="#twobluetriangles"/> </g> </defs> <rect fill="none" stroke="blue" x="1" y="1" width="1098" height="648"/> <g font-family="verdana" font-size="40" shape-rendering="crispedges"> <desc>render the
examples using the filters that draw on top of an opaque white surface, thus obliterating the background.</desc> <g enable-background="new"> <text x="15" y="75">opacity 1.0</text> <text x="15" y="115" font-size="27">(with feflood)</text> <text x="15" y="200">opacity 0.5</text> <text x="15" y="240" font-size="27">(with feflood)</text> <use xlink:href="#bluetriang...
...ter="url(#xorflood)" /> <text x="15" y="275">xor</text> </g> <g transform="translate(900,25)"> <use xlink:href="#red100" filter="url(#arithmeticflood)" /> <use xlink:href="#red50" filter="url(#arithmeticflood)" /> <text x="-25" y="275">arithmetic</text> </g> </g> <g transform="translate(0,325)" enable-background="new"> <desc>render the
examples using the filters that do not obliterate the background, thus sometimes causing the background to continue to appear in some cases, and in other cases the background image blends into itself ("double-counting").</desc> <text x="15" y="75">opacity 1.0</text> <text x="15" y="115" font-size="27">(without feflood)</text> <text x="15" y="200">opacity 0.5...
Bootstrapped extensions - Archive of obsolete content
some
examples of when the shutdown() function may be called: when the extension is uninstalled, if it's currently enabled.
... edward lee shows off some helpful coding patterns and
examples you can use in your bootstrapped add-on.
File I/O - Archive of obsolete content
use of os.file is preferred over the
examples in this article.
...those methods/properties are mostly self-explanatory, so we haven't included
examples of using them here.
Post data to window - Archive of obsolete content
this offers
examples of sending post data to the server and displaying the server response.
... need more elaborate
examples,
examples of displaying the response in a new tab, in background tabs, and a link to using xmlhttprequest for post requests.
Extension Versioning, Update and Compatibility - Archive of obsolete content
as a rough overview this is a version string split by periods, some
examples: 2.0 1.0b1 3.0pre1 5.0.1.2 note: before firefox 1.5 the more basic firefox version format was used: major.minor.release.build[+] where only digits were allowed.
... and all popular (scripting) languages offer support, for
examples: python, perl: cpan digest, php signing update manifests if you wish to serve your update rdf over regular http, gecko 1.9 based applications will require that you digitally sign the update manifest to ensure that it's information isn't tampered with between you creating it and applications retrieving it.
Inline options - Archive of obsolete content
some
examples: <!-- boolean
examples --> <setting pref="extensions.myaddon.bool1" type="bool" title="boolean 1"/> <setting pref="extensions.myaddon.bool2" type="bool" title="boolean 2"> description of boolean 2 </setting> <!-- boolean stored as an integer --> <setting pref="extensions.myaddon.boolint" type="boolint" title="boolean 3" on="1" off="2"/> <!-- integer example --> <setting pref="extensions.myad...
...don.int" type="integer" title="integer"/> <!-- string
examples --> <setting pref="extensions.myaddon.text" type="string" title="text"/> <setting pref="extensions.myaddon.password" type="string" title="password" inputtype="password"/> <!-- color example --> <setting pref="extensions.myaddon.color" type="color" title="color"/> <!-- file and directory
examples --> <setting pref="extensions.myaddon.file" type="file" title="file"/> <setting pref="extensions.myaddon.directory" type="directory" title="directory"/> <!-- list example (this example would be stored as an integer) --> <setting pref="extensions.myaddon.options1" type="menulist" title="options 1"> <menulist> <menupopup> <menuitem value="500" label="small"/> <menuitem value="800" label="medium"/> <menuitem value="1200...
Adding windows and dialogs - Archive of obsolete content
read the article and its
examples carefully, because there are many useful functions to use in the prompt service.
...we have been using the window.alert function to open alert messages in our
examples so far, but that's not the right way to do it.
Setting Up a Development Environment - Archive of obsolete content
all of our
examples are handled with komodo edit, so if you see a .kpf or .komodoproject file in an example you download, this is a komodo project file.
... we recommend you set up make in your system, since our
examples come with all the necessary files to build and install the resulting xpi using this tool.
Promises - Archive of obsolete content
the following page contains
examples of many promise-based replacement apis for common operations.
... the following
examples make use of the task api, which harnesses generator functions to remove some of the syntactic clutter of raw promises, such that asynchronous promise code more closely resembles synchronous, procedural code.
JXON - Archive of obsolete content
animal.dog[1] 7 <animal> in my house <dog>charlie</dog> </animal> "animal": { "keyvalue": "in my house", "dog": "charlie" } myobject.animal.keyvalue, myobject.animal.dog 8 <animal> in my ho <dog>charlie</dog> use </animal> "animal": { "keyvalue": "in my house", "dog": "charlie" } myobject.animal.keyvalue, myobject.animal.dog code considerations in these
examples we chose to use a property named keyvalue for the text content.
...><label for="rel_pullover">pullover</label></span> </td> </tr> <tr> <th style="text-align: right;">quantity:</th> <td> <input type="text" name="myinput" onkeypress="return numbersonly(this, event);" onpaste="return false;" /> </td> </tr> </table> <p> <input type="submit" value="purchase!" /> </p> </form> </div> other
examples example #1: how to use jxon to create an html document instead of an xml document: /* the structure of my document */ var omyhtmlstruct = { "html": { "head": { "meta": { "@http-equiv": "content-type", "@content": "text/html; charset=utf-8" }, "title": "my html document", "script": { "@type": "text/javascript", "keyvalue": "alert(\"we...
Installing plugins to Gecko embedding browsers on Windows - Archive of obsolete content
examples given for "product x.y" were using netscape 6 but other possible mozilla based browsers exist as well; all gecko-based browsers are encouraged to write these keys, so that plugin vendors can write plugin installers that install correctly to all gecko-based browsers.
...
examples given for "product x.y" were using netscape 6, but other possible mozilla based browsers exist as well; all gecko-based browsers are encouraged to write these keys, so that plugin vendors can write a plugin installer that is able to find the information it needs across all gecko-based browsers.
Creating regular expressions for a microsummary generator - Archive of obsolete content
to identify which parts are unique and which are common, let's look at the urls of several other auction item pages: http://cgi.ebay.com/ws/ebayisapi.dll?viewitem&item=130017517168 http://cgi.ebay.com/ws/ebayisapi.dll?viewitem&item=290019763032 http://cgi.ebay.com/ws/ebayisapi.dll?viewitem&item=170019463424 based on these
examples, it looks like the unique part is the item number at the end of the urls, and everything else is common to all urls.
... here are several other urls of this style: http://cgi.ebay.com/firefox-2002-dvd_w0qqitemz130017517168qqihz003qqcategoryz617qqcmdzviewitem http://cgi.ebay.com/ahm-ho-scale-firefox-tank-car_w0qqitemz290019763032qqihz019qqcategoryz19130qqcmdzviewitem http://cgi.ebay.com/inuyasha-anime-pin-of-kirara-kilala-firefox_w0qqitemz170019463424qqihz007qqcategoryz39557qqcmdzviewitem based on these
examples, it looks like the urls all start with "http://cgi.ebay.com/", they all contain the string "qqitemz" followed by the item number, and they all end with the string "qqcmdzviewitem".
Embedding FAQ - Archive of obsolete content
faq mozilla.dev.embedding how to start embedding you can find a
examples, faqs, and the api from mozilla itself.
...you can find more information on adding new protocols here how to embedding mozilla inside of java there hasn't been any good code
examples found.
Simple Storage - Archive of obsolete content
examples this code persistently stores some data: jetpack.future.import("storage.simple");var mystorage = jetpack.storage.simple;mystorage.fribblefrops = [1, 3, 3, 7];mystorage.heimelfarbs = { bar: "baz" }; and this code -- pretend it's in the same jetpack as the code above -- simply uses that data: mystorage.fribblefrops.foreach(function (elt) console.log(elt));var bar = mystorage.heimelfarbs.bar;jetpack...
...note that these
examples create a mystorage variable to emphasize the fact that jetpack.storage.simple is just a normal javascript object.
Simple Storage - Archive of obsolete content
examples this code persistently stores some data: jetpack.future.import("storage.simple"); var mystorage = jetpack.storage.simple; mystorage.fribblefrops = [1, 3, 3, 7]; mystorage.heimelfarbs = { bar: "baz" }; and this code -- pretend it's in the same jetpack as the code above -- simply uses that data: mystorage.fribblefrops.foreach(function (elt) console.log(elt)); var bar = mystorage.heimelfarbs.bar; j...
...note that these
examples create a mystorage variable to emphasize the fact that jetpack.storage.simple is just a normal javascript object.
RDF Datasource How-To - Archive of obsolete content
for
examples of an implementation like this, look at the rdf/xml datasource or the bookmarks datasource.
...the file system datasource and local mail datasource are good
examples of datasources that have been implemented this way.
File object - Archive of obsolete content
examples of possible prefix strings are "/" to indicate the unix root directory, "c:" to specify a windows drive letter, and "file:" to indicate a file url.
...
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 mai...
URIs and URLs - Archive of obsolete content
familiar
examples include an electronic document, an image, a service (e.g., "today's weather report for los angeles"), and a collection of other resources.
... also the handling of query segments is different from the
examples given in rfc 2396: within an object with a well-defined base uri of http://a/b/c/d;p?q the relative uri would be resolved as follows: ...
Venkman Introduction - Archive of obsolete content
this article provides an overview and some practical
examples of using the javascript debugger in web applications and web page scripting.
...but the steps described here can give you a basic feel for the debugger if you haven't already had some experience using it, and they provide the basis for the more interesting and practical
examples in the articles that follow this one.
Dynamically modifying XUL-based user interface - Archive of obsolete content
it explains the concept of dom documents, demonstrates a few simple
examples of using dom calls to perform basic manipulations on a document, and then demonstrates working with anonymous xbl content using mozilla-specific methods.
...
examples: using dom methods this section demonstrates the use of appendchild(), createelement(), insertbefore(), and removechild() dom methods.
RDF Modifications - Archive of obsolete content
as it happens, this resource is being used, since it is the value of the ref attribute we've been using in these
examples.
...consider the following binding: <binding subject="?start" predicate="http://www.xulplanet.com/rdf/categoryname" object="?name"/> this binding involves a triple pointing out from the starting variable that has been used in these
examples.
Simple Example - Archive of obsolete content
unlike previous
examples where we iterated over a property to navigate the graph, here we want to iterate over the children of an rdf container.
... <query> <content uri="?start"/> <member container="?start" child="?photo"/> <triple subject="?photo" predicate="http://purl.org/dc/elements/1.1/title" object="?title"/> </query> the seed is set in a similar manner as the previous
examples, effectively creating a single result with the ?start variable set to the reference resource 'http://www.xulplanet.com/rdf/myphotos'.
Template Logging - Archive of obsolete content
the two errors where neither variable of either a <member> or <triple> have a value deserve some
examples.
... <content uri="?uri"> <member container="?uri" child="?person"> <triple subject="?person" predicate="http://example.com/name" object="?name"/> <content uri="?uri"> <member container="?uri" child="?human"> <triple subject="?person" predicate="http://example.com/name" object="?name"/> note that subtle difference in these
examples.
XML Assignments - Archive of obsolete content
in this case, we use an expression that returns the nodes as in earlier
examples, and use some additional syntax of the query to get the length of the names.
...here, the two attributes 'name' and 'gender' will be taken from the xml data, as in previous
examples.
XML Templates - Archive of obsolete content
for this and the following
examples, we are going to use the following xml document containing a list of people: <people> <person name="napoleon bonaparte" gender="male"/> <person name="cleopatra" gender="female"/> <person name="julius caesar" gender="male"/> <person name="ferdinand magellan" gender="male"/> <person name="laura secord" gender="female"/> </people> xml query syntax the query syntax is fairly simple for x...
...this is useful when recursive generation or multiple rules are used, and we'll see
examples of why this is useful later.
textbox (Toolkit autocomplete) - Archive of obsolete content
« xul reference home [
examples | attributes | properties | methods | related ] this element is created by setting the type attribute of the textbox to autocomplete.
...ghlightnonmatches, ignoreblurwhilesearching, inputfield, label, maxlength, maxrows, minresultsforpopup, open, popup, popupopen, searchcount, searchparam, selectionend, selectionstart, showcommentcolumn, showimagecolumn,size, tabindex, tabscrolling, textlength, textvalue, timeout, type, value methods getsearchat, onsearchcomplete, ontextentered, ontextreverted, select, setselectionrange
examples <textbox type="autocomplete" autocompletesearch="history"/> attributes accesskey type: character this should be set to a character that is used as a shortcut key.
Textbox (XPFE autocomplete) - Archive of obsolete content
« xul reference home [
examples | attributes | properties | methods | related ] this element is created by setting the type attribute of a textbox to autocomplete.
...onstart, sessioncount, showcommentcolumn, showpopup, size, tabindex, tabscrolling, textlength, textvalue, timeout, type, useraction, value methods addsession, clearresults, getdefaultsession, getresultat, getresultcount, getresultvalueat, getsession, getsessionbyname, getsessionresultat, getsessionstatusat, getsessionvalueat, removesession, select, setselectionrange, syncsessions
examples (example needed) attributes accesskey type: character this should be set to a character that is used as a shortcut key.
Box Model Details - Archive of obsolete content
here, we'll find out some more details with some
examples.
...layout
examples using spacers example 3 : source view <hbox> <button label="one"/> <spacer style="width: 5px"/> <button label="two"/> </hbox> here, a spacer is used as a separator between the two buttons, by setting an explicit width of 5 pixels.
Creating Dialogs - Archive of obsolete content
amongst other useful attributes are buttonlabelaccept - label to appear on the accept button egsave buttonaccesskeyaccept - access key to use for the accept button egs defaultbutton - button is activated when the enter key is pressed note: the label attributes are required by remote sites and are probably missing in the above
examples due to bug 224996.
... <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).
Document Object Model - Archive of obsolete content
for example, if we combined the last two
examples into a single file, we might want to call the gettext() function from within the other window (for example, the test.xul window).
...here are some
examples: <button xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"/> <button xmlns="http://www.w3.org/1999/xhtml"/> <html:button xmlns:html="http://www.w3.org/1999/xhtml"/> <html:button xmlns:html="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"/> namespaces are specified using the xmlns attribute.
action - Archive of obsolete content
« xul reference home [
examples | attributes | properties | methods | related ] used to specify the content that should be generated for each matching result from a query.
...
examples example needed attributes inherited from xul element align, allowevents, allownegativeassertions, class, coalesceduplicatearcs, collapsed, container, containment, context, contextmenu, datasources, dir, empty, equalsize, flags, flex, height, hidden, id, insertafter, insertbefore, left, maxheight, maxwidth, menu, minheight, minwidth, mousethrough, observes, ordinal, orient, pack, persist, po...
arrowscrollbox - Archive of obsolete content
« xul reference home [
examples | attributes | properties | methods | related ] a box which provides scroll arrows along its edges for scrolling through the contents of the box.
... attributes clicktoscroll, disabled, smoothscroll, tabindex properties disabled, scrollboxobject, scrollincrement, smoothscroll, tabindex methods ensureelementisvisible, scrollbyindex, scrollbypixels
examples <arrowscrollbox orient="vertical" flex="1"> <button label="red"/> <button label="blue"/> <button label="green"/> <button label="yellow"/> <button label="orange"/> <button label="silver"/> <button label="lavender"/> <button label="gold"/> <button label="turquoise"/> <button label="peach"/> <button label="maroon"/> <button label="black"/> </arrowscrollbox> attributes ...
assign - Archive of obsolete content
« xul reference home [
examples | attributes | properties | methods | related ] for xml templates, specifies an additional variable to assign a value to.
... for more information, see xml_assignments attributes expr, var
examples (example needed) attributes expr type: string for xml queries, an xpath expression which returns results.
bbox - Archive of obsolete content
« xul reference home [
examples | attributes | properties | methods | related ] a horizontal box that is baseline aligned.
...
examples (example needed) attributes inherited from xul element align, allowevents, allownegativeassertions, class, coalesceduplicatearcs, collapsed, container, containment, context, contextmenu, datasources, dir, empty, equalsize, flags, flex, height, hidden, id, insertafter, insertbefore, left, maxheight, maxwidth, menu, minheight, minwidth, mousethrough, observes, ordinal, orient, pack, persist, popup, position, preference-editable, querytype, ref, removeelement, sortdirection, sortresource, sortresource2, statustext, style, template, tooltip, tooltiptext, top, uri, wait-cursor, width properties inherited properties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapse...
binding - Archive of obsolete content
« xul reference home [
examples | attributes | properties | methods | related ] should be contained within a bindings element.
... properties object, predicate, subject
examples fixme: (example needed) attributes inherited from xul element align, allowevents, allownegativeassertions, class, coalesceduplicatearcs, collapsed, container, containment, context, contextmenu, datasources, dir, empty, equalsize, flags, flex, height, hidden, id, insertafter, insertbefore, left, maxheight, maxwidth, menu, minheight, minwidth, mousethrough, observes, ordinal, orient, pack, persist, popup, position, preference-editable, querytype, ref, removeelement, sortdirection, sortresource, sortresou...
bindings - Archive of obsolete content
« xul reference home [
examples | attributes | properties | methods | related ] used to specify a set of variable bindings for a rule.
...
examples (example needed) attributes inherited from xul element align, allowevents, allownegativeassertions, class, coalesceduplicatearcs, collapsed, container, containment, context, contextmenu, datasources, dir, empty, equalsize, flags, flex, height, hidden, id, insertafter, insertbefore, left, maxheight, maxwidth, menu, minheight, minwidth, mousethrough, observes, ordinal, orient, pack, persist, popup, position, preference-editable, querytype, ref, removeelement, sortdirection, sortresource, sortresource2,...
box - Archive of obsolete content
« xul reference home [
examples | attributes | properties | methods | related ] a container element which can contain any number of child elements.
...
examples <box orient="horizontal"> <label value="zero"/> <box orient="vertical"> <label value="one"/> <label value="two"/> </box> <box orient="horizontal"> <label value="three"/> <label value="four"/> </box> </box> attributes inherited from xul element align, allowevents, allownegativeassertions, class, coalesceduplicatearcs, collapsed, container, containment, context, contextmenu, datasources, dir, empty, e...
broadcaster - Archive of obsolete content
« xul reference home [
examples | attributes | properties | methods | related ] a broadcaster is used when you want multiple elements to share one or more attribute values, or when you want elements to respond to a state change.
...
examples (example needed) attributes inherited from xul element align, allowevents, allownegativeassertions, class, coalesceduplicatearcs, collapsed, container, containment, context, contextmenu, datasources, dir, empty, equalsize, flags, flex, height, hidden, id, insertafter, insertbefore, left, maxheight, maxwidth, menu, minheight, minwidth, mousethrough, observes, ordinal, orient, pack, persist,...
broadcasterset - Archive of obsolete content
« xul reference home [
examples | attributes | properties | methods | related ] a container element for broadcaster elements.
...
examples (example needed) attributes inherited from xul element align, allowevents, allownegativeassertions, class, coalesceduplicatearcs, collapsed, container, containment, context, contextmenu, datasources, dir, empty, equalsize, flags, flex, height, hidden, id, insertafter, insertbefore, left, maxheight, maxwidth, menu, minheight, minwidth, mousethrough, observes, ordinal, orient, pack, persist, popup, position, preference-editable, querytype, ref, removeelement, sortdirection, sortresource, sortresource2, statustext, style, template, tooltip, tooltiptext, top, uri, wait-cursor, width properties inherited properties align, , allowevents, , boxobject, builder, , , , ...
browser - Archive of obsolete content
« xul reference home [
examples | attributes | properties | methods | related ] a xul <browser> element represents a frame which is expected to contain a view of a web document.
..., contentvieweredit, contentviewerfile, contentwindow, currenturi, docshell, documentcharsetinfo, homepage, markupdocumentviewer, messagemanager, preferences, securityui, sessionhistory, webbrowserfind, webnavigation, webprogress methods addprogresslistener, goback, goforward, gohome, gotoindex, loaduri, loaduriwithflags, reload, reloadwithflags, removeprogresslistener, stop, swapdocshells
examples <!-- shows mozilla homepage inside a groupbox --> <groupbox flex="1"> <caption label="mozilla homepage"/> <browser type="content" src="http://www.mozilla.org" flex="1"/> </groupbox> attributes autocompleteenabled type: boolean set to true to enable autocomplete of fields.
button - Archive of obsolete content
« xul reference home [
examples | attributes | properties | methods | related ] a button that can be pressed by the user.
... attributes accesskey, autocheck, checkstate, checked, command, crop, dir, disabled, dlgtype, group, icon, image, label, open, orient, tabindex, type properties accesskey, accessibletype, autocheck, checkstate, checked, command, crop, dir, disabled, dlgtype, group, image, label, open, orient, tabindex, type
examples <button label="press me" oncommand="alert('you pressed me!');"/> attributes accesskey type: character this should be set to a character that is used as a shortcut key.
caption - Archive of obsolete content
« xul reference home [
examples | attributes | properties | methods | related ] a header for a groupbox.
... attributes accesskey, crop, image, label, tabindex properties accesskey, crop, image, label, tabindex
examples <groupbox> <caption label="my groupbox"/> </groupbox> <groupbox flex="1"> <caption> <checkbox label="a checked groupbox"/> </caption> </groupbox> attributes accesskey type: character this should be set to a character that is used as a shortcut key.
checkbox - Archive of obsolete content
« xul reference home [
examples | attributes | properties | methods | related ] an element that can be turned on and off.
... attributes accesskey, checked, command, crop, disabled, src, label, preference, tabindex properties accesskey, accessibletype, checked, command, crop, disabled, src, label, tabindex
examples <checkbox label="enable javascript" checked="true"/> <checkbox label="enable java" checked="false"/> attributes accesskey type: character this should be set to a character that is used as a shortcut key.
colorpicker - Archive of obsolete content
« xul reference home [
examples | attributes | properties | methods | related ] a palette of colors from which a user may select by clicking on one of the grid cells.
... attributes disabled, color, onchange, preference, tabindex, type properties accessibletype, color, disabled, open, tabindex, value
examples <colorpicker/> attributes disabled type: boolean indicates whether the element is disabled or not.
command - Archive of obsolete content
« xul reference home [
examples | attributes | properties | methods | related ] a command element can be used to invoke an operation that can come from multiple sources.
...see also: command attribute, commandset element attributes disabled, label, oncommand,reserved
examples the following code will send a paste command (cmd_paste) to the currently focused element: // first include chrome://global/content/globaloverlay.js godocommand("cmd_paste"); example with two buttons <commandset><command id="cmd_openhelp" oncommand="alert('help');"/></commandset> <button label="help" command="cmd_openhelp"/> <button label="more help" command="cmd_openhelp"/> attributes ...
conditions - Archive of obsolete content
« xul reference home [
examples | attributes | properties | methods | related ] this element should appear directly inside a rule element and is used to define conditions for the rule.
...
examples (example needed) attributes inherited from xul element align, allowevents, allownegativeassertions, class, coalesceduplicatearcs, collapsed, container, containment, context, contextmenu, datasources, dir, empty, equalsize, flags, flex, height, hidden, id, insertafter, insertbefore, left, maxheight, maxwidth, menu, minheight, minwidth, mousethrough, observes, ordinal, orient, pack, persist,...
datepicker - Archive of obsolete content
« xul reference home [
examples | attributes | properties | methods | related ] a datepicker allows the user to enter a date.
... 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.
deck - Archive of obsolete content
« xul reference home [
examples | attributes | properties | methods | related ] an element that displays only one of its children at a time.
... attributes selectedindex properties selectedindex, selectedpanel
examples <deck selectedindex="2"> <description value="this is the first page"/> <button label="this is the second page"/> <box> <description value="this is the third page"/> <button label="this is also the third page"/> </box> </deck> attributes selectedindex type: integer gets and sets the index of the currently selected panel.
description - Archive of obsolete content
« xul reference home [
examples | attributes | properties | methods | related ] this element is used to create a block of text.
... attributes crop, disabled, tabindex value properties accessibletype, crop, disabled, tabindex, value style classes header, indent, monospace, plain, small-margin
examples this is a long section of text that will word wrap when displayed <description> this is a long section of text that will word wrap when displayed.
dialog - Archive of obsolete content
« xul reference home [
examples | attributes | properties | methods | related ] this element should be used in place of the window element for dialog boxes.
...1, buttonaccesskeyextra2, buttonaccesskeyhelp, buttonalign, buttondir, buttondisabledaccept, buttonlabelaccept, buttonlabelcancel, buttonlabeldisclosure, buttonlabelextra1, buttonlabelextra2, buttonlabelhelp, buttonorient, buttonpack, buttons, defaultbutton, title properties buttons, defaultbutton methods acceptdialog, canceldialog, centerwindowonscreen, getbutton, movetoalertposition
examples <?xml version="1.0"?> <?xml-stylesheet href="chrome://global/skin/global.css" type="text/css"?> <dialog id="donothing" title="dialog example" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" buttons="accept,cancel" buttonlabelcancel="cancel" buttonlabelaccept="save"> <dialogheader title="options" description="my preferences"/> <groupbox> <caption label="co...
dialogheader - Archive of obsolete content
« xul reference home [
examples | attributes | properties | methods | related ] a heading row for a dialog box.
... attributes crop, description, title
examples <?xml version="1.0"?> <?xml-stylesheet href="chrome://global/skin/global.css" type="text/css"?> <dialog id="donothing" title="dialog example" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <dialogheader title="my dialog" description="example dialog"/> <!-- other widgets --> </dialog> 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.
dropmarker - Archive of obsolete content
« xul reference home [
examples | attributes | properties | methods | related ] a dropmarker is a button with an arrow which will reveal more details when pressed.
...
examples properties accessibletype attributes inherited from xul element align, allowevents, allownegativeassertions, class, coalesceduplicatearcs, collapsed, container, containment, context, contextmenu, datasources, dir, empty, equalsize, flags, flex, height, hidden, id, insertafter, insertbefore, left, maxheight, maxwidth, menu, minheight, minwidth, mousethrough, observes, ordinal, orient, pack, persist, popup, position, preference-editable, querytype, ref, removeelement, sortdirection, sortresource, sortresource2, statustext, style, template, tooltip, tooltiptext,...
editor - Archive of obsolete content
« xul reference home [
examples | attributes | properties | methods | related ] a frame which is expected to contain an editable document.
... attributes editortype, src, type properties accessibletype, commandmanager, contentdocument, 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" typ...
grippy - Archive of obsolete content
« xul reference home [
examples | attributes | properties | methods | related ] an element that may be used inside a splitter which can be used to collapse a sibling element of the splitter.
...
examples (example needed) attributes inherited from xul element align, allowevents, allownegativeassertions, class, coalesceduplicatearcs, collapsed, container, containment, context, contextmenu, datasources, dir, empty, equalsize, flags, flex, height, hidden, id, insertafter, insertbefore, left, maxheight, maxwidth, menu, minheight, minwidth, mousethrough, observes, ordinal, orient, pack, persist, popup, position, preference-editable, querytype, ref, removeelement, sortdirection, sortresource, sortresource2, statustext, style, template, tooltip, tooltiptext, top, uri, wait-cursor, width properties inherited properties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextmenu, controllers, da...
groupbox - Archive of obsolete content
« xul reference home [
examples | attributes | properties | methods | related ] the groupbox is used to group related elements together.
... properties accessibletype
examples <groupbox> <caption label="settings"/> <radiogroup> <radio label="black and white"/> <radio label="colour"/> </radiogroup> <checkbox label="enabled"/> </groupbox> attributes inherited from xul element align, allowevents, allownegativeassertions, class, coalesceduplicatearcs, collapsed, container, containment, context, contextmenu, datasources, dir, empty, equalsize, flag...
iframe - Archive of obsolete content
« xul reference home [
examples | attributes | properties | methods | related ] an inner frame that works much like the html <iframe> element.
... attributes showcaret, src, type, transparent properties accessibletype, contentdocument, contentwindow, docshell, webnavigation
examples <iframe src="table.php" flex="2" id="browsertable" name="table_frame"/> selecting an url from a menu <menulist oncommand="donav(this);"> <menupopup> <menuitem label="mozilla" value="http://mozilla.org" /> <menuitem label="slashdot" value="http://slashdot.org"/> <menuitem label="sourceforge" value="http://sf.net" /> <menuitem label="freshmeat" value="http://freshmeat.net"/> ...
image - Archive of obsolete content
« xul reference home [
examples | attributes | properties | methods | related ] summary an element that displays an image, much like the html img element.
... attributes onerror, onload, src, validate properties accessibletype, src style classes alert-icon, error-icon, message-icon, question-icon
examples <image src='firefoxlogo.png' width='135' height='130'/> attributes onerror type: script code this event is sent to an image element when an error occurs loading the image.
key - Archive of obsolete content
« xul reference home [
examples | attributes | properties | methods | related ] the key element defines a window-global keyboard shortcut and must be placed inside a keyset element.
... attributes command, disabled, key, keycode, keytext, modifiers, oncommand, phase
examples (example needed) attributes command type: id set to the id of a command element that is being observed by the element.
keyset - Archive of obsolete content
« xul reference home [
examples | attributes | properties | methods | related ] a container element for key elements.
... attributes disabled
examples <keyset> <key id="sample-key" modifiers="shift" key="r"/> </keyset> attributes inherited from xul element align, allowevents, allownegativeassertions, class, coalesceduplicatearcs, collapsed, container, containment, context, contextmenu, datasources, dir, empty, equalsize, flags, flex, height, hidden, id, insertafter, insertbefore, left, maxheight, maxwidth, menu, minheight, minwidth, mousethrough, observes, ordinal, orient, pack, persist, popup, position, preference-editable, querytype, ref, removeelement, sortdirection, sortresource, sortresource2, statustext, style, template, tooltip, tooltiptext, top, uri, wait-cursor, width disabled typ...
label - Archive of obsolete content
« xul reference home [
examples | attributes | properties | methods | related ] this element is used to provide a label for a control element.
... attributes accesskey, control, crop, disabled, href, value properties accesskey, accessibletype, control, crop, disabled, value style classes header, indent, monospace, plain, small-margin, text-link
examples <label value="email address" control="email"/> <textbox id="email"/> attributes accesskey type: character this should be set to a character that is used as a shortcut key.
listbox - Archive of obsolete content
« xul reference home [
examples | attributes | properties | methods | related ] this element is used to create a list of items where one or more of the items may be selected.
...value methods additemtoselection, appenditem, clearselection, ensureelementisvisible, ensureindexisvisible, getindexoffirstvisiblerow, getindexofitem, getitematindex, getnumberofvisiblerows, getrowcount, getselecteditem, insertitemat, invertselection, movebyoffset, removeitemat, removeitemfromselection, scrolltoindex, selectall, selectitem, selectitemrange, timedselect, toggleitemselection
examples <listbox id="thelist"> <listitem label="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"/> </listco...
listcell - Archive of obsolete content
« xul reference home [
examples | attributes | properties | methods | related ] a single cell of a listbox.
... attributes crop, disabled, image, label, type properties disabled style classes listcell-iconic,
examples (example needed) 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.
listcol - Archive of obsolete content
« xul reference home [
examples | attributes | properties | methods | related ] a column in a listbox.
...
examples example <!-- a two column listbox with one column flexible --> <listbox> <listhead> <listheader label="first"/> <listheader label="last"/> </listhead> <listcols> <listcol flex="1"/> <listcol/> </listcols> <listitem> <listcell label="buck"/> <listcell label="rogers"/> </listitem> <listitem> <listcell label="john"/> <listcell label="painter"/> </listitem> </listbox> attributes inherited from xul element align, allowevents, allownegativeassertions, class, coalesceduplicatearcs, collapsed, container, containment, context, contextmenu, datasources, dir, empty, equalsize, flags, flex, height, hidden, id, insertafter, insertbefore, left, maxheight, maxwidth, menu, minheig...
listhead - Archive of obsolete content
« xul reference home [
examples | attributes | properties | methods | related ] a header row of a listbox.
... attributes disabled properties acesssibletype, disabled
examples (example needed) attributes disabled type: boolean indicates whether the element is disabled or not.
listheader - Archive of obsolete content
« xul reference home [
examples | attributes | properties | methods | related ] a header for a single column in a listbox.
... attributes disabled properties acesssibletype
examples <listbox> <listhead> <listheader label="name"/> <listheader label="occupation"/> </listhead> <listitem> <listcell label="george"/> <listcell label="house painter"/> </listitem> <listitem> <listcell label="mary ellen"/> <listcell label="candle maker"/> </listitem> <listitem> <listcell label="roger"/> <listcell label="swashbuckler"/> </listitem> </listbox> attributes disabled type: boolean indicates whether the element is disabled or not.
listitem - Archive of obsolete content
« xul reference home [
examples | attributes | properties | methods | related ] a single row in a listbox.
... attributes accesskey, checked, command, crop, current, disabled, image, label, preference, selected, tabindex, type, value properties accesskey, accessible, checked, control, crop, current, disabled, image, label, selected, tabindex, value style classes listitem-iconic
examples <listbox id="thelist"> <listitem label="ruby"/> <listitem label="emerald"/> <listitem label="sapphire" selected="true"/> <listitem label="diamond"/> </listbox> attributes accesskey type: character this should be set to a character that is used as a shortcut key.
member - Archive of obsolete content
« xul reference home [
examples | attributes | properties | methods | related ] used within a rule's conditions element to match elements that are containers or are contained within another element.
... properties child, container
examples (example needed) attributes inherited from xul element align, allowevents, allownegativeassertions, class, coalesceduplicatearcs, collapsed, container, containment, context, contextmenu, datasources, dir, empty, equalsize, flags, flex, height, hidden, id, insertafter, insertbefore, left, maxheight, maxwidth, menu, minheight, minwidth, mousethrough, observes, ordinal, orient, pack, persist, popup, position, preference-editable, querytype, ref, removeelement, sortdirection, sortresource, sortresource2, statustext, style, template, tooltip, tooltiptext, top, uri, wait-cursor, width properties child type: ?
menubar - Archive of obsolete content
« xul reference home [
examples | attributes | properties | methods | related ] a container that usually contains menu elements.
... attributes grippyhidden, statusbar properties accessibletype, statusbar
examples <menubar id="sample-menubar"> <menu id="action-menu" label="action"> <menupopup id="action-popup"> <menuitem label="new"/> <menuitem label="save" disabled="true"/> <menuitem label="close"/> <menuseparator/> <menuitem label="quit"/> </menupopup> </menu> <menu id="edit-menu" label="edit"> <menupopup id="edit-popup"> <menuitem label="undo"/> <menuitem labe...
menuitem - Archive of obsolete content
« xul reference home [
examples | attributes | properties | methods | related ] a single choice in a menupopup element.
... attributes acceltext, accesskey, allowevents, autocheck, checked, closemenu, command, crop, description, disabled, image, key, label, name, selected, tabindex, type, validate, value properties accessibletype, accesskey, command, control, crop, disabled, image, label, labelelement, parentcontainer, selected, tabindex, value style classes menuitem-iconic, menuitem-non-iconic
examples <menulist> <menupopup> <menuitem label="option 1" value="1"/> <menuitem label="option 2" value="2"/> <menuitem label="option 3" value="3"/> <menuitem label="option 4" value="4"/> </menupopup> </menulist> attributes acceltext type: string text that appears beside the menu label to indicate the shortcut key (accelerator key) to use to invoke the com...
menulist - Archive of obsolete content
« xul reference home [
examples | attributes | properties | methods | related ] an element that can be used for drop-down choice lists.
...oncommand, open, preference, readonly, sizetopopup, tabindex, value properties accessibletype, crop, description, disableautoselect, disabled, editable, editor, image, inputfield, itemcount, label, menuboxobject, menupopup, open, selectedindex, selecteditem, tabindex, value methods appenditem, contains, getindexofitem, getitematindex, insertitemat, removeallitems, removeitemat, select
examples <menulist> <menupopup> <menuitem label="option 1" value="1"/> <menuitem label="option 2" value="2"/> <menuitem label="option 3" value="3"/> <menuitem label="option 4" value="4"/> </menupopup> </menulist> attributes accesskey type: character this should be set to a character that is used as a shortcut key.
menuseparator - Archive of obsolete content
« xul reference home [
examples | attributes | properties | methods | related ] used to create a separator between menu items.
... attributes acceltext, accesskey, allowevents, command, crop, disabled, image, label, selected, tabindex, value properties accessibletype, accesskey, command, control, crop, disabled, image, label, labelelement, parentcontainer, selected, tabindex, value
examples <menu label="menu"> <menupopup> <menuitem label="item1"/> <menuseparator/> <menuitem label="item2"/> <menuitem label="item3"/> </menupopup> </menu> attributes acceltext type: string text that appears beside the menu label to indicate the shortcut key (accelerator key) to use to invoke the command.
notification - Archive of obsolete content
« xul reference home [
examples | attributes | properties | methods | related ] the notification is used to display an informative message.
... attributes image, label, priority, persistence, type, value properties accessibletype, control, image, label, priority, persistence, type, value methods close
examples <notification label="this is a warning"/> attributes image type: uri the uri of the image to appear on the element.
notificationbox - Archive of obsolete content
« xul reference home [
examples | attributes | properties | methods | related ] the notificationbox element is used to display notifications above an element.
... also it is possible to call function with the same name (they are different) of global object gbrowser: notifybox = gbrowser.getnotificationbox()
examples <notificationbox flex="1"> <browser src="http://www.mozilla.org"/> </notificationbox> there is a more complex code available in the code snippets area.
observes - Archive of obsolete content
« xul reference home [
examples | attributes | properties | methods | related ] the observes element can be used to listen to a broadcaster and receive events and attributes from it.
... attributes attribute, element
examples (example needed) attributes attribute type: attribute name the attribute that the observer is observing.
page - Archive of obsolete content
« xul reference home [
examples | attributes | properties | methods | related ] similar to a window, except it should be used for xul files that are to be loaded into an iframe.
...
examples (example needed) attributes inherited from xul element align, allowevents, allownegativeassertions, class, coalesceduplicatearcs, collapsed, container, containment, context, contextmenu, datasources, dir, empty, equalsize, flags, flex, height, hidden, id, insertafter, insertbefore, left, maxheight, maxwidth, menu, minheight, minwidth, mousethrough, observes, ordinal, orient, pack, persist, popup, position, preference-editable, querytype, ref, removeelement, sortdirection, sortresource, sortresource2, statustext, style, template, tooltip, tooltiptext, top, uri, wait-cursor, width properties inherited properties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextmenu, controllers, database, datasources, dir, , , flex, height, hidden, ...
popupset - Archive of obsolete content
« xul reference home [
examples | attributes | properties | methods | related ] a container for menupopup, panel and tooltip elements.
...
examples <popupset> <menupopup id="clipmenu"> <menuitem label="cut"/> <menuitem label="copy"/> <menuitem label="paste"/> </menupopup> </popupset> <label value="right click for popup" context="clipmenu"/> attributes inherited from xul element align, allowevents, allownegativeassertions, class, coalesceduplicatearcs, collapsed, container, containment, context, contextmenu, datasources, dir, empty, equalsize, flags, flex, height, hidden, id, insertafter, insertbefore, left, maxheight, maxwidth, menu, minheight, minwidth, mousethrough, observes, ordinal, orient, pack, persist, popup, position, preference-editable, querytype, ref, removeel...
progressmeter - Archive of obsolete content
« xul reference home [
examples | attributes | properties | methods | related ] a meter which can be used to display the progress of a lengthy operation.
... attributes max, mode, value properties 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) ?
query - Archive of obsolete content
« xul reference home [
examples | attributes | properties | methods | related ] used to specify the query for a template.
... attributes expr
examples (example needed) attributes expr type: string for xml queries, an xpath expression which returns results.
radio - Archive of obsolete content
« xul reference home [
examples | attributes | properties | methods | related ] an element that can be turned on and off.
... attributes accesskey, command, crop, disabled, focused, group, image, label, selected, tabindex, value properties accesskey, accessibletype, control, crop, disabled, image, label, radiogroup, selected, tabindex, value
examples <radiogroup> <radio id="orange" label="red" accesskey="r"/> <radio id="violet" label="green" accesskey="g" selected="true"/> <radio id="yellow" label="blue" accesskey="b" disabled="true"/> </radiogroup> attributes accesskey type: character this should be set to a character that is used as a shortcut key.
radiogroup - Archive of obsolete content
« xul reference home [
examples | attributes | properties | methods | related ] a group of radio buttons.
... 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.
resizer - Archive of obsolete content
« xul reference home [
examples | attributes | properties | methods | related ] an element used for window resizing.
... attributes dir, element, type
examples resizing a window <window xmlns="http://www.mozilla.org/keymaster/gat...re.is.only.xul" hidechrome="true" windowtype="main" orient="vertical" sizemode="normal" width="400" height="300" persist="screenx screeny width height"> <hbox flex="1"> <vbox width="2" style="background-color: grey;"> <resizer dir="topleft" height="2" style="cursor: nw-resize;"/> <resizer dir="left" flex="1" style...
richlistbox - Archive of obsolete content
« xul reference home [
examples | attributes | properties | methods | related ] this element is used to create a list of listitems (richlistitems), similar to a listbox, but is designed to be used when the items do not contain simple text content.
...value methods additemtoselection, appenditem, clearselection, ensureelementisvisible, ensureindexisvisible, getindexoffirstvisiblerow, getindexofitem, getitematindex, getnumberofvisiblerows, getrowcount, getselecteditem, insertitemat, invertselection, movebyoffset, removeitemat, removeitemfromselection, scrolltoindex, selectall, selectitem, selectitemrange, timedselect, toggleitemselection
examples <richlistbox> <richlistitem> <description>a xul description!</description> </richlistitem> <richlistitem> <button label="a xul button"/> </richlistitem> </richlistbox> the richlistbox element contains multiple richlistitem elements, which can contain any content.
richlistitem - Archive of obsolete content
« xul reference home [
examples | attributes | properties | methods | related ] an individual item in a richlistbox.
... attributes disabled, searchlabel, selected, tabindex, value properties accessible, control, disabled, label, selected, tabindex, value
examples (example needed) attributes disabled type: boolean indicates whether the element is disabled or not.
rule - Archive of obsolete content
« xul reference home [
examples | attributes | properties | methods | related ] a rule is used in a template.
... attributes iscontainer, isempty, parent, parsetype
examples (example needed) attributes iscontainer type: boolean indicates whether rules match based on containment.
scale - Archive of obsolete content
« xul reference home [
examples | attributes | properties | methods | related ] a scale (sometimes referred to as a "slider") allows the user to select a value from a range.
... attributes dir, disabled, increment, max, min, movetoclick, pageincrement, tabindex, value properties disabled, max, min, increment, pageincrement, tabindex, value, methods decrease, decreasepage, increase, increasepage,
examples horizontal scale: <scale min="1" max="10"/> vertical scale: <scale min="1" max="10" orient="vertical"/> attributes dir type: one of the values below the direction in which the child elements of the element are placed.
script - Archive of obsolete content
« xul reference home [
examples | attributes | properties | methods | related ] much like the html script element, this is used to declare a script to be used by the xul window.
... attributes src, type
examples <script src="test.js"/> <script src="http://example.com/js/test.js"/> <script> function foo(){ // code } </script> attributes src type: uri the uri of the script.
scrollbar - Archive of obsolete content
« xul reference home [
examples | attributes | properties | methods | related ] when a container's contents which are larger that the size of the container, scroll bars may be placed at the side of the container to allow the user to scroll around in the container.
... attributes curpos, increment, maxpos, pageincrement
examples <scrollbar curpos="5" maxpos="50"/> attributes curpos type: integer the current position of the scrollbar, which ranges from 0 to the value of the maxpos attribute.
scrollbox - Archive of obsolete content
« xul reference home [
examples | attributes | properties | methods | related ] a box that has additional functions that can be used to scroll the content.
...
examples the following shows the xul for a bunch of labels.
scrollcorner - Archive of obsolete content
« xul reference home [
examples | attributes | properties | methods | related ] this element is used for the small box where the horizontal and vertical scrollbars meet.
...
examples (example needed) attributes inherited from xul element align, allowevents, allownegativeassertions, class, coalesceduplicatearcs, collapsed, container, containment, context, contextmenu, datasources, dir, empty, equalsize, flags, flex, height, hidden, id, insertafter, insertbefore, left, maxheight, maxwidth, menu, minheight, minwidth, mousethrough, observes, ordinal, orient, pack, persist, popup, position, preference-editable, querytype, ref, removeelement, sortdirection, sortresource, sortresource2, statustext, style, template, tooltip, tooltiptext, top, uri, wait-cursor, width properties inherited properties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextmenu, controllers, database, datasources, dir, , , flex, height, hidden, ...
separator - Archive of obsolete content
« xul reference home [
examples | attributes | properties | methods | related ] creates a small separating gap between elements.
... attributes orient style classes groove, groove-thin, thin
examples <separator class="groove-thin"/> attributes orient type: one of the values below used to specify whether the separator is a horizontal or vertical separator.
spacer - Archive of obsolete content
« xul reference home [
examples | attributes | properties | methods | related ] an element that takes up space but does not display anything.
...
examples <box> <button label="left"/> <spacer flex="1"/> <button label="right"/> </box> attributes inherited from xul element align, allowevents, allownegativeassertions, class, coalesceduplicatearcs, collapsed, container, containment, context, contextmenu, datasources, dir, empty, equalsize, flags, flex, height, hidden, id, insertafter, insertbefore, left, maxheight, maxwidth, menu, minheight, minwidth, mousethrough, observes, ordinal, orient, pack, persist, popup, position, preference-editable, querytype, ref, rem...
splitter - Archive of obsolete content
« xul reference home [
examples | attributes | properties | methods | related ] an element which should appear before or after an element inside a container.
... attributes collapse, resizeafter, resizebefore, state, substate style classes tree-splitter
examples <!-- this bar has some styling associated with it.
stack - Archive of obsolete content
« xul reference home [
examples | attributes | properties | methods | related ] an element that renders its children on top of each other.
...
examples <stack> <hbox flex="1"> <image src="chrome://xulschoolhello/skin/stack-bg.png" flex="1"left="10"right="10" top="10" bottom="10"/> </hbox> <hbox> <!-- some content here.
statusbar - Archive of obsolete content
« xul reference home [
examples | attributes | properties | methods | related ] an element used to create a status bar, usually placed along the bottom of a window.
... properties accessibletype
examples <statusbar> <statusbarpanel label="left panel"/> <spacer flex="1"/> <progressmeter mode="determined" value="82"/> <statusbarpanel label="right panel"/> </statusbar> attributes inherited from xul element align, allowevents, allownegativeassertions, class, coalesceduplicatearcs, collapsed, container, containment, context, contextmenu, datasources, dir, empty, equalsize, flags, flex, height, hidden, id, insertafter, insertbefore, left, maxheight, maxwidth, menu, minheight, minwidth, mousethrough, observes, ordinal, orient, pack, persist, popup, position, preference-editable, querytype, ref, removeelement, sortdirection, sortresource, sortreso...
<statusbarpanel> - Archive of obsolete content
« xul reference home [
examples | attributes | properties | methods | related ] firefox 4 note the status bar has been removed.
... attributes crop, image, label properties image, label style classes statusbarpanel-iconic, statusbarpanel-iconic-text, statusbarpanel-menu-iconic
examples <statusbar> <statusbarpanel label="left panel"/> <spacer flex="1"/> <progressmeter mode="determined" value="82"/> <statusbarpanel label="right panel"/> </statusbar> 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.
stringbundle - Archive of obsolete content
« xul reference home [
examples | attributes | properties | methods | related ] an element which can be used to load localized resources from property files.
... the "src" attribute accepts only absolute chrome:// urls (see bugs 133698, 26291) attributes src properties applocale , src, stringbundle, strings methods getformattedstring, getstring
examples (example needed) attributes src type: uri the uri of the property file that contains the localized strings.
stringbundleset - Archive of obsolete content
« xul reference home [
examples | attributes | properties | methods | related ] a container for stringbundle elements.
...
examples (example needed) attributes inherited from xul element align, allowevents, allownegativeassertions, class, coalesceduplicatearcs, collapsed, container, containment, context, contextmenu, datasources, dir, empty, equalsize, flags, flex, height, hidden, id, insertafter, insertbefore, left, maxheight, maxwidth, menu, minheight, minwidth, mousethrough, observes, ordinal, orient, pack, persist, popup, position, preference-editable, querytype, ref, removeelement, sortdirection, sortresource, sortresource2, statustext, style, template, tooltip, tooltiptext, top, uri, wait-cursor, width properties inherited properties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextmenu, controllers, database, datasources, dir, , , flex, height, hidden, ...
tab - Archive of obsolete content
« xul reference home [
examples | attributes | properties | methods | related ] a single tab which should be placed inside a tabs element.
... attributes accesskey, afterselected, beforeselected, command, crop, disabled, first-tab, image, label, last-tab, linkedpanel, oncommand, pending, pinned, selected, tabindex, unread, validate, value properties accesskey, accessibletype, command, control, crop, disabled, image, label, linkedpanel, selected, tabindex, value
examples (example needed) attributes accesskey type: character this should be set to a character that is used as a shortcut key.
tabbox - Archive of obsolete content
« xul reference home [
examples | attributes | properties | methods | related ] a container used to display a set of tabbed pages of elements.
... attributes eventnode, handlectrlpageupdown, handlectrltab properties accessibletype, eventnode, handlectrlpageupdown, handlectrltab, selectedindex, selectedpanel, selectedtab, tabs, tabpanels
examples <tabbox id="mytablist" selectedindex="2"> <tabs> <tab label="a first tab"/> <tab label="second tab"/> <tab label="another tab"/> <tab label="last tab"/> </tabs> <tabpanels> <tabpanel><!-- tabpanel first elements go here --></tabpanel> <tabpanel><!-- tabpanel second elements go here --></tabpanel> <tabpanel><button label="click me"/></tabpanel> <tabpanel><!--...
tabbrowser - Archive of obsolete content
« xul reference home [
examples | attributes | properties | methods | related ] this element is used for holding a set of read-only views of web documents.
... see code snippets: tabbed browser for
examples.
tabpanel - Archive of obsolete content
« xul reference home [
examples | attributes | properties | methods | related ] a individual panel in a tabpanels element.
...
examples (example needed) attributes inherited from xul element align, allowevents, allownegativeassertions, class, coalesceduplicatearcs, collapsed, container, containment, context, contextmenu, datasources, dir, empty, equalsize, flags, flex, height, hidden, id, insertafter, insertbefore, left, maxheight, maxwidth, menu, minheight, minwidth, mousethrough, observes, ordinal, orient, pack, persist, popup, position, preference-editable, querytype, ref, removeelement, sortdirection, sortresource, sortresource2, statustext, style, template, tooltip, tooltiptext, top, uri, wait-cursor, width properties inherited properties align, , allowevents, , bo...
tabpanels - Archive of obsolete content
« xul reference home [
examples | attributes | properties | methods | related ] a container to hold the set of pages in a tabbox.
... attributes selectedindex properties selectedindex, selectedpanel
examples (example needed) attributes selectedindex type: integer gets and sets the index of the currently selected panel.
tabs - Archive of obsolete content
« xul reference home [
examples | attributes | properties | methods | related ] a row of tabs.
... attributes closebutton, disableclose, disabled, onclosetab, onnewtab, onselect, setfocus, selectedindex, tabbox, tabindex, tooltiptextnew, value, properties accessibletype, disabled, itemcount, selectedindex, selecteditem, tabindex, value, methods advanceselectedtab, appenditem, getindexofitem, getitematindex, insertitemat, removeitemat
examples (example needed) attributes closebutton obsolete since gecko 1.9.2 type: boolean if this attribute is set to true, the tabs row will have a "new tab" button and "close" button on the ends.
template - Archive of obsolete content
« xul reference home [
examples | attributes | properties | methods | related ] used to declare a template for rule-based construction of elements.
... attributes container, member
examples (example needed) attributes container type: string may optionally be set to the variable to use as the container or reference variable.
textbox - Archive of obsolete content
« xul reference home [
examples | attributes | properties | methods | related ] an input field where the user can enter text.
...ssibletype, clickselectsall, decimalplaces, decimalsymbol, defaultvalue, disabled, editor, emptytext, increment, inputfield, label, max, maxlength, min, placeholder, readonly, searchbutton, selectionend, selectionstart, size, spinbuttons, tabindex, textlength, timeout, type, value, valuenumber, wraparound methods decrease, increase, reset, select, setselectionrange style classes plain
examples <vbox> <label control="your-name" value="enter your name:"/> <textbox id="your-name" value="john"/> </vbox> attributes cols type: integer for multiline textboxes, the number of columns to display.
textnode - Archive of obsolete content
« xul reference home [
examples | attributes | properties | methods | related ] normally when substituting rdf resources in template rules, you place the rdf property name inside an attribute value preceded with rdf:.
... attributes value
examples (example needed) attributes value type: uri the text value to display.
timepicker - Archive of obsolete content
« xul reference home [
examples | attributes | properties | methods | related ] the timepicker is used to allow the user to enter a time.
... 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.
titlebar - Archive of obsolete content
« xul reference home [
examples | attributes | properties | methods | related ] boxes created with the titlebar element behave just like a normal window titlebar: when the element is clicked and dragged, the window moves with it.
...
examples this xul file will create a hud-style window that can be moved with the mouse.
toolbar - Archive of obsolete content
« xul reference home [
examples | attributes | properties | methods | related ] a container which typically contains a row of buttons.
... attributes autohide, currentset, customindex, customizable, defaultset, grippyhidden, grippytooltiptext, height, iconsize, mode, toolbarname properties accessibletype, currentset, firstpermanentchild, lastpermanentchild, toolbarname, toolboxid methods insertitem style classes chromeclass-toolbar
examples <toolbox> <toolbar id="nav-toolbar"> <toolbarbutton id="nav-users" accesskey="u" label="users"/> <toolbarbutton id="nav-groups" accesskey="p" label="groups"/> <toolbarbutton id="nav-events" accesskey="e" label="events" disabled="true"/> </toolbar> </toolbox> attributes autohide type: boolean when set to true, the toolbar will be invisible unless the alt key is presse...
toolbargrippy - Archive of obsolete content
« xul reference home [
examples | attributes | properties | methods | related ] not in firefox the notch on the side of a toolbar which can be used to collapse and expand it.
... properties accessible
examples (example needed) attributes inherited from xul element align, allowevents, allownegativeassertions, class, coalesceduplicatearcs, collapsed, container, containment, context, contextmenu, datasources, dir, empty, equalsize, flags, flex, height, hidden, id, insertafter, insertbefore, left, maxheight, maxwidth, menu, minheight, minwidth, mousethrough, observes, ordinal, orient, pack, persist, popup, position, preference-editable, querytype, ref, removeelement, sortdirection, sortresource, sortresource2, statustext, style, template, tooltip, tooltiptext, top, uri, wait-cursor, width properties ...
toolbaritem - Archive of obsolete content
« xul reference home [
examples | attributes | properties | methods | related ] firefox only an item that appears on a toolbar.
...
examples <toolbaritem> <menulist label="bus"> <menupopup> <menuitem label="car"/> <menuitem label="taxi"/> <menuitem label="bus" selected="true"/> <menuitem label="train"/> </menupopup> </menulist> </toolbaritem> <toolbaritem id="sample-toolbutton-unified"> <toolbarbutton id="myext-button1" class="toolbarbutton-1" label="label1" /> ...
toolbarpalette - Archive of obsolete content
« xul reference home [
examples | attributes | properties | methods | related ] firefox only the item is a palette of available toolbar items.
...
examples <toolbarpalette id="browsertoolbarpalette"> <toolbarbutton id="toolbarpalette-button" class="toolbarbutton-class" label="&mylabel;" tooltiptext="&mytiptext;" oncommand="somefunction()"/> </toolbarpalette> attributes inherited from xul element align, allowevents, allownegativeassertions, class, coalesceduplicatearcs, col...
toolbarseparator - Archive of obsolete content
« xul reference home [
examples | attributes | properties | methods | related ] creates a separator between groups of toolbar items.
... properties accessibletype
examples <toolbox> <toolbar> <toolbarbutton label="button 1"/> <toolbarseparator /> <toolbarbutton label="button 2"/> </toolbar> </toolbox> attributes inherited from xul element align, allowevents, allownegativeassertions, class, coalesceduplicatearcs, collapsed, container, containment, context, contextmenu, datasources, dir, empty, equalsize, flags, flex, height, hidden, id, insertafter, insertbefore, left, maxheight, maxwidth, menu, minheight, minwidth, mousethrough, observes, ordinal, orient, pack, persist, popup, position, preference-editable, querytype, ref, removeelement, sortdirection, sortresource, sortresource2, statustext...
toolbarset - Archive of obsolete content
« xul reference home [
examples | attributes | properties | methods | related ] firefox only this element is used as a container for custom toolbars, which are added in the custom toolbar dialog.
...
examples (example needed) attributes inherited from xul element align, allowevents, allownegativeassertions, class, coalesceduplicatearcs, collapsed, container, containment, context, contextmenu, datasources, dir, empty, equalsize, flags, flex, height, hidden, id, insertafter, insertbefore, left, maxheight, maxwidth, menu, minheight, minwidth, mousethrough, observes, ordinal, orient, pack, persist, popup, position, preference-editable, querytype, ref, removeelement, sortdirection, sortresource, sortresource2, statustext, style, template, tooltip, tooltiptext, top, uri, wait-cursor, width properties inherited properties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextmenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , ...
toolbarspacer - Archive of obsolete content
« xul reference home [
examples | attributes | properties | methods | related ] firefox only a space between toolbar items.
... properties accessibletype
examples (example needed) attributes inherited from xul element align, allowevents, allownegativeassertions, class, coalesceduplicatearcs, collapsed, container, containment, context, contextmenu, datasources, dir, empty, equalsize, flags, flex, height, hidden, id, insertafter, insertbefore, left, maxheight, maxwidth, menu, minheight, minwidth, mousethrough, observes, ordinal, orient, pack, persist, popup, position, preference-editable, querytype, ref, removeelement, sortdirection, sortresource, sortresource2, statustext, style, template, tooltip, tooltiptext, top, uri, wait-cursor, width properties accessibletype type: integer a value indicating the type of accessibility object for the element.
toolbarspring - Archive of obsolete content
« xul reference home [
examples | attributes | properties | methods | related ] firefox only a flexible space between toolbar items.
... properties accessibletype
examples (example needed) attributes inherited from xul element align, allowevents, allownegativeassertions, class, coalesceduplicatearcs, collapsed, container, containment, context, contextmenu, datasources, dir, empty, equalsize, flags, flex, height, hidden, id, insertafter, insertbefore, left, maxheight, maxwidth, menu, minheight, minwidth, mousethrough, observes, ordinal, orient, pack, persist, popup, position, preference-editable, querytype, ref, removeelement, sortdirection, sortresource, sortresource2, statustext, style, template, tooltip, tooltiptext, top, uri, wait-cursor, width properties accessibletype type: integer a value indicating the type of accessibility object for the element.
toolbox - Archive of obsolete content
« xul reference home [
examples | attributes | properties | methods | related ] a container for toolbars.
... properties accessible, customtoolbarcount, externaltoolbars, palette, toolbarset methods appendcustomtoolbar, collapsetoolbar, expandtoolbar
examples <?xml version="1.0"?> <?xml-stylesheet href="chrome://global/skin/" type="text/css"?> <window id="yourwindow" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" title="toolbox example" width="300"> <toolbox> <toolbar> <toolbarbutton label="back"/> <toolbarbutton label="forward"/> <toolbarbutton label="home"/> </toolbar> <toolbar> <toolba...
treecol - Archive of obsolete content
« xul reference home [
examples | attributes | properties | methods | related ] a column of a tree.
... attributes crop, cycler, dragging, editable, fixed, hidden, hideheader, ignoreincolumnpicker, label, primary, sort, sortactive, sortdirection, src, type, width properties accessibletype style classes treecol-image
examples this example shows a checkbox in the first column, requires the style below.
treecols - Archive of obsolete content
« xul reference home [
examples | attributes | properties | methods | related ] a group of treecol elements.
... attributes pickertooltiptext properties accessibletype
examples (example needed) attributes pickertooltiptext type: string the text for the tooltip on the column picker.
treeitem - Archive of obsolete content
« xul reference home [
examples | attributes | properties | methods | related ] a treeitem should be placed inside a treechildren element and should contain treerow elements.
... attributes container, empty, label, open, uri
examples (example needed) attributes container type: boolean set to true if the element is to act as a container which can have child elements.
treerow - Archive of obsolete content
« xul reference home [
examples | attributes | properties | methods | related ] a single row in a tree.
... attributes properties
examples (example needed) attributes properties type: space-separated list of property names sets the properties of the element, which can be used to style the element.
treeseparator - Archive of obsolete content
« xul reference home [
examples | attributes | properties | methods | related ] used to place a separator row in a tree.
... attributes properties
examples (example needed) attributes properties type: space-separated list of property names sets the properties of the element, which can be used to style the element.
triple - Archive of obsolete content
« xul reference home [
examples | attributes | properties | methods | related ] a triple can be included inside a rule's conditions element.
... attributes object, predicate, subject
examples (example needed) attributes object type: string the object of the element.
where - Archive of obsolete content
« xul reference home [
examples | attributes | properties | methods | related ] indicate a condition that must match for a template result to be used.
... attributes ignorecase, multiple, negate, rel, subject, value
examples (example needed) attributes ignorecase type: boolean set to true to indicate that the case does not matter when making comparisons.
window - Archive of obsolete content
« xul reference home [
examples | attributes | properties | methods | related ] describes the structure of a top-level window.
... attributes accelerated, chromemargin, disablechrome, disablefastfind, drawintitlebar, fullscreenbutton, height, hidechrome, id, lightweightthemes, lightweightthemesfooter, screenx, screeny, sizemode, title, width, windowtype
examples <?xml version="1.0"?> <?xml-stylesheet href="chrome://global/skin/" type="text/css"?> <!-- run this example using copy & paste in this live xul editor: https://github.com/km-200/xul --> <!-- extremely recommended to keep this css include!!
wizard - Archive of obsolete content
« xul reference home [
examples | attributes | properties | methods | related ] this element is used to construct a step-by-step wizard found in some applications to guide users through a task.
... attributes firstpage, lastpage, pagestep, title, windowtype properties canadvance, canrewind, currentpage, onfirstpage, onlastpage, pagecount, 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 onpages...
XULRunner Hall of Fame - Archive of obsolete content
latest release: june 2010 - build instructions utilities / prototypes ajax toolkit framework (atf) a part of the eclipse web tools platform (wtp) aliwal geocoder geocode addresses onto a map benjamin's xulrunner
examples "mybrowser is a very simple example browser", xulmine.
... an updated version of "mybrowser" that works with firefox 25.0.1+ is available in matthew kastor's xulrunner
examples at https://github.com/matthewkastor/xulrunner-
examples/ exch a currency conversion tool using updated data from http://finance.yahoo.com/currency.
Using the W3C DOM - Archive of obsolete content
instead, use the w3c dom properties and methods (
examples in the next section).
... the following
examples show how to modify the text of a span element that already exists in the html file.
-ms-filter - Archive of obsolete content
examples the following example shows how to use the -ms-filter attribute in internet explorer 8.
...use commas (,) to separate multiple values, as shown in the
examples section.
Generator comprehensions - Archive of obsolete content
r (i in it) i * 2); console.log(it2.next()); // the first value from it, doubled console.log(it2.next()); // the second value from it, doubled when a generator comprehension is used as the argument to a function, the parentheses used for the function call means that the outer parentheses can be omitted: var result = dosomething(for (i in it) i * 2); the significant difference between the two
examples being that by using the generator comprehension, you would only have to loop over the 'obj' structure once, total, as opposed to once when comprehending the array, and again when iterating through it.
...
examples simple generator comprehensions (for (i of [1, 2, 3]) i * i ); // generator function which yields 1, 4, and 9 [...(for (i of [1, 2, 3]) i * i )]; // [1, 4, 9] var abc = ['a', 'b', 'c']; (for (letters of abc) letters.tolowercase()); // generator function which yields "a", "b", and "c" generator comprehensions with if statement var years = [1954, 1974, 1990, 2006, 2010, 2014]; (for (year of years) if (year > 2000) year); // generator function which yields 2006, 2010, and 2014 (for (year of years) if (year > 2000) if (year < 2010) year); // generator function which yields 2006, the same as below: (for (year of years) if (year > 2000 && year < 2010) year); // generator function which yields 2006 generator comprehensions compared to generator function an easy way to understand g...
handler.enumerate() - Archive of obsolete content
examples the following code traps for...in statements.
... var p = new proxy({}, { enumerate(target) { return 1; } }); for (var x in p) {} // typeerror is thrown note: both
examples make use of the shorthand syntax for method definitions.
Archive of obsolete content
- some inline
examples were removed because of technical limitations.
...this article explains how to embed the windows media player activex control in web pages to support netscape 7.1, how to control the windows media player activex control using javascript and provides working
examples.
Index - Game development
3
examples demos, example, games, web this page lists a number of impressive web technology demos for you to get inspiration from, and generally have fun with.
...this article looks at exactly what is permitted in the asm.js subset, what improvements it confers, where and how you can make use of it, and further resources and
examples.
Game monetization - Game development
specific
examples can include bonus levels, better weapons or spells, or refilling the energy needed to play.
...if you focus on sharing the knowledge first and use your games just as the
examples it should be ok.
Visual typescript game engine - Game development
| ├──
examples/ | | ├── platformer/ | ├── html-components/ | | ├── register.html | | ├── login.html | | ├── games-list.html | | ├── user-profile.html | | ├── store.html | | ├── broadcaster.html | ├── index.html | ├── app-icon.ts | └── app.ts └── server/ | ├── package.json | ├── package-loc...
... create
examples demos in minimum 20 gameplay variants (table games, actions, platformers, basic demo throw the api doc etc.).
Accessible multimedia - Learn web development
transcript
examples if you use an automated service, then you'll probably have to use the user interface that the tool provides.
...in some cases it is not so bad, for example: if you are embedding audio content using a plugin technology like flash or silverlight, you can probably just provide an audio transcript in the same manner as we already showed above in the transcript
examples section.
The box model - Learn web development
the <a> element, used for links, <span>, <em> and <strong> are all
examples of elements that will display inline by default.
...
examples of different display types let's move on and have a look at some
examples.
Advanced form styling - Learn web development
you can see the live result: we've also created a couple of other
examples to give you more ideas: styled radio buttons: custom radio button styling.
... font-family: inherit; font-size: 100%; padding: 0; margin: 0; box-sizing: border-box; width: 100%; padding: 5px; height: 30px; } input[type="text"], input[type="datetime-local"], input[type="color"], select { box-shadow: inset 1px 1px 3px #ccc; border-radius: 5px; } label { margin-bottom: 5px; } button { width: 60%; margin: 0 auto; } note: if you want to test these
examples across a number of browsers simultaneously, you can find it live here (also see here for the source code).
Advanced text formatting - Learn web development
tion.value === 'show solution') { userentry = textarea.value; } else { solutionentry = textarea.value; } updatecode(); }; abbreviations another fairly common element you'll meet when looking around the web is <abbr> — this is used to wrap around an abbreviation or acronym, and provide a full expansion of the term (included inside a title attribute.) let's look at a couple of
examples: <p>we use <abbr title="hypertext markup language">html</abbr> to structure our web documents.</p> <p>i think <abbr title="reverend">rev.</abbr> green did it in the kitchen with the chainsaw.</p> these will come out looking something like this (the expansion will appear in a tooltip when the term is hovered over): note: there is another element, <acronym>, which basically does the same t...
... let's look at a few
examples.
Introduction to events - Learn web development
you've already seen events and event handlers used in many of the
examples, but let's recap just to cement our knowledge.
... this concept is explained further on david walsh's blog, with multiple
examples — see how javascript event delegation works.
Test your skills: Conditionals - Learn web development
note: in the
examples below, if there is an error in your code it will be outputted into the results panel on the page, to help you try to figure out the answer (or into the browser's javascript console, in the case of the downloadable version).
... assessment or further help you can practice these
examples in the interactive editors above.
Test your skills: Loops - Learn web development
we haven't explicitly taught this yet in the course, but you'll have seen some
examples that make use of it, and we'd like you to do some research into what dom apis you need to successfully answer the questions.
... assessment or further help you can practice these
examples in the interactive editors above.
Client-side web APIs - Learn web development
those modules typically involve simple api usage, as it is often difficult to write client-side javascript
examples without them.
... note: if you are working on a device where you don't have the ability to create your own files, you could try out (most of) the code
examples in an online coding program such as jsbin or glitch.
Arrays - Learn web development
as in previous articles, let's learn about the real basics of arrays by entering some
examples into browser developer console.
...for example, to access one of the items inside the array that is the third item inside the random array (see previous section), we could do something like this: random[2][2]; try making some more modifications to your array
examples before moving on.
Test your skills: Arrays - Learn web development
note: in the
examples below, if there is an error in your code it will be outputted into the results panel on the page, to help you try to figure out the answer (or into the browser's javascript console, in the case of the downloadable version).
... assessment or further help you can practice these
examples in the interactive editors above.
Test your skills: Math - Learn web development
note: in the
examples below, if there is an error in your code it will be outputted into the results panel on the page, to help you try to figure out the answer (or into the browser's javascript console, in the case of the downloadable version).
... assessment or further help you can practice these
examples in the interactive editors above.
Test your skills: Strings - Learn web development
note: in the
examples below, if there is an error in your code it will be outputted into the results panel on the page, to help you try to figure out the answer (or into the browser's javascript console, in the case of the downloadable version).
... assessment or further help you can practice these
examples in the interactive editors above.
Test your skills: variables - Learn web development
note: in the
examples below, if there is an error in your code it will be outputted into the results panel on the page, to help you try to figure out the answer (or into the browser's javascript console, in the case of the downloadable version).
... assessment or further help you can practice these
examples in the interactive editors above.
Useful string methods - Learn web development
let's enter some
examples into the browser developer console.
...so you'd have to actually write this: browsertype = browsertype.replace('moz','van'); active learning
examples in this section we'll get you to try your hand at writing some string manipulation code.
JavaScript object basics - Learn web development
you've been using objects all along as you've been going through these
examples, you have probably been thinking that the dot notation you've been using is very familiar.
...every time we've been working through an example that uses a built-in browser api or javascript object, we've been using objects, because such features are built using exactly the same kind of object structures that we've been looking at here, albeit more complex ones than in our own basic custom
examples.
Object prototypes - Learn web development
you'll see other
examples of prototype chain inheritance all over javascript — try looking for the methods and properties defined on the prototype of the string, date, number, and array global objects, for example.
...therefore, for more complex
examples, you'll want to use the instanceof operator instead.
Test your skills: Object-oriented JavaScript - Learn web development
note: in the
examples below, if there is an error in your code it will be outputted into the results panel on the page, to help you try to figure out the answer (or into the browser's javascript console, in the case of the downloadable version).
... assessment or further help you can practice these
examples in the interactive editors above.
Test your skills: Object basics - Learn web development
note: in the
examples below, if there is an error in your code it will be outputted into the results panel on the page, to help you try to figure out the answer (or into the browser's javascript console, in the case of the downloadable version).
... assessment or further help you can practice these
examples in the interactive editors above.
Package management basics - Learn web development
many projects will use npm, and we’ll stick to this in our
examples throughout the rest of the module.
... where npm is shown in the
examples below, pnpm can be swapped in and the command will work.
Configuring Build Options
regardless of the name of the actual file you use, we refer to this file as the mozconfig file in the
examples below.
... warning: these mozconfig files are taken from production builds and are provided as
examples only.
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.
...the following stylesheet is optional and only applies styles and icons to the built-in tree view: <?xml-stylesheet href="chrome://browser/skin/places/places.css" ?> for
examples of instantiating a tree view from javascript rather than xul, see programmatic generation of the built-in tree view.
Limitations of frame scripts
for example: nsipromptservice nsifilepicker nsixul* <need more
examples> services some services will not work in frame scripts.
...for example: nsisessionstore nsiwindowmediator <need more
examples> places api the places api can't be used inside a frame script.
Performance
the following
examples omit some boilerplate code for the sake of brevity the "better"
examples also omit some best practices and only demonstrate how to fix the problem described in their respective subtopics.
... clean up on addon unload bad: all the previous
examples, *even the "better" ones* if your addon is restartless or uses the sdk then updates or the user turning it off and on will load to unload/reload events.
Storage access policy: Block cookies from trackers
consider the following
examples: hostname on the list hostname of resource matched example.com example.com yes example.com a.b.example.com yes blah.example.com example.com no a.b.example.com c.d.example.com no blah.example.com foo.blah.example.com yes what does the storage access policy block?
...consider the following
examples: you run an ad on a social media website that is seen several times by a user, but never clicked.
ChromeWorker
examples of chromeworker's using js-ctypes are availabe on github and are linked to from the see also section below.
... see using web workers for
examples and details.
HTTP Cache
api here is a detailed description of the http cache v2 api,
examples included.
... code
examples tbd opening an entry creating a new entry recreating an already open entry implementation threading the cache api is fully thread-safe.
IPDL Type Serialization
most structures can be serialized in this manner: struct
examplestruct { int i; nscstring j; int k[4]; }; namespace ipc { template <> struct paramtraits<
examplestruct> { typedef
examplestruct paramtype; static void write(message* amsg, const paramtype& aparam) { writeparam(amsg, aparam.i); writeparam(amsg, aparam.j); for (int i = 0; i < 4; ++i) writeparam(amsg, aparam.k[i]); } static bool read(const message* amsg, void** ai...
...ter, paramtype* aresult) { if (!readparam(amsg, aiter, &(aresult->i)) || !readparam(amsg, aiter, &(aresult->j))) return false; for (int i = 0; i < 4; ++i) if (!readparam(amsg, aiter, &(aresult->k[i]))) return false; return true; } }; } // namespace ipc once you have a serializer for a type, you can serialize a collection of it (ex: an nstarray<
examplestruct>) by simply declaring "using nstarray<
examplestruct>;' in your ipdl file, then using it in a ipc method.
JavaScript-DOM Prototypes in Mozilla
if you think back to the htmlimageelement
examples above, those
examples let you define new properties on all image elements.
...a few
examples of class constructor names would be htmlimageelement, htmldocument, element, nodelist, and two
examples of class prototype names would be node and characterdata.
Localizing without a specialized tool
folder structure throughout this document, we will be using the following folder structure in all
examples: your working directory (root) mozilla-1.9.2 (en-us source, pulled from http://hg.mozilla.org/releases/mozilla-1.9.2) l10n-mozilla-1.9.2 (a directory containing localization directories, one dir per localization; often referred to as "l10n base") x-testing (a directory with your localization files) please either follow this structure closely or adjust all commands in the documentation as ...
... 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 DOM Hacking Guide
i'll take two very different
examples.
... these two
examples demonstrate the power of the dom combined with xpconnect and the javascript engine.
Mozilla Web Services Security Model
(is this correct?) web-scripts-access.xml
examples these
examples are untested!
...in the root directory of the server: <webscriptaccess xmlns="http://www.mozilla.org/2002/soap/security"> <delegate/> <allow type="none"/> </webscriptaccess> and in the services directory: <webscriptaccess xmlns="http://www.mozilla.org/2002/soap/security"> <allow type="soapv"/> <allow type="soap"/> </webscriptaccess> good
examples (needed.) references new security model for web services, the original proposal for the web-scripts-access.xml file format web services roadmap, documenting when web services features, including the security model, were first supported additional reading documentation of crossdomain.xml, a similar format used by macromedia flash player ...
Leak-hunting strategies and tips
see bug 106860 and bug 84136 for
examples.
...(this can happen equally with or without nscomptr.) see bug 38586 and bug 287847 for
examples.
Scroll-linked effects
below are a couple of
examples of effects that would not work well with asynchronous scrolling, along with equivalent versions that would work well: example 1: sticky positioning here is an implementation of a sticky-positioning effect, where the "toolbar" div will stick to the top of the screen as you scroll down.
...see the asynchronous scrolling in firefox blog post for some more
examples of effects that can be implemented using css to avoid jank.
L20n
complete with use cases and
examples of l20n in action.
...complete with use cases and
examples of l20n in action.
Anonymous Shared Memory
see the
examples below.
...in the
examples, the server creates the file-mapped shared memory, the client attaches to it.
An overview of NSS Internals
examples for the database files are key3.db and cert8.db, where the numbers are file version numbers.
...
examples are retrieving ocsp (online certificate status protocol) information or downloading a crl (certificate revocation list).
FC_Initialize
the library parameters string has this format: "configdir='dir' certprefix='prefix1' keyprefix='prefix2' secmod='file' flags= " here are some
examples.
...
examples #include <assert.h> ck_function_list_ptr pfunctionlist; ck_rv crv; ck_c_initialize_args initargs; crv = fc_getfunctionlist(&pfunctionlist); assert(crv == ckr_ok); initargs.createmutex = null; initargs.destroymutex = null; initargs.lockmutex = null; initargs.unlockmutex = null; initargs.flags = ckf_os_locking_ok; initargs.libraryparameters = "..."; initargs.preserved = null; /* invoke fc_initi...
NSS tools : certutil
usage and
examples most of the command options in the
examples listed here have more arguments available.
... the arguments included in these
examples are the most common ones or are used to illustrate a specific scenario.
NSS tools : ssltab
the following are well-known port numbers: * http 80 * https 443 * smtp 25 * ftp 21 * imap 143 * imaps 993 (imap over ssl) * nntp 119 * nntps 563 (nntp over ssl) usage and
examples you can use the ssl debugging tool to intercept any connection information.
...the following
examples show the output from commonly used combinations of options.
NSS tools : ssltap
the following are well-known port numbers: * http 80 * https 443 * smtp 25 * ftp 21 * imap 143 * imaps 993 (imap over ssl) * nntp 119 * nntps 563 (nntp over ssl) usage and
examples you can use the ssl debugging tool to intercept any connection information.
...the following
examples show the output from commonly used combinations of options.
sslfnc.html
for
examples of the callback functions listed here, see chapter 2, "getting started with ssl." ssl_authcertificatehook specifies a certificate authentication callback function called to authenticate an incoming certificate.
... see also for
examples of certificate authentication callback functions, see the sample code referenced from chapter 2, "getting started with ssl." ssl_authcertificate default callback function used to authenticate certificates received from the remote end of an ssl connection if the application has not previously called ssl_authcertificatehook to specify its own certificate authentication callback function.
NSS Tools modutil
the following system names and platforms are currently defined by nspr: aix (rs6000) bsdi (x86) freebsd (x86) hpux (hppa1.1) irix (mips) linux (ppc, alpha, x86) macos (powerpc) ncr (x86) nec (mips) os2 (x86) osf (alpha) reliantunix (mips) sco (x86) solaris (sparc) sony (mips) sunos (sparc) unixware (x86) win16 (x86) win95 (x86) winnt (x86) here are some
examples of valid platform strings: irix:6.2:mipssunos:5.5.1:sparclinux:2.0.32:x86win95::x86.
...
examples creating database filesdisplaying module informationsetting a default providerenabling a slotenabling fips complianceadding a cryptographic moduleinstalling a cryptographic module from a jar filechanging the password on a token creating database files this example creates a set of security management database files in the specified directory: modutil -create -dbdir c:\databases the secur...
NSS Tools ssltap
the following are well-known port numbers: http 80 https 443 smtp 25 ftp 21 imap 143 imaps 993 (imap over ssl) nntp 119 nntps 563 (nntp over ssl)
examples you can use the ssl debugging tool to intercept any connection information.
... the following
examples show the output from commonly used combinations of options.
certutil
usage and
examples most of the command options in the
examples listed here have more arguments available.
... the arguments included in these
examples are the most common ones or are used to illustrate a specific scenario.
NSS tools : ssltap
the following are well-known port numbers: * http 80 * https 443 * smtp 25 * ftp 21 * imap 143 * imaps 993 (imap over ssl) * nntp 119 * nntps 563 (nntp over ssl) usage and
examples you can use the ssl debugging tool to intercept any connection information.
...the following
examples show the output from commonly used combinations of options.
Scripting Java
packages are likely not in the java package, so you'll need to prefix the package name with "packages." for example, to import the org.mozilla.javascript package you could use importpackage() as follows: $ java org.mozilla.javascript.tools.shell.main js> importpackage(packages.org.mozilla.javascript); js> context.currentcontext; org.mozilla.javascript.context@bb6ab6 occasionally, you will see
examples that use the fully qualified name of the package instead of importing using the importpackage() method.
...the above
examples could be expressed as follows: $ java org.mozilla.javascript.tools.shell.main js> importclass(packages.org.mozilla.javascript.context); js> context.currentcontext; org.mozilla.javascript.context@bb6ab6 working with java now that we can access java classes, the next logical step is to create an object.
Index
in particular, it has more and better code
examples!
...
examples at jsclass illustrate how stub functions can be used.
JSAPI User Guide
several more
examples of throwing and catching exceptions can be found in the jsapi phrasebook.
...*/ js_clearpendingexception(cx); return false; more sample code the following
examples illustrate how to achieve a few different effects using the jsapi.
Secure Development Guidelines
memory saved return addr or function pointer get altered introduction: gaining control (3) common issues used to gain control buffer overflows format string bugs integer overflows/underflows writing secure code: input validation input validation most vulnerabilities are a result of un-validated input always perform input validation could save you without knowing it
examples: if it doesn’t have to be negative, store it in an unsigned int if the input doesn’t have to be > 512, cut it off there if the input should only be [a-za-z0-9], enforce it cross site scripting (xss) xss is a type of code injection attack typically occurs in web applications injection of arbitrary data into an html document from another site victim’s browser executes...
... 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)); correct usage strncat(buffer, string, sizeof(buffer) – strlen(string) – 1)); banned api list: recommendations create wrappers or replacements for standard functions with a bad design libc fu...
A Web PKI x509 certificate primer
examples of key usages are: digitalsignature, keyencipherment, dataencipherment, keycertsign, and crlsign.
...
examples of extended key usages are: serverauth, clientauth, and ocspsigning.
Preface
also many of the
examples are in javascript, which is used in mozilla to access xpcom components as scriptable objects, and so familiarity with that language is useful as well.
... following along with the
examples there are a couple of different ways to get xpcom onto your machine so you can begin to create components.
Using XPCOM Utilities to Make Things Easier
string size the
examples above illustrate the use of the single byte string class, nsembedcstring.
...in the coming chapters, you'll see
examples that use this version in the weblock component.
Creating XPCOM components
preface who should read this book organization of the tutorial following along with the
examples conventions acknowledgements an overview of xpcom the xpcom solution gecko components interfaces interfaces and encapsulation the nsisupports base interface xpcom identifiers cid contract id factories xpidl and type libraries xpcom services xpcom types method types reference counting status codes variable mappings common xpcom error codes ...
... using xpcom components component
examples cookie manager the webbrowserfind component the weblock component component use in mozilla finding mozilla components using xpcom components in your cpp xpconnect: using xpcom components from script component internals creating components in cpp xpcom initialization xpcom registry manifests registration methods in xpcom autoregistration the shutdown process three parts of a xpcom component library xpcom glue the glue library xpcom string classes creating the component code what we'll be working on component registration the regxpcom program registration alternatives overview of the weblock module source digging in: required includes and constants identifiers in xpcom co...
nsITextInputProcessor
examples of modifier state management var leftshiftkey = new keyboardevent("", { key: "shift", code: "shiftleft" }); var rightshiftkey = new keyboardevent("", { key: "shift", code: "shiftright" }); var shiftkeyonvirtualkeyboard = new keyboardevent("", { key: "shift", code: "" }); tip.keydown(leftshiftkey); // this activates shift state.
...
examples of lockable modifier state management var capslockkey = new keyboardevent("", { key: "capslock", code: "capslock" }); var capslockkeyonvirtualkeyboard = new keyboardevent("", { key: "capslock", code: "" }); tip.keydown(capslockkey); // this activates capslock state.
Xray vision
on() {return 1000};' + 'var date = new date(); '; var sandbox = components.utils.sandbox("https://example.org/"); components.utils.evalinsandbox(sandboxscript, sandbox); // date objects are xrayed console.log(sandbox.date.getfullyear()); // -> 2014 // but you can waive xray vision console.log(components.utils.waivexrays(sandbox.date).getfullyear()); // -> 1000 to test out
examples like this, you can use the scratchpad in browser context for the code snippet, and the browser console to see the expected output.
... to test out
examples like this, you can use the scratchpad in browser context for the code snippet, and the browser console to see the expected output.
Filelink Providers
the hightail implementation is a great place to look for
examples and inspiration.
... the hightail settings.xhtml and settings.js file have
examples of this.
Finding the code for a feature
if you want
examples, scan mxr for addkeywordstomessages.
... you'll find that the only decent
examples are in unit tests, my test_bug428427.js or asuth's messagemodifier.js ...
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 sam...
...
examples 1.-1 < 1 == 1.
Working with windows in chrome code
some
examples use _content instead of content.
...please refer to the nsiwindowmediator page for more information and
examples of using nsiwindowmediator.
Standard OS Libraries
examples for both are found below.
... see also finding window handles - os specific
examples - how to get the a window and pass it to js-ctypes using com from js-ctypes example using objective-c from js-ctypes example ...
Mozilla
toolbars, menu bars, progress bars, and window title bars are all
examples of elements that are typically part of the chrome.
... redis tips this document is a collection of some
examples and tips for using redis, the open-source data structure server.
DevTools API - Firefox Developer Tools
examples here's a few
examples using the gdevtools object.
...
examples register a tool gdevtools.registertool({ // fixme: missing key related properties.
AddressErrors - Web APIs
see the
examples below to see how this works.
...
examples snippet: limiting destination countries this first example is just a snippet showing an implementation of the event handler for the shippingaddresschange event which checks to be sure the chosen address is located within one of a limited number of countries.
AnalyserNode - Web APIs
examples note: see the guide visualizations with web audio api for more information on creating audio visualizations.
...for more complete applied
examples/information, check out our voice-change-o-matic demo (see app.js lines 128–205 for relevant code).
AudioNode - Web APIs
examples include: an audio source (e.g.
...you can find
examples of such usage on any of the
examples linked to on the web audio api landing page (for example violent theremin.) const audioctx = new audiocontext(); const oscillator = new oscillatornode(audioctx); const gainnode = new gainnode(audioctx); oscillator.connect(gainnode).connect(audioctx.destination); oscillator.context; oscillator.numberofinputs; oscillator.numberofoutputs; oscillator.channelc...
AudioParam - Web APIs
examples first, a basic example showing a gainnode having its gain value set.
...these are
examples of k-rate audioparam's, as the values are set for the entire audio block at once.
AudioTrackList - Web APIs
see onaddtrack and onremovetrack for details and
examples.
...
examples getting a media element's audio track list to get a media element's audiotracklist, use its audiotracks property.
CSSNumericValue.equals() - Web APIs
examples as stated earlier, all passed values must be of the same type and value and must be in the same order.
... some of the following
examples illustrate what happens when they are not.
CSSNumericValue.max() - Web APIs
examples as stated earlier, all passed values must be of the same type and value.
... some of the following
examples illustrate what happens when they are not.
CSSNumericValue.min() - Web APIs
examples as stated earlier, all passed values must be of the same type and value.
... some of the following
examples illustrate what happens when they are not.
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.
...> <li>item 5</li> <li>item 6</li> <li>item 7</li> <li>item 8</li> <li>item 9</li> <li>item 10</li> <li>item 11</li> <li>item 12</li> <li>item 13</li> <li>item 14</li> <li>item 15</li> <li>item 16</li> <li>item 17</li> <li>item 18</li> <li>item 19</li> <li>item 20</li> </ul> css.paintworklet.addmodule('https://mdn.github.io/houdini-
examples/csspaint/intro/worklets/hilite.js'); then we can use the <image> with the css paint() function: li { --boxcolor: hsla(55, 90%, 60%, 1.0); background-image: paint(hollowhighlights, stroke, 2px); } li:nth-of-type(3n) { --boxcolor: hsla(155, 90%, 60%, 1.0); background-image: paint(hollowhighlights, filled, 3px); } li:nth-of-type(3n+1) { --boxcolor: hsla(255, 90%, 60%, 1.0); b...
CanvasRenderingContext2D.createImageData() - Web APIs
examples creating a blank imagedata object this snippet creates a blank imagedata object using the createimagedata() method.
...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() and the imagedata object, see pixel manipulation with canvas and imagedata.data.
CanvasRenderingContext2D.fillStyle - Web APIs
for more
examples of fill and stroke styles, see applying styles and color in the canvas tutorial.
...
examples changing the fill color of a shape this example applies a blue fill color to a rectangle.
CanvasRenderingContext2D.imageSmoothingEnabled - Web APIs
examples disabling image smoothing this example compares three images.
... 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 = true', w * 2.5, 20); ctx.imagesmoothingenabled = true; ctx.drawimage(img, w, 24, w * 3, h * 3); ctx.filltext('smoothing = false', w * 5.5, 20); ctx.imagesmoothingenabled = ...
CanvasRenderingContext2D.lineWidth - Web APIs
examples changing line width this example draws a line and a rectangle, using a line width of 15 units.
... 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.strokeStyle - Web APIs
for more
examples of stroke and fill styles, see applying styles and color in the canvas tutorial.
...
examples changing the stroke color of a shape this example applies a blue stroke color to a rectangle.
Basic animations - Web APIs
in the
examples below, we'll use the window.requestanimationframe() method to control the animation.
...spatchevent(e) }; var o, s, h = innerheight, w = innerwidth, fw = 60, fa = []; window.onkeydown = function (t) { var e = t.key; (e.search("arrow") > -1 || "1" == e) && (d = t.key), "i" != e && "i" != e || (console.log("inc"), fw -= 10), "d" != e && "d" != e || (console.log("dec"), fw += 10) }, init(); output other
examples a basic ray-caster a good example of how to do animations using keyboard controls.
Basic usage of canvas - Web APIs
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.
...we'll explore how this works in more detail in later
examples.
Compositing and clipping - Web APIs
« previousnext » in all of our previous
examples, shapes were always drawn one on top of the other.
... see compositing
examples for the code of the following
examples.
Finale - Web APIs
more
examples and tutorials there are a variety of demos and further explanations about canvas on these sites: codepen.io front end developer playground & code editor in the browser.
... html5 canvas tutorials
examples for most canvas apis.
Canvas tutorial - Web APIs
the images on this page show
examples of <canvas> implementations which will be created in this tutorial.
...the
examples provided should give you some clear ideas about what you can do with canvas, and will provide code snippets that may get you started in building your own content.
Console.timeEnd() - Web APIs
see timers in the documentation for details and
examples.
...
examples console.time("answer time"); alert("click to continue"); console.timelog("answer time"); alert("do a bunch of other stuff..."); console.timeend("answer time"); the output from the example above shows the time taken by the user to dismiss the first alert box, followed by the time it took for the user to dismiss the second alert: notice that the timer's name is displayed when the timer value is logged using timelog() and again when it's stopped.
Console.timeLog() - Web APIs
see timers in the documentation for details and
examples.
...
examples console.time("answer time"); alert("click to continue"); console.timelog("answer time"); alert("do a bunch of other stuff..."); console.timeend("answer time"); the output from the example above shows the time taken by the user to dismiss the first alert box, followed by the time it took for the user to dismiss the second alert: notice that the timer's name is displayed when the timer value ...
console - Web APIs
for example: console.log("failed to open the specified link") this page documents the methods available on the console object and gives a few usage
examples.
...
examples outputting text to the console the most frequently-used feature of the console is logging of text and other data.
Content Index API - Web APIs
examples could be a news website prefetching the latest articles in the background, or a content streaming app registering downloaded content.
...
examples all the following
examples assume a service worker has been registered.
DOMMatrixReadOnly.scale() - Web APIs
dommatrix.scale(scale[, originx][, originy]) we'll show an example of how you can deal with the cross-browser support implications of this in the
examples section, below.
...
examples this svg contains three squares, one red, one blue, and one green, each positioned at the document origin: <svg width="250" height="250" viewbox="0 0 25 25"> <rect width="25" height="25" fill="red" /> <rect id="transformed" width="25" height="25" fill="blue" /> <rect id="transformedorigin" width="25" height="25" fill="green" /> </svg> this javascript first creates an identity matrix, then uses the scale() method to create a new matrix with a single parameter.
DataTransfer.effectAllowed - Web APIs
<!doctype html> <html lang=en> <title>
examples of datatransfer.{dropeffect,effectallowed} properties</title> <meta content="width=device-width"> <style> div { margin: 0em; padding: 2em; } #source { color: blue; border: 1px solid black; } #target { border: 1px solid black; } </style> <script> function dragstart_handler(ev) { console.log("dragstart: dropeffect = " + ev.datatransfer.dropeffect + " ; effectallowed...
...ement 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> <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> </b...
DataTransfer.items - Web APIs
<!doctype html> <html lang=en> <title>
examples of datatransfer.{types,items} properties</title> <meta content="width=device-width"> <style> div { margin: 0em; padding: 2em; } #target { border: 1px solid black; } </style> <script> function dragstart_handler(ev) { console.log("dragstart: target.id = " + ev.target.id); // add this element's id to the drag payload so the drop handler will // know which element to add to its...
...items[" + i + "].kind = " + ev.datatransfer.items[i].kind + " ; type = " + ev.datatransfer.items[i].type); } } } function dragover_handler(ev) { console.log("dragover"); ev.preventdefault(); // set the dropeffect to move ev.datatransfer.dropeffect = "move" } </script> <body> <h1>
examples of <code>datatransfer</code>.{<code>types</code>, <code>items</code>} properties</h1> <ul> <li id="i1" ondragstart="dragstart_handler(event);" draggable="true">drag item 1 to the drop zone</li> <li id="i2" ondragstart="dragstart_handler(event);" draggable="true">drag item 2 to the drop zone</li> </ul> <div id="target" ondrop="drop_handler(event);" ondragover="dragover_handler(event);">dr...
DataTransfer.setData() - Web APIs
<!doctype html> <html lang=en> <title>
examples of datatransfer's setdata(), getdata() and cleardata()</title> <meta content="width=device-width"> <style> div { margin: 0em; padding: 2em; } #source { color: blue; border: 1px solid black; } #target { border: 1px solid black; } </style> <script> function dragstart_handler(ev) { console.log("dragstart"); // change the source element's background color to signify ...
...er_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 selection to move the element.</p> </div> <div id="target" ondrop="drop_handler(event);" ondragover="dragover_handler(event);">drop zo...
DataTransfer.types - Web APIs
<!doctype html> <html lang=en> <title>
examples of datatransfer.{types,items} properties</title> <meta content="width=device-width"> <style> div { margin: 0em; padding: 2em; } #target { border: 1px solid black; } </style> <script> function dragstart_handler(ev) { console.log("dragstart: target.id = " + ev.target.id); // add this element's id to the drag payload so the drop handler will // know which element to add to its...
...items[" + i + "].kind = " + ev.datatransfer.items[i].kind + " ; type = " + ev.datatransfer.items[i].type); } } } function dragover_handler(ev) { console.log("dragover"); ev.preventdefault(); // set the dropeffect to move ev.datatransfer.dropeffect = "move" } </script> <body> <h1>
examples of <code>datatransfer</code>.{<code>types</code>, <code>items</code>} properties</h1> <ul> <li id="i1" ondragstart="dragstart_handler(event);" draggable="true">drag item 1 to the drop zone</li> <li id="i2" ondragstart="dragstart_handler(event);" draggable="true">drag item 2 to the drop zone</li> </ul> <div id="target" ondrop="drop_handler(event);" ondragover="dragover_handler(event);">dr...
Document: pointercancel event - Web APIs
bubbles yes cancelable no interface pointerevent event handler property onpointercancel some
examples of situations that will trigger a pointercancel event: a hardware event occurs that cancels the pointer activities.
...
examples using addeventlistener(): document.addeventlistener('pointercancel', (event) => { console.log('pointer event cancelled') }); using the onpointercancel event handler property: document.onpointercancel = (event) => { console.log('pointer event cancelled') }; specifications specification status pointer events obsolete ...
Document.requestStorageAccess() - Web APIs
examples: allow lists, block lists, on-device classification, user settings, anti-clickjacking heuristics, or prompting the user for explicit permission.
...
examples document.requeststorageaccess().then( () => { console.log('access granted') }, () => { console.log('access denied') } ); specifications the api is currently only at the proposal stage — the standardization process has yet to begin.
Document: scroll event - Web APIs
examples scroll event throttling since scroll events can fire at a high rate, the event handler shouldn't execute computationally expensive operations such as dom modifications.
...ition = 0; let ticking = false; function dosomething(scroll_pos) { // do something with the scroll position } window.addeventlistener('scroll', function(e) { last_known_scroll_position = window.scrolly; if (!ticking) { window.requestanimationframe(function() { dosomething(last_known_scroll_position); ticking = false; }); ticking = true; } }); see more, similar
examples on the resize event page.
Events and the DOM - Web APIs
the event interface itself is described, as well as the interfaces for event registration on nodes in the dom, and event listeners, and several longer
examples that show how the various event interfaces relate to one another.
... also see example 5: event propagation in the
examples chapter for a more detailed example of how events move through the dom.
Element.querySelector() - Web APIs
examples let's consider a few
examples.
... more
examples see document.queryselector() for additional
examples of the proper format for the selectors.
Element: scroll event - Web APIs
examples scroll event throttling since scroll events can fire at a high rate, the event handler shouldn't execute computationally expensive operations such as dom modifications.
... 0; let ticking = false; function dosomething(scroll_pos) { // do something with the scroll position } window.addeventlistener('scroll', function(e) { last_known_scroll_position = window.scrolly; if (!ticking) { window.requestanimationframe(function() { dosomething(last_known_scroll_position); ticking = false; }); ticking = true; } }); note: you can find more
examples on the resize event page.
Event.composed - Web APIs
examples in our composed-composed-path example (see it live), we define two trivial custom elements, <open-shadow> and <closed-shadow>, both of which take the contents of their text attribute and insert them into the element's shadow dom as the text content of a <p> element.
... the <open-shadow> element's composed path is this: array [ p, shadowroot, open-shadow, body, html, htmldocument https://mdn.github.io/web-components-
examples/composed-composed-path/, window ] whereas the <closed-shadow> element's composed path is a follows: array [ closed-shadow, body, html, htmldocument https://mdn.github.io/web-components-
examples/composed-composed-path/, window ] in the second case, the event listeners only propagate as far as the <closed-shadow> element itself, but not to the nodes inside the shadow boundary.
Event.composedPath() - Web APIs
examples in our composed-composed-path example (see it live), we define two trivial custom elements, <open-shadow> and <closed-shadow>, both of which take the contents of their text attribute and insert them into the element's shadow dom as the text content of a <p> element.
...the <open-shadow> element's composed path is this: array [ p, shadowroot, open-shadow, body, html, htmldocument https://mdn.github.io/web-components-
examples/composed-composed-path/, window ] whereas the <closed-shadow> element's composed path is a follows: array [ closed-shadow, body, html, htmldocument https://mdn.github.io/web-components-
examples/composed-composed-path/, window ] in the second case, the event listeners only propagate as far as the <closed-shadow> element itself, but not to the nodes inside the shadow boundary.
FileSystemEntrySync - Web APIs
examples include a backslash (\), dot (.), and two dots (..).
...
examples include a backslash (\), dot (.), and two dots (..).
Introduction to the File and Directory Entries API - Web APIs
for
examples of features you can create with this app, see the sample use cases section.
... sample use cases the following are just a few
examples of how you can use the file and directory entries api: apps with persistent uploader when a file or directory is selected for upload, you can copy the file into a local sandbox and upload a chunk at a time.
GlobalEventHandlers.ondrag - Web APIs
<!doctype html> <html lang=en> <title>
examples of using the ondrag global event attribute</title> <meta content="width=device-width"> <style> div { margin: 0em; padding: 2em; } #source { color: blue; border: 1px solid black; } #target { border: 1px solid black; } </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) { conso...
...le.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, 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> </body> </html> specifications ...
GlobalEventHandlers.ondragend - Web APIs
<!doctype html> <html lang=en> <title>
examples of using the drag and drop global event attribute</title> <meta content="width=device-width"> <style> div { margin: 0em; padding: 2em; } #source { color: blue; border: 1px solid black; } #target { border: 1px solid black; } </style> </head> <script> function dragstart_handler(ev) { console.log("dragstart"); // change the source element's background color to signify drag has started ev.currenttarget.style.border ...
...der 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> <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 zo...
GlobalEventHandlers.ondragenter - Web APIs
<!doctype html> <html lang=en> <title>
examples of using the drag and drop global event attribute</title> <meta content="width=device-width"> <style> div { margin: 0em; padding: 2em; } #source { color: blue; border: 1px solid black; } #target { border: 1px solid black; } </style> </head> <script> function dragstart_handler(ev) { console.log("dragstart"); // change the source element's background color to signify drag has started ev.currenttarget.st...
...der 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> <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 zo...
GlobalEventHandlers.ondragexit - Web APIs
<!doctype html> <html lang=en> <title>
examples of using the drag and drop global event attribute</title> <meta content="width=device-width"> <style> div { margin: 0em; padding: 2em; } #source { color: blue; border: 1px solid black; } #target { border: 1px solid black; } </style> </head> <script> function dragstart_handler(ev) { console.log("dragstart"); // change the source element's background color to signi...
...der 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> <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 zo...
GlobalEventHandlers.ondragleave - Web APIs
<!doctype html> <html lang=en> <title>
examples of using the drag and drop global event attribute</title> <meta content="width=device-width"> <style> div { margin: 0em; padding: 2em; } #source { color: blue; border: 1px solid black; } #target { border: 1px solid black; } </style> </head> <script> function dragstart_handler(ev) { console.log("dragstart"); // change the source element's border to signify drag has started ev.currenttarget.style.border...
...lor 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> <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 zo...
GlobalEventHandlers.ondragover - Web APIs
<!doctype html> <html lang=en> <title>
examples of using the ondrag global event attribute</title> <meta content="width=device-width"> <style> div { margin: 0em; padding: 2em; } #source { color: blue; border: 1px solid black; } #target { border: 1px solid black; } </style> </head> <script> function drag_handler(ev) { console.log("drag"); } function dragstart_handler(ev) { console.log("dragstart"); ev.datatransfer.setdata("text", ev.target.id); } functio...
...n 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 then release the selection to move the element.</p> </div> <div id="target" ondrop="drop_handler(event);" ondragover="dragover_handler(event);">drop zone</div> </body> </html> specifications sp...
GlobalEventHandlers.ondragstart - Web APIs
<!doctype html> <html lang=en> <title>
examples of using the ondrag global event attribute</title> <meta content="width=device-width"> <style> div { margin: 0em; padding: 2em; } #source { color: blue; border: 1px solid black; } #target { border: 1px solid black; } </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 then release the selection to move the element.</p> </div> <div id="target" ondrop="drop_handler(event);" ondragover="dragover_handler(event);">drop zone</div> </body> </html> specifications ...
GlobalEventHandlers.ondrop - Web APIs
<!doctype html> <html lang=en> <title>
examples of using the ondrag global event attribute</title> <meta content="width=device-width"> <style> div { margin: 0em; padding: 2em; } #source { color: blue; border: 1px solid black; } #target { border: 1px solid black; } </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) { consol...
...e.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 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> </body> </html> specifications specification ...
HTMLElement: pointercancel event - Web APIs
bubbles yes cancelable no interface pointerevent event handler property onpointercancel some
examples of situations that will trigger a pointercancel event: a hardware event occurs that cancels the pointer activities.
...
examples using addeventlistener(): const para = document.queryselector('p'); para.addeventlistener('pointercancel', (event) => { console.log('pointer event cancelled'); }); using the onpointercancel event handler property: const para = document.queryselector('p'); para.onpointercancel = (event) => { console.log('pointer event cancelled'); }; specifications specification status ...
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.
... these are shown in the
examples below.
HTMLImageElement.useMap - Web APIs
that looks like this: <map name="mainmenu-map"> <area shape="circle" coords="25, 25, 75, 75" href="/index.html" alt="return to home page"> <area shape="rect" coords="25, 25, 100, 150" href="/index.html" alt="shop"> </map> given the image map named mainmenu-map, the image which uses it should look something like the following: <img src="menubox.png" usemap="#mainmenu-map"> for additional
examples (including interactive ones), see the articles about the <map> and <area> elements, as well as the guide to using image maps.
...if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
HTMLMediaElement: loadstart event - Web APIs
bubbles no cancelable no interface event event handler property onloadstart
examples live example html <div class="example"> <button type="button">load video</button> <video controls width="250"></video> <div class="event-log"> <label>event log:</label> <textarea readonly class="event-log-contents"></textarea> </div> </div> css .event-log-contents { width: 18rem; height: 5rem; border: 1px solid black; margin: .2rem; padding: .2rem; } .example { display: grid; grid-template-areas: "button log" "video log"; } button { grid-area: button; width: 10rem; margin: .5rem 0; } video ...
...r('progress', handleevent); video.addeventlistener('canplay', handleevent); video.addeventlistener('canplaythrough', handleevent); loadvideo.addeventlistener('click', () => { if (source) { document.location.reload(); } else { loadvideo.textcontent = "reset example"; source = document.createelement('source'); source.setattribute('src', 'https://interactive-
examples.mdn.mozilla.net/media/
examples/flower.webm'); source.setattribute('type', 'video/webm'); video.appendchild(source); } }); result specifications specification status html living standardthe definition of 'loadstart media event' in that specification.
HTMLMediaElement: progress event - Web APIs
bubbles no cancelable no interface event event handler property onprogress
examples live example html <div class="example"> <button type="button">load video</button> <video controls width="250"></video> <div class="event-log"> <label>event log:</label> <textarea readonly class="event-log-contents"></textarea> </div> </div> css .event-log-contents { width: 18rem; height: 5rem; border: 1px solid black; margin: .2rem; padding: .2rem; } .example { display: grid; grid-template-areas: "button log" "video log"; } button { grid-area: button; width: 10rem; margin: .5rem 0; } video { g...
...r('progress', handleevent); video.addeventlistener('canplay', handleevent); video.addeventlistener('canplaythrough', handleevent); loadvideo.addeventlistener('click', () => { if (source) { document.location.reload(); } else { loadvideo.textcontent = "reset example"; source = document.createelement('source'); source.setattribute('src', 'https://interactive-
examples.mdn.mozilla.net/media/
examples/flower.webm'); source.setattribute('type', 'video/webm'); video.appendchild(source); } }); result specifications specification status html living standardthe definition of 'progress media event' in that specification.
HTMLMediaElement.srcObject - Web APIs
examples basic example in this example, a mediastream from a camera is assigned to a newly-created <video> element.
... const mediasource = new mediasource(); const video = document.createelement('video'); video.srcobject = mediasource; supporting fallback to the src property the
examples below support older browser versions that require you to create an object url and assign it to src if srcobject isn't supported.
Headers - Web APIs
you can add to this using methods like append() (see
examples.) in all methods of this interface, header names are matched by case-insensitive byte sequence.
...
examples in the following snippet, we create a new header using the headers() constructor, add a new header to it using append(), then return that header value using get(): var myheaders = new headers(); myheaders.append('content-type', 'text/xml'); myheaders.get('content-type') // should return 'text/xml' the same can be achieved by passing an array of arrays or an object literal to the constructor:...
ImageData.data - Web APIs
syntax imagedata.data
examples getting an imagedata object's pixel data this example creates an imagedata object that is 100 pixels wide and 100 pixels tall, making 10,000 pixels in all.
...400 * 255; // percentage in the y direction, times 255 let y = math.ceil(i / 400) / 100 * 255; // modify pixel data imagedata.data[i + 0] = x; // r value imagedata.data[i + 1] = y; // g value imagedata.data[i + 2] = 255 - x; // 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 imagedata.data, see pixel manipulation with canvas, canvasrenderingcontext2d.createimagedata(), and canvasrenderingcontext2d.putimagedata().
IndexedDB API - Web APIs
examples elibri: a powerful library and ebook reader application, written by marco castelluccio, winner of the indexeddb mozilla devderby.
... to-do notifications (view example live): the reference application for the
examples in the reference docs.
Key Values - Web APIs
examples include the shift and control keys, and lock keys such as caps lock and numlock.
...common
examples include chinese, japanese, korean, and hindi.
MediaQueryList - Web APIs
examples this simple example creates a mediaquerylist and then sets up a listener to detect when the media query status changes, running a custom function when it does to change the appearence of the page.
... you can find other
examples on the individual property and method pages.
MediaStreamConstraints.audio - Web APIs
examples for browsers with feature policy enabled, the samples below need the microphone feature enabled.
... see security in mediadevices.getusermedia() for details and
examples on how to configure this.
Navigator.getUserMedia() - Web APIs
errors
examples width and height here's an example of using getusermedia(), including code to cope with various browsers' prefixes.
... note that this is the deprecated way of doing it: see the
examples section under the mediadevices.getusermedia() for modern
examples.
Using the Notifications API - Web APIs
examples one of the most obvious use cases for web notifications is a web-based mail or irc application that needs to notify the user when a new message is received, even if the user is doing something else with another application.
... many
examples of this now exist, such as slack.
PaymentAddress - Web APIs
some
examples of valid country values: "us", "gb", "cn", or "jp".
...
examples in the following example, the paymentrequest() constructor is used to create a new payment request, which takes three objects as parameters — one containing details of the payment methods that can be used for the payment, one containing details of the actual order (such as items bought and shipping options), and an optional object containing further options.
PaymentRequest.show() - Web APIs
most
examples on mdn and elsewhere use async/await to wait asynchronously while results are validated and so forth.
...
examples in the following example, a paymentrequest object is instantiated before the show() method is called.
Pointer events - Web APIs
examples of pointer input devices are mouse, pen/stylus, and touch contacts.
...
examples this section contains
examples of basic usage of using the pointer events interfaces.
Using the Resource Timing API - Web APIs
for more details about the interfaces, including
examples, see each interface's reference page and the references in the see also section.
... a live version of the
examples is available on github, as is the source code.
Using the Screen Capture API - Web APIs
the
examples below show a few ways to make use of the stream.
...
examples simple screen capture in this example, the contents of the captured screen area are simply streamed into a <video> element on the same page.
ServiceWorkerContainer.register() - Web APIs
see the
examples section for more information on how it works.
...
examples the
examples described here should be taken together to get a better understanding of how service workers scope applies to a page.
ServiceWorkerGlobalScope: pushsubscriptionchange event - Web APIs
bubbles no cancelable no interface pushsubscriptionchangeevent event handler property onpushsubscriptionchange usage notes although
examples demonstrating how to share subscription related information with the application server tend to use fetch(), this is not necessarily the best choice for real-world use, since it will not work if the app is offline, for example.
...
examples this example, run in the context of a service worker, listens for a pushsubscriptionchange event and re-subscribes to the lapsed subscription.
SpeechRecognitionEvent.emma - Web APIs
you can see muliple emma
examples in the spec.
...
examples recognition.onresult = function(event) { var color = event.results[0][0].transcript; diagnostic.textcontent = 'result received: ' + color + '.'; bg.style.backgroundcolor = color; console.log(event.emma); } ...
SpeechRecognitionEvent.interpretation - Web APIs
this might be determined, for instance, through the sisr specification of semantics in a grammar (see semantic interpretation for speech recognition (sisr) version 1.0 for specification and
examples.) syntax var myinterpretation = event.interpretation; value the returned value can be of any type.
...
examples recognition.onresult = function(event) { var color = event.results[0][0].transcript; diagnostic.textcontent = 'result received: ' + color + '.'; bg.style.backgroundcolor = color; console.log(event.interpretation); } ...
TextTrackList - Web APIs
see onaddtrack and onremovetrack for details and
examples.
...
examples getting a video element's text track list to get a media element's texttracklist, use its texttracks property.
TransformStream - Web APIs
methods none
examples anything-to-uint8array stream in the following example, a transform stream passes through all chunks it receives as uint8array values.
...
examples include building a pwa with progressive loading and progressive streaming.
VideoTrackList - Web APIs
see onaddtrack and onremovetrack for details and
examples.
...
examples getting a media element's video track list to get a media element's videotracklist, use its videotracks property.
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.
...
examples for example, when checking for program linking success, you could also check if the context is not lost: gl.linkprogram(program); if (!gl.getprogramparameter(program, gl.link_status) && !gl.iscontextlost()) { var info = gl.getprograminfolog(program); console.log('error linking program:\n' + info); } specifications specification status comment webgl 1.0the definiti...
WebGLRenderingContext - Web APIs
the webgl tutorial has more information,
examples, and resources on how to get started with webgl.
...
examples webgl context feature detection in this first example we are going to check whether the browser supports webgl.
Boilerplate 1 - Web APIs
any additional non-trivial css and html will be displayed on the pages of specific
examples.
... in following
examples, we will use a javascript helper function, getrenderingcontext(), to initialize the webgl rendering context.
Matrix math for the web - Web APIs
the live
examples use a collection of utility functions available under a global object named mdn.
... <div id='move-me' class='transformable'> <h2>move me with a matrix</h2> <p>lorem ipsum dolor sit amet, consectetur adipisicing elit...</p> </div> finally, for each of the
examples we will generate a 4x4 matrix, then update the <div>'s style to have a transform applied to it, set to a matrix3d.
Viewpoints and viewers: Simulating cameras in WebXR - Web APIs
some
examples of ways 3d cameras are used: when rendering animation—whether for filmmaking or for use within the context of a presentation or game—the virtual camera is used just like a real-world film camera.
...popular
examples include world of warcraft, tomb raider, and fortnite.
Movement, orientation, and motion: A WebXR example - Web APIs
dependencies while we will not rely upon any 3d graphics frameworks such as three.js or the like for this example, we do use the glmatrix library for matrix math, which we've used in other
examples in the past.
... everything else the rest of the code is identical to that found in the earlier
examples: initshaderprogram() initializes the glsl shader program, calling loadshader() to load and compile each shader's program, then attaching each one to the webgl context.
Using the Web Audio API - Web APIs
more
examples there are other
examples available to learn more about the web audio api.
... also see our webaudio-
examples repo for more
examples.
Window.console - Web APIs
examples logging to console the first example logs text to the console.
... console.log("an error occurred while loading the content"); the next example logs an object to the console, with the object's fields expandable using disclosure widgets: console.dir(someobject); see usage in console for more thorough
examples.
Window.customElements - Web APIs
examples the most common example you'll see of this property being used is to get access to the customelementregistry.define() 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.getComputedStyle() - Web APIs
examples in this example we style a <p> element, then retrieve those styles using getcomputedstyle(), and print them into the text content of the <p>.
...see plugging the css history leak and privacy-related changes coming to css :visited for
examples of how this is implemented.
Window.matchMedia() - Web APIs
examples this example runs the media query (max-width: 600px) and displays the value of the resulting mediaquerylist's matches property in a <span>; as a result, the output will say "true" if the viewport is less than or equal to 600 pixels wide, and will say "false" if the window is wider than that.
... css .mq-value { font: 18px arial, sans-serif; font-weight: bold; color: #88f; padding: 0.4em; border: 1px solid #dde; } result see testing media queries programmatically for additional code
examples.
WindowOrWorkerGlobalScope.setInterval() - Web APIs
examples example 1: basic syntax the following example demonstrates setinterval()'s basic syntax.
...note also that the actual amount of time that elapses between calls to the callback may be longer than the given delay; see reasons for delays longer than specified in windoworworkerglobalscope.settimeout() for
examples.
XRRenderState.baseLayer - Web APIs
see the
examples below to see how to use updaterenderstate() to set the current xrwebgllayer used for rendering the scene.
...
examples you can set the xrwebgllayer used for rendering by calling updaterenderstate(), like this: let canvas = document.queryselector("canvas"); gl = canvas.getcontext("webgl", { xrcompatible: true }); setnewwebgllayer(); function setnewwebgllayer(gl) { if (!gl) { /* webgl not available */ return; } xrsession.updaterenderstate({ baselayer: new xrwebgllayer(xrsession, gl); }); }; here, the canvas obtained in the first line is the canvas into which webgl is going to draw.
XRRigidTransform() - Web APIs
examples in this example, the beginning of the animation of a scene is shown, starting with a request for a reference space of a given type, then shifting the coordinate system based on a transform before requesting the first animation frame.
... you can find more
examples in movement, orientation, and motion.
XRSession.onsqueeze - Web APIs
examples handling squeeze events for a specific hand this snippet of code adds a simple handler for the squeeze event, which responds only to events on the user's off-hand (that is, the hand that isn't their dominant hand).
... xrsession.onsqueeze = event => { if (event.inputsource.handedness == user.handedness) { let targetraypose = event.frame.getpose(event.inputsource.targetrayspace, myrefspace); if (user.heldobject && targetraypose) { dropobjectusingray(user.heldobject, targetraypose.transform.matrix): } } }; see the
examples in the onsqueezestart and onsqueezeend event handlers for the reset of the event handling related to this approach.
XRSession: select event - Web APIs
examples of comon kinds of primary action are users pressing triggers or buttons, tapping a touchpad, speaking a command, or performing a recognizable gesture when using a video tracking system or handheld controller with an accelerometer.
...
examples the following example uses addeventlistener() to set up a handler for the select event.
XRSession: squeeze event - Web APIs
examples of comon kinds of primary action are users pressing triggers or buttons, tapping a touchpad, speaking a command, or performing a recognizable gesture when using a video tracking system or handheld controller with an accelerometer.
...
examples the following example uses addeventlistener() to set up a handler for the squeeze event.
XRWebGLLayer.getNativeFramebufferScaleFactor() static method - Web APIs
see the usage notes and
examples for details.
...
examples in this example, we request a frame buffer at the device's native resolution, regardless of any performance concerns: function requestnativescalewebgllayer(gl, xrsession) { return gl.makexrcompatible().then(() => { let scalefactor = xrwebgllayer.getnativeframebufferscalefactor(xrsession); let gllayer = new xrwebgllayer(xrsession, gl, { framebufferscalefactor: scale...
Using the alert role - Accessibility
examples example 1: adding the role in the html code the snippet below shows how the alert role is added directly into the html source code.
... .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".
Using the alertdialog role - Accessibility
examples example 1: a basic alert dialog the code snippet below shows how to mark up an alert dialog that only provides a message and an ok button.
... <div role="alertdialog" aria-labelledby="dialog1title" aria-describedby="dialog1desc"> <div role="document" tabindex="0"> <h2 id="dialog1title">your login session is about to expire</h2> <p id="dialog1desc">to extend your session, click the ok button</p> <button>ok</button> </div> </div> working
examples: tbd notes aria attributes used alertdialog aria-labelledby aria-describedby related aria techniques using the dialog role using the alert role compatibility tbd: add support information for common ua and at product combinations additional resources ...
Using the aria-invalid attribute - Accessibility
examples example 1: simple form validation the following snippet shows a simplified version of two form fields with a validation function attached to the blur event.
...(oldalert); } if (msg) { var newalert = document.createelement("div"); newalert.setattribute("role", "alert"); newalert.setattribute("id", "alert"); var content = document.createtextnode(msg); newalert.appendchild(content); document.body.appendchild(newalert); } } note that the alert has the aria role attribute set to "alert." working
examples: alert role example (uses the aria-invalid attribute) notes when aria-invalid is used in conjunction with the aria-required attribute, aria-invalid should not be set to true before the form is submitted - only in response to validation.
Using the aria-labelledby attribute - Accessibility
the
examples section below provides more information on how to use the attribute this way.
...
examples example 1: multiple labels in the example below, each input field is labelled by both its own individual label and by the label for the group: <div id="mybillingid">billing</div> <div> <div id="mynameid">name</div> <input type="text" aria-labelledby="mybillingid mynameid"/> </div> <div> <div id="myaddressid">address</div> <input type="text" aria-labelledby="mybillingid myaddre...
Using the aria-orientation attribute - Accessibility
examples example 1: the snippet below shows a simple slider that is oriented vertically.
... <a href="#" id="handle_zoomslider" role="slider" aria-orientation="vertical" aria-valuemin="0" aria-valuemax="17" aria-valuenow="14" > <span>11</span> </a> working
examples: slider example notes used with aria roles scrollbar listbox combobox menu tree separator slider tablist toolbar related aria techniques compatibility tbd: add support information for common ua and at product combinations additional resources wai-aria specification for the aria-orientation attribute ...
Using the aria-required attribute - Accessibility
examples example 1: a simple form <form action="post"> <label for="firstname">first name:</label> <input id="firstname" type="text" aria-required="true" /> <br/> <label for="lastname">last name:</label> <input id="lastname" type="text" aria-required="true" /> <br/> <label for="streetaddress">street address:</label> <input id="streetaddress" type="text" /> </fo...
...rm> working
examples: tooltip example (includes the use of the aria-required attribute) notes used in aria roles combobox gridcell listbox radiogroup spinbutton textbox tree related aria techniques using the aria-invalid attribute compatibility tbd: add support information for common ua and at product combinations additional resources wai-aria specification for aria-required wai-aria authoring practices for forms constraint validation in html5 ...
Using the aria-valuemax attribute - Accessibility
examples example 1: the snippet below shows a simple slider with a maximum value of 10.
... <div role="slider" aria-valuenow="4" aria-valuemin="1" aria-valuemax="10"> working
examples: progressbar example slider example spinbutton example notes used with aria roles progressbar scrollbar slider spinbutton related aria techniques aria-valuemin aria-valuenow aria-valuetext compatibility tbd: add support information for common ua and at product combinations additional resources wai-aria specification for the aria-valuemax attribute ...
Using the aria-valuemin attribute - Accessibility
examples example 1: the snippet below shows a simple slider with a minimum value of 1.
... <div role="slider" aria-valuenow="4" aria-valuemin="1" aria-valuemax="10"> working
examples: progressbar example slider example spinbutton example notes used with aria roles progressbar scrollbar slider spinbutton related aria techniques aria-valuemax aria-valuenow aria-valuetext compatibility tbd: add support information for common ua and at product combinations additional resources wai-aria specification for the aria-valuemin attribute ...
Using the aria-valuenow attribute - Accessibility
examples example 1: the snippet below shows a simple slider with a current value of 4.
... <div role="slider" aria-valuenow="4" aria-valuemin="1" aria-valuemax="10"> working
examples: progressbar example slider example spinbutton example notes used with aria roles progressbar scrollbar slider spinbutton related aria techniques aria-valuemax aria-valuemin aria-valuetext compatibility tbd: add support information for common ua and at product combinations additional resources wai-aria specification for the aria-valuenow attribute ...
Using the aria-valuetext attribute - Accessibility
examples example 1: the snippet below shows a simple slider for selecting a day of the week.
... <div role="slider" aria-valuenow="1" aria-valuemin="1" aria-valuemax="7" aria-valuetext="sunday"> working
examples: notes used with aria roles progressbar scrollbar slider spinbutton related aria techniques aria-valuenow compatibility tbd: add support information for common ua and at product combinations additional resources wai-aria specification for the aria-valuetext attribute ...
Using the article role - Accessibility
examples of an article include web log posts, newspaper or magazine articles and use-submitted comments.
...
examples <article role="article"> <header> <h2>blog post</h2> </header> <section class="content"> <p>a very interesting post</p> </section> <section class="comments"> <div class="comment" role="article"> <p>meaningful comment</p> </div> <div class="comment" role="article"> <p>positive comment</p> </div> </section> </article> notes aria attributes used r...
Using the group role - Accessibility
examples example 1: using the group role with a html tree view the snippet below shows how the group role is added directly into the html source code.
...<div role="menu"> <ul role="group"> <li role="menuitem">inbox</li> <li role="menuitem">archive</li> <li role="menuitem">trash</li> </ul> <ul role="group"> <li role="menuitem">custom folder 1</li> <li role="menuitem">custom folder 2</li> <li role="menuitem">custom folder 3</li> </ul> <ul role="group"> <li role="menuitem">new folder</li> </ul> </div> working
examples: file directory treeview example using computed properties navigation treeview example using declared properties notes group members that are outside of the dom subtree of the group need to have explicit relationships assigned to them in order to participate in the group.
Using the log role - Accessibility
examples example 1: adding the role in the html code the snippet below shows how the log role is added directly into the html source code.
... <div id="chatarea" role="log"> <ul id="chatregion" aria-live="polite" aria-atomic="false"> <li>please choose a user name to begin using ajax chat.</li> </ul> <ul id="userlistregion" aria-live="off" aria-relevant="additions removals text"> </ul> </div> working
examples: http://websiteaccessibility.donaldevans.com/2011/07/12/aria-log/ notes using the log role on an element implies that element has aria-live="polite".
Using the progressbar role - Accessibility
examples example 1: basic progressbar with percentage values <div role="progressbar" aria-valuenow="20" aria-valuemin="0" aria-valuemax="100">20 %</div> example 2: using aria-valuetext <div role="progressbar" aria-valuenow="20" aria-valuemin="0" aria-valuetext="step 2: copying files...
...</div> working
examples: notes aria attributes used progressbar aria-valuenow aria-valuemin aria-valuemax aria-valuetext related aria techniques compatibility tbd: add support information for common ua and at product combinations additional resources ...
Using the radio role - Accessibility
examples example 1: example from the basic form hints mdn page.
...="-1" role="radio" aria-checked="false"> <img role="presentation" src="radio-unchecked.gif" /> thai </li> <li id="r2" tabindex="-1" role="radio" aria-checked="false"> <img role="presentation" src="radio-unchecked.gif" /> subway </li> <li id="r3" tabindex="0" role="radio" aria-checked="true"> <img role="presentation" src="radio-checked.gif" /> radio maria </li> </ul> working
examples: notes aria attributes used related aria techniques compatibility tbd: add support information for common ua and at product combinations additional resources ...
Using the status role - Accessibility
examples example 1: adding the status role in html the snippet below shows how the status role is added directly into the html source code.
... <p role="status">your changes were automatically saved.</p> working
examples: notes aria attributes used status related aria techniques alert role live region roles live region attributes compatibility the paciello group published some data on compatibility via their 2014 blog post: screen reader support for aria live regions tbd: add updated support information for common ua and at product combinations additional resources previous recommendations from wai-aria 1.0 (2014) for the status role ...
ARIA: feed role - Accessibility
examples include an rss feed, news feeds, social media feeds like facebook, instagram or twitter, or even a list of related products on an ecommerce page.
...
examples example implementation of feed pattern specifications specification status accessible rich internet applications (wai-aria) 1.1the definition of 'feed' in that specification.
ARIA: grid role - Accessibility
examples calendar example html <table role="grid" aria-labelledby="calendarheader" aria-readonly=true> <caption id="calendarheader">september 2018</caption> <thead role="rowgroup"> <tr role="row"> <td></td> <th role="columnheader" aria-label="sunday">s</th> <th role="columnheader" aria-label="monday">m</th> <th role="columnheader" aria-label="tuesday">t</th> <th r...
...result = moveto(i, event.target.dataset.col); i++; } while (result == false); break; case "pagedown": var i = maxrow; var result; do { result = moveto(i, event.target.dataset.col); i--; } while (result == false); break; case "enter": alert(event.target.textcontent); break; } event.preventdefault(); }); more
examples data grid
examples layout grids
examples w3c/wai tutorial: tables accessibility concerns even if the keyboard use is properly implemented, some users might not be aware that they have to use the arrow keys.
ARIA: dialog role - Accessibility
examples a dialog containing a form <div role="dialog" aria-labelledby="dialog1title" aria-describedby="dialog1desc"> <h2 id="dialog1title">subscription form</h2> <p id="dialog1desc">we will not share this information with third parties.</p> <form> <p> <label for="firstname">first name</label> <input id="firstname" type="text" /> </p> <p> <label for="lastnam...
...ast name</label> <input id="lastname" type="text"/> </p> <p> <label for="interests">interests</label> <textarea id="interests"></textarea> </p> <p> <input type="checkbox" id="autologin"/> <label for="autologin">auto-login?</label> </p> <p> <input type="submit" value="save information"/> </p> </form> </div> working
examples: jquery-ui dialog notes note: while it is possible to prevent keyboard users from moving focus to elements outside of the dialog, screen reader users may still be able to navigate to that content using their screen reader's virtual cursor.
overview - Accessibility
warning: needs updating introduction here's a look at working
examples and best practices in building accessible javascript widgets.
... general resources dhtml style guide provides keyboard interaction recommendations wai-aria authoring practices guide checkbox aria toggle button and tri-state checkbox
examples (from "the paciello group blog") aria example checkbox widgets from the university of illinois menu using wai-aria roles and states with the yui menu control slider from the paciello group blog: aria slider, part one, part two, part threet (example) creating an accessible, internationalized dojo rating widget tabs enhancing tabview accessibility with wai-aria roles and states, from the yui blog enhancing the jquery ui tabs accordingly to wcag 2.0 and aria tab panel example here on codetalks lightbox wcag 2.0 and aria-conformant lightbox application http://majx-js.digissime.net/js/popin/ ...
ARIA - Accessibility
videos of screen readers using aria see both real and simplified
examples from around the web, including "before" and "after" aria videos.
...see also, aria landmark implementation notes and
examples on real sites (updated as of july 2011).
Operable - Accessibility
examples include scrolling text and videos.
...
examples include carousels or rotating annoucements.
Color contrast - Accessibility
examples let's have a look at some simple html and css code: <div class="good">good contrast</div> <div class="bad">bad contrast</div> div { /* general div styles here */ } .good { background-color: #fae6fa; } .bad { background-color: #400064; } both pieces of text have their default black color.
...try using it on the live
examples in the description section.
@counter-style - CSS: Cascading Style Sheets
er-style <counter-style-name> { [ system: <counter-system>; ] | [ symbols: <counter-symbols>; ] | [ additive-symbols: <additive-symbols>; ] | [ negative: <negative-symbol>; ] | [ prefix: <prefix>; ] | [ suffix: <suffix>; ] | [ range: <range>; ] | [ pad: <padding>; ] | [ speak-as: <speak-as>; ] | [ fallback: <counter-style-name>; ] }where <counter-style-name> = <custom-ident>
examples specifying symbols with counter-style @counter-style circled-alpha { system: fixed; symbols: Ⓐ Ⓑ Ⓒ Ⓓ Ⓔ Ⓕ Ⓖ Ⓗ Ⓘ Ⓙ Ⓚ Ⓛ Ⓜ Ⓝ Ⓞ Ⓟ Ⓠ Ⓡ Ⓢ Ⓣ Ⓤ Ⓥ Ⓦ Ⓧ Ⓨ Ⓩ; suffix: " "; } the above counter style rule can be applied to lists like this: .items { list-style: circled-alpha; } which will produce lists like this: Ⓐ one Ⓑ two Ⓒ three Ⓓ ...
... Ⓨ twenty five Ⓩ twenty six 27 twenty seven 28 twenty eight 29 twenty nine 30 thirty see more
examples on the demo page.
grid - CSS: Cascading Style Sheets
examples of grid-based devices include text-only terminals and basic phones with only one fixed font.
...
examples html <p class="unknown">i don't know if you're using a grid device.
update - CSS: Cascading Style Sheets
examples: e-book readers or severely underpowered devices.
...
examples html <p>if this text animates for you, you are using a fast-updating device.</p> css @keyframes jiggle { from { transform: translatey(0); } to { transform: translatey(25px); } } @media (update: fast) { p { animation: 1s jiggle linear alternate infinite; } } result specifications specification status comment media queries level 4the definition of 'update' in that specification.
@media - CSS: Cascading Style Sheets
<mf-value>where <mf-name> = <ident><mf-value> = <number> | <dimension> | <ident> | <ratio>
examples testing for print and screen media types @media print { body { font-size: 10pt; } } @media screen { body { font-size: 13px; } } @media screen, print { body { line-height: 1.2; } } @media only screen and (min-width: 320px) and (max-width: 480px) and (resolution: 150dpi) { body { line-height: 1.4; } } introduced in media queries level 4 is a new range syntax that allows for l...
...ess verbose media queries when testing for any feature accepting a range, as shown in the below
examples: @media (height > 600px) { body { line-height: 1.4; } } @media (400px <= width <= 700px) { body { line-height: 1.4; } } for more
examples, please see using media queries.
@supports - CSS: Cascading Style Sheets
the following
examples are both valid: @supports not (not (transform-origin: 2px)) {} @supports (display: grid) and (not (display: inline-grid)) {} note: there is no need to enclose the not operator between two parentheses at the top level.
...'='<attr-modifier> = i | s
examples testing for the support of a given css property @supports (animation-name: test) { … /* css applied when animations are supported without a prefix */ @keyframes { /* other at-rules can be nested inside */ … } } testing for the support of a given css property or a prefixed version @supports ((perspective: 10px) or (-moz-perspective: 10px) or (-webkit-perspective: 10px) or ...
Using CSS animations - CSS: Cascading Style Sheets
examples note: some older browsers (pre-2017) may need prefixes; the live
examples you can click to see in your browser include the -webkit prefixed syntax.
...let’s look at some quick
examples to explain the different permutations: in this first example, we have three animation names set, but only one duration and iteration count.
CSS Box Alignment - CSS: Cascading Style Sheets
basic
examples the following
examples demonstrate how some of the box alignment properties are applied in grid and flexbox.
... both of these
examples have justify-content: start, however the location of start changes according to the writing mode.
Mastering Wrapping of Flex Items - CSS: Cascading Style Sheets
single-dimensional layout explained as we have seen from the above
examples if our items are allowed to grow and shrink, when there are fewer items in the last row or column then those items grow to fill the available space.
... note: use firefox for the below two
examples as chrome and safari treat collapse as hidden.
Ordering Flex Items - CSS: Cascading Style Sheets
the row-related
examples above demonstrate how row and row-reverse work in a left-to-right language such as english.
... by tabbing around any of the live
examples on this page, you can see how order is potentially creating a strange experience for anyone not using a pointing device of some kind.
Variable fonts guide - CSS: Cascading Style Sheets
you can use these four-letter tags in css to specify a point along that axis of variation, as will be show in the code
examples below.
... registered axes and existing css attributes in this section we'll demonstrate the five registered axes defined with
examples and the corresponding css.
Shapes from box values - CSS: Cascading Style Sheets
in all of the
examples below i am using an element which has padding, a border, and a margin defined in order that you can see the different ways in which content will flow.
...the
examples shown above show one such use case.
Using media queries - CSS: Cascading Style Sheets
note: the
examples on this page use css's @media for illustrative purposes, but the basic syntax remains the same for all types of media queries.
...} for more media feature
examples, please see the reference page for each specific feature.
align-content - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...baseline<content-distribution> = space-between | space-around | space-evenly | stretch<overflow-position> = unsafe | safe<content-position> = center | start | end | flex-start | flex-end
examples css #container { height:200px; width: 240px; align-content: center; /* can be changed in the live sample */ background-color: #8c8c8c; } .flex { display: flex; flex-wrap: wrap; } .grid { display: grid; grid-template-columns: repeat(auto-fill, 50px); } div > div { box-sizing: border-box; border: 2px solid #8c8c8c; width: 50px; display: flex; align-items: center; ju...
align-items - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...baseline<overflow-position> = unsafe | safe<self-position> = center | start | end | self-start | self-end | flex-start | flex-end
examples css #container { height:200px; width: 240px; align-items: center; /* can be changed in the live sample */ background-color: #8c8c8c; } .flex { display: flex; flex-wrap: wrap; } .grid { display: grid; grid-template-columns: repeat(auto-fill, 50px); } div > div { box-sizing: border-box; border: 2px solid #8c8c8c; width: 50px; display: flex; align-items: center; just...
align-self - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...baseline<overflow-position> = unsafe | safe<self-position> = center | start | end | self-start | self-end | flex-start | flex-end
examples html <section> <div>item #1</div> <div>item #2</div> <div>item #3</div> </section> css section { display: flex; align-items: center; height: 120px; background: beige; } div { height: 60px; background: cyan; margin: 5px; } div:nth-child(3) { align-self: flex-end; background: pink; } result specifications specification status comment cs...
all - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... formal definition initial valuethere is no practical initial value for it.applies toall elementsinheritednocomputed valueas the specified value applies to each property this is a shorthand for.animation typeas each of the properties of the shorthand (all properties but unicode-bidi and direction) formal syntax initial | inherit | unset | revert
examples html <blockquote id="quote"> lorem ipsum dolor sit amet, consectetur adipiscing elit.
animation-delay - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... formal definition initial value0sapplies toall elements, ::before and ::after pseudo-elementsinheritednocomputed valueas specifiedanimation typediscrete formal syntax <time>#
examples see css animations for
examples.
animation-direction - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... formal definition initial valuenormalapplies toall elements, ::before and ::after pseudo-elementsinheritednocomputed valueas specifiedanimation typediscrete formal syntax <single-animation-direction>#where <single-animation-direction> = normal | reverse | alternate | alternate-reverse
examples see css animations for
examples.
animation-duration - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... formal definition initial value0sapplies toall elements, ::before and ::after pseudo-elementsinheritednocomputed valueas specifiedanimation typediscrete formal syntax <time>#
examples see css animations for
examples.
animation-iteration-count - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... formal definition initial value1applies toall elements, ::before and ::after pseudo-elementsinheritednocomputed valueas specifiedanimation typediscrete formal syntax <single-animation-iteration-count>#where <single-animation-iteration-count> = infinite | <number>
examples see css animations for
examples.
animation-name - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... formal definition initial valuenoneapplies toall elements, ::before and ::after pseudo-elementsinheritednocomputed valueas specifiedanimation typediscrete formal syntax [ none | <keyframes-name> ]#where <keyframes-name> = <custom-ident> | <string>
examples see css animations for
examples.
animation-play-state - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... formal definition initial valuerunningapplies toall elements, ::before and ::after pseudo-elementsinheritednocomputed valueas specifiedanimation typediscrete formal syntax <single-animation-play-state>#where <single-animation-play-state> = running | paused
examples see css animations for
examples.
appearance (-moz-appearance, -webkit-appearance) - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... formal definition initial valueautoapplies toall elementsinheritednocomputed valueas specifiedanimation typediscrete formal syntax none | auto | button | textfield | menulist-button | <compat-auto>where <compat-auto> = searchfield | textarea | push-button | slider-horizontal | checkbox | radio | square-button | menulist | listbox | meter | progress-bar
examples the following would make an element look like a menulist button: .exampleone { appearance: menulist-button; } see also this jsfiddle for an example showing how you might use appearance: none to apply custom styling to radio buttons and checkboxes.
backface-visibility - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... formal definition initial valuevisibleapplies totransformable elementsinheritednocomputed valueas specifiedanimation typediscrete formal syntax visible | hidden
examples cube with transparent and opaque faces this example shows a cube with transparent faces, and one with opaque faces.
background-attachment - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...it also applies to ::first-letter and ::first-line.inheritednocomputed valueas specifiedanimation typediscrete formal syntax <attachment>#where <attachment> = scroll | fixed | local
examples simple example html <p> there were doors all round the hall, but they were all locked; and when alice had been all the way down one side and up the other, trying every door, she walked sadly down the middle, wondering how she was ever to get out again.
background-blend-mode - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...it also applies to ::first-letter and ::first-line.inheritednocomputed valueas specifiedanimation typediscrete formal syntax <blend-mode>#where <blend-mode> = normal | multiply | screen | overlay | darken | lighten | color-dodge | color-burn | hard-light | soft-light | difference | exclusion | hue | saturation | color | luminosity
examples <div id="div"></div> <select id="select"> <option>normal</option> <option>multiply</option> <option selected>screen</option> <option>overlay</option> <option>darken</option> <option>lighten</option> <option>color-dodge</option> <option>color-burn</option> <option>hard-light</option> <option>soft-light</option> <option>difference</option> <option>ex...
background-clip - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...it also applies to ::first-letter and ::first-line.inheritednocomputed valueas specifiedanimation typediscrete formal syntax <box>#where <box> = border-box | padding-box | content-box
examples html <p class="border-box">the background extends behind the border.</p> <p class="padding-box">the background extends to the inside edge of the border.</p> <p class="content-box">the background extends only to the edge of the content box.</p> <p class="text">the background is clipped to the foreground text.</p> css p { border: .8em darkviolet; border-style: dotted double; margin: 1em ...
background-color - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...)where <alpha-value> = <number> | <percentage><hue> = <number> | <angle>
examples html <div class="exampleone"> lorem ipsum dolor sit amet, consectetuer </div> <div class="exampletwo"> lorem ipsum dolor sit amet, consectetuer </div> <div class="examplethree"> lorem ipsum dolor sit amet, consectetuer </div> css .exampleone { background-color: teal; color: white; } .exampletwo { background-color: rgb(153,102,153); color: rgb(255,255,204); } .examplethree { ...
background-image - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...ge><hue> = <number> | <angle><linear-color-stop> = <color> <color-stop-length>?<linear-color-hint> = <length-percentage><length-percentage> = <length> | <percentage><angular-color-stop> = <color> && <color-stop-angle>?<angular-color-hint> = <angle-percentage>where <color-stop-length> = <length-percentage>{1,2}<color-stop-angle> = <angle-percentage>{1,2}<angle-percentage> = <angle> | <percentage>
examples layering background images note that the star image is partially transparent and is layered over the cat image.
background-origin - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...it also applies to ::first-letter and ::first-line.inheritednocomputed valueas specifiedanimation typediscrete formal syntax <box>#where <box> = border-box | padding-box | content-box
examples setting background origins .example { border: 10px double; padding: 10px; background: url('image.jpg'); background-position: center left; background-origin: content-box; } #example2 { border: 4px solid black; padding: 10px; background: url('image.gif'); background-repeat: no-repeat; background-origin: border-box; } div { background-image: url('logo.jpg'), url('mainback...
background-position-x - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...]#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
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...]#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-repeat - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...it also applies to ::first-letter and ::first-line.inheritednocomputed valuea list, each item consisting of two keywords, one per dimensionanimation typediscrete formal syntax <repeat-style>#where <repeat-style> = repeat-x | repeat-y | [ repeat | space | round | no-repeat ]{1,2}
examples setting background-repeat html <ol> <li>no-repeat <div class="one"></div> </li> <li>repeat <div class="two"></div> </li> <li>repeat-x <div class="three"></div> </li> <li>repeat-y <div class="four"></div> </li> <li>space <div class="five"></div> </li> <li>round <div class="six"></div> </li> <li>repeat-x, repeat-y (multiple images) <div class...
background-size - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...letter and ::first-line.inheritednopercentagesrelative to the background positioning areacomputed valueas specified, but with relative lengths converted into absolute lengthsanimation typerepeatable list of simple list of length, percentage, or calc formal syntax <bg-size>#where <bg-size> = [ <length-percentage> | auto ]{1,2} | cover | containwhere <length-percentage> = <length> | <percentage>
examples please see scaling background images for
examples.
background - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...op>where <alpha-value> = <number> | <percentage><hue> = <number> | <angle><linear-color-stop> = <color> <color-stop-length>?<linear-color-hint> = <length-percentage><angular-color-stop> = <color> && <color-stop-angle>?<angular-color-hint> = <angle-percentage>where <color-stop-length> = <length-percentage>{1,2}<color-stop-angle> = <angle-percentage>{1,2}<angle-percentage> = <angle> | <percentage>
examples setting backgrounds with color keywords and images html <p class="topbanner"> starry sky<br/> twinkle twinkle<br/> starry sky </p> <p class="warning">here is a paragraph<p> css .warning { background: pink; } .topbanner { background: url("https://mdn.mozillademos.org/files/11983/starsolid.gif") #99f repeat-y fixed; } result specifications specification status c...
<basic-shape> - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples animated polygon in this example, we use the @keyframes at-rule to animate a clip path between two polygons.
block-size - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... formal definition initial valueautoapplies tosame as width and heightinheritednopercentagesblock-size of containing blockcomputed valuesame as width and heightanimation typea length, percentage or calc(); formal syntax <'width'>
examples block size with vertical text html <p class="exampletext">example text</p> css .exampletext { writing-mode: vertical-rl; background-color: yellow; block-size: 200px; } result specifications specification status comment css logical properties and values level 1the definition of 'block-size' in that specification.
border-block-end-color - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... formal definition initial valuecurrentcolorapplies toall elementsinheritednocomputed valuecomputed coloranimation typea color formal syntax <'border-top-color'>
examples border color with vertical text html <div> <p class="exampletext">example text</p> </div> css div { background-color: yellow; width: 120px; height: 120px; } .exampletext { writing-mode: vertical-lr; border: 10px solid blue; border-block-end-color: red; } results specifications specification status comment css logical properties and values leve...
border-block-end-style - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... formal definition initial valuenoneapplies toall elementsinheritednocomputed valueas specifiedanimation typediscrete formal syntax <'border-top-style'>
examples dashed border with vertical text html <div> <p class="exampletext">example text</p> </div> css div { background-color: yellow; width: 120px; height: 120px; } .exampletext { writing-mode: vertical-lr; border: 5px solid blue; border-block-end-style: dashed; } results specifications specification status comment css logical properties and values l...
border-block-end-width - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... formal definition initial valuemediumapplies toall elementsinheritednopercentageslogical-width of containing blockcomputed valueabsolute length; 0 if the border style is none or hiddenanimation typea length formal syntax <'border-top-width'>
examples border width with veritcal text html <div> <p class="exampletext">example text</p> </div> css div { background-color: yellow; width: 120px; height: 120px; } .exampletext { writing-mode: vertical-lr; border: 1px solid blue; border-block-end-width: 5px; } results specifications specification status comment css logical properties and values level...
border-block-end - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...)where <alpha-value> = <number> | <percentage><hue> = <number> | <angle>
examples border with vertical text html <div> <p class="exampletext">example text</p> </div> css div { background-color: yellow; width: 120px; height: 120px; } .exampletext { writing-mode: vertical-rl; border-block-end: 5px dashed blue; } results specifications specification status comment css logical properties and values level 1the definition of 'borde...
border-block-start-color - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... values <'color'> see border-color formal definition initial valuecurrentcolorapplies toall elementsinheritednocomputed valuecomputed coloranimation typea color formal syntax <'border-top-color'>
examples border color with vertical text html <div> <p class="exampletext">example text</p> </div> css div { background-color: yellow; width: 120px; height: 120px; } .exampletext { writing-mode: vertical-lr; border: 10px solid blue; border-block-start-color: red; } results specifications specification status comment css logical properties and values le...
border-block-start-style - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... formal definition initial valuenoneapplies toall elementsinheritednocomputed valueas specifiedanimation typediscrete formal syntax <'border-top-style'>
examples dashed border wtih vertical text html <div> <p class="exampletext">example text</p> </div> css div { background-color: yellow; width: 120px; height: 120px; } .exampletext { writing-mode: vertical-lr; border: 5px solid blue; border-block-start-style: dashed; } results specifications specification status comment css logical properties and values...
border-block-start-width - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... formal definition initial valuemediumapplies toall elementsinheritednopercentageslogical-width of containing blockcomputed valueabsolute length; 0 if the border style is none or hiddenanimation typea length formal syntax <'border-top-width'>
examples border width with vertical text html <div> <p class="exampletext">example text</p> </div> css div { background-color: yellow; width: 120px; height: 120px; } .exampletext { writing-mode: vertical-lr; border: 1px solid blue; border-block-start-width: 5px; } results specifications specification status comment css logical properties and values lev...
border-block-start - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...)where <alpha-value> = <number> | <percentage><hue> = <number> | <angle>
examples border with vertical text html <div> <p class="exampletext">example text</p> </div> css div { background-color: yellow; width: 120px; height: 120px; } .exampletext { writing-mode: vertical-rl; border-block-start: 5px dashed blue; } specifications specification status comment css logical properties and values level 1the definition of 'border-block...
border-bottom-color - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...it also applies to ::first-letter.inheritednocomputed valuecomputed coloranimation typea color formal syntax <'border-top-color'>
examples a simple div with a border html <div class="mybox"> <p>this is a box with a border around it.
border-bottom-left-radius - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...it also applies to ::first-letter.inheritednopercentagesrefer to the corresponding dimension of the border boxcomputed valuetwo absolute <length>s or <percentage>sanimation typea length, percentage or calc(); formal syntax <length-percentage>{1,2}where <length-percentage> = <length> | <percentage>
examples live example code .
border-bottom-right-radius - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...it also applies to ::first-letter.inheritednopercentagesrefer to the corresponding dimension of the border boxcomputed valuetwo absolute <length>s or <percentage>sanimation typea length, percentage or calc(); formal syntax <length-percentage>{1,2}where <length-percentage> = <length> | <percentage>
examples live example code .
border-bottom-style - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...it also applies to ::first-letter.inheritednocomputed valueas specifiedanimation typediscrete formal syntax <line-style>where <line-style> = none | hidden | dotted | dashed | solid | double | groove | ridge | inset | outset
examples demonstrating all border styles html <table> <tr> <td class="b1">none</td> <td class="b2">hidden</td> <td class="b3">dotted</td> <td class="b4">dashed</td> </tr> <tr> <td class="b5">solid</td> <td class="b6">double</td> <td class="b7">groove</td> <td class="b8">ridge</td> </tr> <tr> <td class="b9">inset</td> <td class="b10">outset</td> </tr> ...
border-bottom-width - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...it also applies to ::first-letter.inheritednocomputed valuethe absolute length or 0 if border-bottom-style is none or hiddenanimation typea length formal syntax <line-width>where <line-width> = <length> | thin | medium | thick
examples comparing bottom border widths html <div>element 1</div> <div>element 2</div> css div { border: 1px solid red; margin: 1em 0; } div:nth-child(1) { border-bottom-width: thick; } div:nth-child(2) { border-bottom-width: 2em; } result specifications specification status comment css backgrounds and borders module level 3the definition of 'border-bottom-wi...
border-bottom - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...)where <alpha-value> = <number> | <percentage><hue> = <number> | <angle>
examples applying a bottom border html <div> this box has a border on the bottom side.
border-collapse - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... formal definition initial valueseparateapplies totable and inline-table elementsinheritedyescomputed valueas specifiedanimation typediscrete formal syntax collapse | separate
examples a colorful table of browser engines html <table class="separate"> <caption><code>border-collapse: separate</code></caption> <tbody> <tr><th>browser</th> <th>layout engine</th></tr> <tr><td class="fx">firefox</td> <td class="gk">gecko</td></tr> <tr><td class="ed">edge</td> <td class="tr">edgehtml</td></tr> <tr><td class="sa">safari</td> <td class="wk">webkit</td></tr> <t...
border-color - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...)where <alpha-value> = <number> | <percentage><hue> = <number> | <angle>
examples complete border-color usage html <div id="justone"> <p><code>border-color: red;</code> is equivalent to</p> <ul><li><code>border-top-color: red;</code></li> <li><code>border-right-color: red;</code></li> <li><code>border-bottom-color: red;</code></li> <li><code>border-left-color: red;</code></li> </ul> </div> <div id="horzvert"> <p><code>border-color: gold red;</code> is eq...
border-image-outset - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...it also applies to ::first-letter.inheritednocomputed valueas specified, but with relative lengths converted into absolute lengthsanimation typeby computed value type formal syntax [ <length> | <number> ]{1,4}
examples outsetting a border image html <div id="outset">this element has an outset border image!</div> css #outset { width: 10rem; background: #cef; border: 1.4rem solid; border-image: radial-gradient(#ff2, #55f) 40; border-image-outset: 1.5; /* 1.5 × 1.4rem = 2.1rem */ margin: 2.1rem; } result specifications specification status comment css background...
border-image-repeat - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...it also applies to ::first-letter.inheritednocomputed valueas specifiedanimation typediscrete formal syntax [ stretch | repeat | round | space ]{1,2}
examples repeating border images css #bordered { width: 12rem; margin-bottom: 1rem; padding: 1rem; border: 40px solid; border-image: url("https://mdn.mozillademos.org/files/4127/border.png") 27; border-image-repeat: stretch; /* can be changed in the live sample */ } html <div id="bordered">you can try out various border repetition rules on me!</div> <select id="repetition"> <option ...
border-image-slice - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...it also applies to ::first-letter.inheritednopercentagesrefer to the size of the border imagecomputed valueone to four percentage(s) (as specified) or absolute length(s), plus the keyword fill if specifiedanimation typeby computed value type formal syntax <number-percentage>{1,4} && fill?where <number-percentage> = <number> | <percentage>
examples adjustable border width and slice the folowing example shows a simple <div> with a border image set on it.
border-image-source - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...ge><hue> = <number> | <angle><linear-color-stop> = <color> <color-stop-length>?<linear-color-hint> = <length-percentage><length-percentage> = <length> | <percentage><angular-color-stop> = <color> && <color-stop-angle>?<angular-color-hint> = <angle-percentage>where <color-stop-length> = <length-percentage>{1,2}<color-stop-angle> = <angle-percentage>{1,2}<angle-percentage> = <angle> | <percentage>
examples please see border-image for
examples.
border-image-width - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...it also applies to ::first-letter.inheritednopercentagesrefer to the width or height of the border image areacomputed valueas specified, but with relative lengths converted into absolute lengthsanimation typeby computed value type formal syntax [ <length-percentage> | <number> | auto ]{1,4}where <length-percentage> = <length> | <percentage>
examples tiling a border image this example creates a border image using the following ".png" file, which is 90 by 90 pixels: thus, each circle in the source image is 30 by 30 pixels.
border-image - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...| <'border-image-repeat'>
examples bitmap in this example, we will apply a diamond pattern to an element's borders.
border-inline-end-color - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... formal definition initial valuecurrentcolorapplies toall elementsinheritednocomputed valuecomputed coloranimation typea color formal syntax <'border-top-color'>
examples html <div> <p class="exampletext">example text</p> </div> css div { background-color: yellow; width: 120px; height: 120px; } .exampletext { writing-mode: vertical-lr; border: 10px solid blue; border-inline-end-color: red; } specifications specification status comment css logical properties and values level 1the definition of 'border-inline-end-c...
border-inline-end-style - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... formal definition initial valuenoneapplies toall elementsinheritednocomputed valueas specifiedanimation typediscrete formal syntax <'border-top-style'>
examples html <div> <p class="exampletext">example text</p> </div> css div { background-color: yellow; width: 120px; height: 120px; } .exampletext { writing-mode: vertical-lr; border: 5px solid blue; border-inline-end-style: dashed; } results specifications specification status comment css logical properties and values level 1the definition of 'border-i...
border-inline-end-width - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... formal definition initial valuemediumapplies toall elementsinheritednopercentageslogical-width of containing blockcomputed valueabsolute length; 0 if the border style is none or hiddenanimation typea length formal syntax <'border-top-width'>
examples applying a border with vertical text html <div> <p class="exampletext">example text</p> </div> css div { background-color: yellow; width: 120px; height: 120px; } .exampletext { writing-mode: vertical-lr; border: 1px solid blue; border-inline-end-width: 5px; } results specifications specification status comment css logical properties and values...
border-inline-end - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...)where <alpha-value> = <number> | <percentage><hue> = <number> | <angle>
examples html <div> <p class="exampletext">example text</p> </div> css div { background-color: yellow; width: 120px; height: 120px; } .exampletext { writing-mode: vertical-rl; border-inline-end: 5px dashed blue; } specifications specification status comment css logical properties and values level 1the definition of 'border-inline-end' in that specification...
border-inline-start-color - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... formal definition initial valuecurrentcolorapplies toall elementsinheritednocomputed valuecomputed coloranimation typea color formal syntax <'border-top-color'>
examples html <div> <p class="exampletext">example text</p> </div> css div { background-color: yellow; width: 120px; height: 120px; } .exampletext { writing-mode: vertical-lr; border: 10px solid blue; border-inline-start-color: red; } specifications specification status comment css logical properties and values level 1the definition of 'border-inline-sta...
border-inline-start-style - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... formal definition initial valuenoneapplies toall elementsinheritednocomputed valueas specifiedanimation typediscrete formal syntax <'border-top-style'>
examples html <div> <p class="exampletext">example text</p> </div> css div { background-color: yellow; width: 120px; height: 120px; } .exampletext { writing-mode: vertical-lr; border: 5px solid blue; border-inline-start-style: dashed; } specifications specification status comment css logical properties and values level 1the definition of 'border-inline-s...
border-inline-start-width - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... formal definition initial valuemediumapplies toall elementsinheritednopercentageslogical-width of containing blockcomputed valueabsolute length; 0 if the border style is none or hiddenanimation typea length formal syntax <'border-top-width'>
examples html <div> <p class="exampletext">example text</p> </div> css div { background-color: yellow; width: 120px; height: 120px; } .exampletext { writing-mode: vertical-lr; border: 1px solid blue; border-inline-start-width: 5px; } specifications specification status comment css logical properties and values level 1the definition of 'border-inline-star...
border-inline-start - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...)where <alpha-value> = <number> | <percentage><hue> = <number> | <angle>
examples html <div> <p class="exampletext">example text</p> </div> css div { background-color: yellow; width: 120px; height: 120px; } .exampletext { writing-mode: vertical-rl; border-inline-start: 5px dashed blue; } specifications specification status comment css logical properties and values level 1the definition of 'border-inline-start' in that specifica...
border-left-color - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...)where <alpha-value> = <number> | <percentage><hue> = <number> | <angle>
examples a simple div with a border html <div class="mybox"> <p>this is a box with a border around it.
border-left-style - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...it also applies to ::first-letter.inheritednocomputed valueas specifiedanimation typediscrete formal syntax <line-style>where <line-style> = none | hidden | dotted | dashed | solid | double | groove | ridge | inset | outset
examples html <table> <tr> <td class="b1">none</td> <td class="b2">hidden</td> <td class="b3">dotted</td> <td class="b4">dashed</td> </tr> <tr> <td class="b5">solid</td> <td class="b6">double</td> <td class="b7">groove</td> <td class="b8">ridge</td> </tr> <tr> <td class="b9">inset</td> <td class="b10">outset</td> </tr> </table> css /* define look of ...
border-left-width - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...it also applies to ::first-letter.inheritednocomputed valuethe absolute length or 0 if border-left-style is none or hiddenanimation typea length formal syntax <line-width>where <line-width> = <length> | thin | medium | thick
examples comparing border widths html <div>element 1</div> <div>element 2</div> css div { border: 1px solid red; margin: 1em 0; } div:nth-child(1) { border-left-width: thick; } div:nth-child(2) { border-left-width: 2em; } result specifications specification status comment css backgrounds and borders module level 3the definition of 'border-left-width' in that ...
border-left - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...)where <alpha-value> = <number> | <percentage><hue> = <number> | <angle>
examples applying a left border html <div> this box has a border on the left side.
border-radius - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...ypeas each of the properties of the shorthand:border-top-left-radius: a length, percentage or calc();border-top-right-radius: a length, percentage or calc();border-bottom-right-radius: a length, percentage or calc();border-bottom-left-radius: a length, percentage or calc(); formal syntax <length-percentage>{1,4} [ / <length-percentage>{1,4} ]?where <length-percentage> = <length> | <percentage>
examples border: solid 10px; /* the border will curve into a 'd' */ border-radius: 10px 40px 40px 10px; border: groove 1em red; border-radius: 2em; background: gold; border: ridge gold; border-radius: 13em/3em; border: none; border-radius: 40px 10px; border: none; border-radius: 50%; border: dotted; border-width: 10px 4px; border-radius: 10px 40px; border: dash...
border-right-color - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...)where <alpha-value> = <number> | <percentage><hue> = <number> | <angle>
examples a simple div with a border html <div class="mybox"> <p>this is a box with a border around it.
border-right-style - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...it also applies to ::first-letter.inheritednocomputed valueas specifiedanimation typediscrete formal syntax <line-style>where <line-style> = none | hidden | dotted | dashed | solid | double | groove | ridge | inset | outset
examples border styles html <table> <tr> <td class="b1">none</td> <td class="b2">hidden</td> <td class="b3">dotted</td> <td class="b4">dashed</td> </tr> <tr> <td class="b5">solid</td> <td class="b6">double</td> <td class="b7">groove</td> <td class="b8">ridge</td> </tr> <tr> <td class="b9">inset</td> <td class="b10">outset</td> </tr> </table> css /* ...
border-right-width - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...it also applies to ::first-letter.inheritednocomputed valuethe absolute length or 0 if border-right-style is none or hiddenanimation typea length formal syntax <line-width>where <line-width> = <length> | thin | medium | thick
examples comparing border widths html <div>element 1</div> <div>element 2</div> css div { border: 1px solid red; margin: 1em 0; } div:nth-child(1) { border-right-width: thick; } div:nth-child(2) { border-right-width: 2em; } result specifications specification status comment css backgrounds and borders module level 3the definition of 'border-right-width' in th...
border-right - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...)where <alpha-value> = <number> | <percentage><hue> = <number> | <angle>
examples applying a right border to a div html <div> this box has a border on the right side.
border-spacing - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples spacing and padding table cells this example applies a spacing of .5em vertically and 1em horizontally between a table's cells.
border-style - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...it also applies to ::first-letter.inheritednocomputed valueas each of the properties of the shorthand:border-bottom-style: as specifiedborder-left-style: as specifiedborder-right-style: as specifiedborder-top-style: as specifiedanimation typediscrete formal syntax <line-style>{1,4}where <line-style> = none | hidden | dotted | dashed | solid | double | groove | ridge | inset | outset
examples table with all property values here is an example of all the property values.
border-top-color - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...)where <alpha-value> = <number> | <percentage><hue> = <number> | <angle>
examples a simple div with a border html <div class="mybox"> <p>this is a box with a border around it.
border-top-left-radius - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...it also applies to ::first-letter.inheritednopercentagesrefer to the corresponding dimension of the border boxcomputed valuetwo absolute <length>s or <percentage>sanimation typea length, percentage or calc(); formal syntax <length-percentage>{1,2}where <length-percentage> = <length> | <percentage>
examples live example code an arc of ellipse is used as the border div { border-top-left-radius: 40px 40px; } an arc of ellipse is used as the border div { border-top-left-radius: 40px 20px; } the box is a square: an arc of circle is used as the border div { border-top-left-radius: 40%; } ...
border-top-right-radius - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...it also applies to ::first-letter.inheritednopercentagesrefer to the corresponding dimension of the border boxcomputed valuetwo absolute <length>s or <percentage>sanimation typea length, percentage or calc(); formal syntax <length-percentage>{1,2}where <length-percentage> = <length> | <percentage>
examples live example code an arc of circle is used as the border div { border-top-right-radius: 40px 40px; } an arc of ellipse is used as the border div { border-top-right-radius: 40px 20px; } the box is a square: an arc of circle is used as the border div { border-top-right-radius: 40%; } ...
border-top-style - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...it also applies to ::first-letter.inheritednocomputed valueas specifiedanimation typediscrete formal syntax <line-style>where <line-style> = none | hidden | dotted | dashed | solid | double | groove | ridge | inset | outset
examples html <table> <tr> <td class="b1">none</td> <td class="b2">hidden</td> <td class="b3">dotted</td> <td class="b4">dashed</td> </tr> <tr> <td class="b5">solid</td> <td class="b6">double</td> <td class="b7">groove</td> <td class="b8">ridge</td> </tr> <tr> <td class="b9">inset</td> <td class="b10">outset</td> </tr> </table> css /* define look of ...
border-top-width - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...it also applies to ::first-letter.inheritednocomputed valuethe absolute length or 0 if border-top-style is none or hiddenanimation typea length formal syntax <line-width>where <line-width> = <length> | thin | medium | thick
examples html <div>element 1</div> <div>element 2</div> css div { border: 1px solid red; margin: 1em 0; } div:nth-child(1) { border-top-width: thick; } div:nth-child(2) { border-top-width: 2em; } result specifications specification status comment css backgrounds and borders module level 3the definition of 'border-top-width' in that specification.
border-top - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...)where <alpha-value> = <number> | <percentage><hue> = <number> | <angle>
examples applying a top border html <div> this box has a border on the top side.
border-width - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...the absolute length or 0 if border-right-style is none or hiddenborder-top-width: the absolute length or 0 if border-top-style is none or hiddenanimation typeas each of the properties of the shorthand:border-bottom-width: a lengthborder-left-width: a lengthborder-right-width: a lengthborder-top-width: a length formal syntax <line-width>{1,4}where <line-width> = <length> | thin | medium | thick
examples a mix of values and lengths html <p id="sval"> one value: 6px wide border on all 4 sides</p> <p id="bival"> two different values: 2px wide top and bottom border, 10px wide right and left border</p> <p id="treval"> three different values: 0.3em top, 9px bottom, and zero width right and left</p> <p id="fourval"> four different values: "thin" top, "medium" right, "thick" bottom, a...
border - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...)where <alpha-value> = <number> | <percentage><hue> = <number> | <angle>
examples setting a pink outset border html <div>i have a border, an outline, and a box shadow!
bottom - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... formal definition initial valueautoapplies topositioned elementsinheritednopercentagesrefer to the height 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 fixed positioning this example demonstrates the difference in behavior of the bottom property, when position is absolute versus fixed.
box-shadow - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...)where <alpha-value> = <number> | <percentage><hue> = <number> | <angle>
examples setting three shadows in this example, we include three shadows: an inset shadow, a regular drop shadow, and a 2px shadow that creates a border effect (we could have used an outline instead for that third shadow).
box-sizing - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... formal definition initial valuecontent-boxapplies toall elements that accept width or heightinheritednocomputed valueas specifiedanimation typediscrete formal syntax content-box | border-box
examples box sizes with content-box and border-box this example shows how different box-sizing values alter the rendered size of two otherwise identical elements.
calc() - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples positioning an object on screen with a margin calc() makes it easy to position an object with a set margin.
caption-side - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... formal definition initial valuetopapplies totable-caption elementsinheritedyescomputed valueas specifiedanimation typediscrete formal syntax top | bottom | block-start | block-end | inline-start | inline-end
examples setting captions above and below html <table class="top"> <caption>caption above the table</caption> <tr> <td>some data</td> <td>some more data</td> </tr> </table> <br> <table class="bottom"> <caption>caption below the table</caption> <tr> <td>some data</td> <td>some more data</td> </tr> </table> css .top caption { caption-side: top; } .bottom caption { ca...
caret-color - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...)where <alpha-value> = <number> | <percentage><hue> = <number> | <angle>
examples setting a custom caret color html <input value="this field uses a default caret." size="64"/> <input class="custom" value="i have a custom caret color!" size="64"/> <p contenteditable class="custom">this paragraph can be edited, and its caret has a custom color as well!</p> css input { caret-color: auto; display: block; margin-bottom: .5em; } input.custom { caret-color: red; } ...
clear - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... formal definition initial valuenoneapplies toblock-level elementsinheritednocomputed valueas specifiedanimation typediscrete formal syntax none | left | right | both | inline-start | inline-end
examples clear: left html <div class="wrapper"> <p class="black">lorem ipsum dolor sit amet, consectetuer adipiscing elit.
clip-path - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...| [ [ left | right ] <length-percentage> ] && [ [ top | bottom ] <length-percentage> ] ]<fill-rule> = nonzero | evenodd<box> = border-box | padding-box | content-box
examples comparison of html and svg <svg class="defs"> <defs> <clippath id="mypath" clippathunits="objectboundingbox"> <path d="m0.5,1 c0.5,1,0,0.7,0,0.3 a0.25,0.25,1,1,1,0.5,0.3 a0.25,0.25,1,1,1,1,0.3 c1,0.7,0.5,1,0.5,1 z" /> </clippath> </defs> </svg> <div class="grid"> <div class="col"> <div class="note">clip-path: none</div> <div class="row"> <div class="cell"> <s...
color - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...)where <alpha-value> = <number> | <percentage><hue> = <number> | <angle>
examples making text red the following are all ways to make a paragraph's text red: p { color: red; } p { color: #f00; } p { color: #ff0000; } p { color: rgb(255,0,0); } p { color: rgb(100%, 0%, 0%); } p { color: hsl(0, 100%, 50%); } /* 50% translucent */ p { color: #ff000080; } p { color: rgba(255, 0, 0, 0.5); } p { color: hsla(0, 100%, 50%, 0.5); } specifications specification stat...
column-count - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... formal definition initial valueautoapplies toblock containers except table wrapper boxesinheritednocomputed valueas specifiedanimation typean integer formal syntax <integer> | auto
examples splitting a paragraph across three columns html <p class="content-box"> this is a bunch of text split into three columns using the css `column-count` property.
column-fill - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... formal definition initial valuebalanceapplies tomulticol elementsinheritednocomputed valueas specifiedanimation typediscrete formal syntax auto | balance | balance-all
examples splitting text evenly across columns html <p class="content-box"> this is a bunch of text split into multiple columns.
column-gap (grid-column-gap) - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...applies tomulti-column elements, flex containers, grid containersinheritednopercentagesrefer to corresponding dimension of the content areacomputed valueas specified, with <length>s made absolute, and normal computing to zero except on multi-column elementsanimation typea length, percentage or calc(); formal syntax normal | <length-percentage>where <length-percentage> = <length> | <percentage>
examples flex layout html <div id="flexbox"> <div></div> <div></div> <div></div> </div> css #flexbox { display: flex; height: 100px; column-gap: 20px; } #flexbox > div { border: 1px solid green; background-color: lime; flex: auto; } result grid layout html <div id="grid"> <div></div> <div></div> <div></div> </div> css #grid { grid-column-gap: 20px; } #grid { ...
column-rule-color - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...)where <alpha-value> = <number> | <percentage><hue> = <number> | <angle>
examples setting a blue column rule html <p>this is a bunch of text split into three columns.
column-rule-style - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... formal definition initial valuenoneapplies tomulticol elementsinheritednocomputed valueas specifiedanimation typediscrete formal syntax <'border-style'>
examples setting a dashed column rule html <p>this is a bunch of text split into three columns.
column-rule-width - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... formal definition initial valuemediumapplies tomulticol elementsinheritednocomputed valuethe absolute length; 0 if the column-rule-style is none or hiddenanimation typea length formal syntax <'border-width'>
examples setting a thick column rule html <p>this is a bunch of text split into three columns.
column-rule - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...roperties of the shorthand:column-rule-color: computed colorcolumn-rule-style: as specifiedcolumn-rule-width: the absolute length; 0 if the column-rule-style is none or hiddenanimation typeas each of the properties of the shorthand:column-rule-color: a colorcolumn-rule-style: discretecolumn-rule-width: a length formal syntax <'column-rule-width'> | <'column-rule-style'> | <'column-rule-color'>
examples example 1 /* same as "medium dotted currentcolor" */ p.foo { column-rule: dotted; } /* same as "medium solid blue" */ p.bar { column-rule: solid blue; } /* same as "8px solid currentcolor" */ p.baz { column-rule: solid 8px; } p.abc { column-rule: thick inset blue; } example 2 html <p class="content-box"> this is a bunch of text split into three columns.
column-width - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... formal definition initial valueautoapplies toblock containers except table wrapper boxesinheritednocomputed valuethe absolute length, zero or largeranimation typea length formal syntax <length> | auto
examples setting column width in pixels html <p class="content-box"> lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.
columns - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... shorthand:column-width: autocolumn-count: autoapplies toblock containers except table wrapper boxesinheritednocomputed valueas each of the properties of the shorthand:column-width: the absolute length, zero or largercolumn-count: as specifiedanimation typeas each of the properties of the shorthand:column-width: a lengthcolumn-count: an integer formal syntax <'column-width'> | <'column-count'>
examples setting three equal columns html <p class="content-box"> this is a bunch of text split into three columns using the css `columns` property.
counter-increment - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...]+ | none
examples incrementing named counters h1 { counter-increment: chapter section 2 page; /* increases the value of the chapter and page counters by 1, and the section counter by 2 */ } specifications specification status comment css lists module level 3the definition of 'counter-increment' in that specification.
counter-reset - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...]+ | none
examples resetting named counters h1 { counter-reset: chapter section 1 page; /* sets the chapter and page counters to 0, and the section counter to 1 */ } specifications specification status comment css lists module level 3the definition of 'counter-reset' in that specification.
cursor - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
..., ]* [ auto | default | none | context-menu | help | pointer | progress | wait | cell | crosshair | text | vertical-text | alias | copy | move | no-drop | not-allowed | e-resize | n-resize | ne-resize | nw-resize | s-resize | se-resize | sw-resize | w-resize | ew-resize | ns-resize | nesw-resize | nwse-resize | col-resize | row-resize | all-scroll | zoom-in | zoom-out | grab | grabbing ] ]
examples setting cursor types .foo { cursor: crosshair; } .bar { cursor: zoom-in; } /* a fallback keyword value is required when using a url */ .baz { cursor: url("hyper.cur"), auto; } specifications specification status comment css basic user interface module level 3the definition of 'cursor' in that specification.
direction - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... formal definition initial valueltrapplies toall elementsinheritedyescomputed valueas specifiedanimation typediscrete formal syntax ltr | rtl
examples setting right-to-left direction blockquote { direction: rtl; } specifications specification status comment css writing modes module level 3the definition of 'direction' in that specification.
blur() - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples setting a blur with pixels and with rem blur(0) /* no effect */ blur(8px) /* blur with 8px radius */ blur(1.17rem) /* blur with 1.17rem radius */ specifications specification status filter effects module level 1the definition of 'blur()' in that specification.
brightness() - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
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
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
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.
drop-shadow() - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples setting a drop shadow using pixel offsets and blur radius /* black shadow with 10px blur */ drop-shadow(16px 16px 10px black) setting a drop shadow using rem offsets and blur radius /* reddish shadow with 1rem blur */ drop-shadow(.5rem .5rem 1rem #e23) specifications specification status filter effects module level 1the definition of 'drop-shadow()' in that specifi...
grayscale() - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
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.
hue-rotate() - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples hue-rotate(-90deg) /* same as 270deg rotation */ hue-rotate(0deg) /* no effect */ hue-rotate(90deg) /* 90deg rotation */ hue-rotate(.5turn) /* 180deg rotation */ hue-rotate(405deg) /* same as 45deg rotation */ specifications specification status filter effects module level 1the definition of 'hue-rotate()' in that specification.
invert() - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
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
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
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
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
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
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
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.
fit-content() - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples sizing grid columns with fit-content html <div id="container"> <div>item as wide as the content.</div> <div> item with more text in it.
flex-basis - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... formal definition initial valueautoapplies toflex items, including in-flow pseudo-elementsinheritednopercentagesrefer to the flex container's inner main sizecomputed valueas specified, but with relative lengths converted into absolute lengthsanimation typea length, percentage or calc(); formal syntax content | <'width'>
examples setting flex item initial sizes html <ul class="container"> <li class="flex flex1">1: flex-basis test</li> <li class="flex flex2">2: flex-basis test</li> <li class="flex flex3">3: flex-basis test</li> <li class="flex flex4">4: flex-basis test</li> <li class="flex flex5">5: flex-basis test</li> </ul> <ul class="container"> <li class="flex flex6">6: flex-basis test</li> </ul> css ...
flex-direction - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... 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 valuerowapplies toflex containersinheritednocomputed valueas specifiedanimation typediscrete formal syntax row | row-reverse | column | column-reverse
examples reversing flex container columns and rows html <h4>this is a column-reverse</h4> <div id="content"> <div class="box" style="background-color:red;">a</div> <div class="box" style="background-color:lightblue;">b</div> <div class="box" style="background-color:yellow;">c</div> </div> <h4>this is a row-reverse</h4> <div id="content1"> <div class="box1" style="background-color:red;">a</div> ...
flex-flow - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... formal definition initial valueas each of the properties of the shorthand:flex-direction: rowflex-wrap: nowrapapplies toflex containersinheritednocomputed valueas each of the properties of the shorthand:flex-direction: as specifiedflex-wrap: as specifiedanimation typediscrete formal syntax <'flex-direction'> | <'flex-wrap'>
examples setting column-reverse and wrap element { /* main-axis is the block direction with reversed main-start and main-end.
flex-grow - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... formal definition initial value0applies toflex items, including in-flow pseudo-elementsinheritednocomputed valueas specifiedanimation typea number formal syntax <number>
examples setting flex item grow factor html <h4>this is a flex-grow</h4> <h5>a,b,c and f are flex-grow:1 .
flex-shrink - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... formal definition initial value1applies toflex items, including in-flow pseudo-elementsinheritednocomputed valueas specifiedanimation typea number formal syntax <number>
examples setting flex item shrink factor html <p>the width of content is 500px; the flex-basis of the flex items is 120px.</p> <p>a, b, c have flex-shrink:1 set.
flex-wrap - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... formal definition initial valuenowrapapplies toflex containersinheritednocomputed valueas specifiedanimation typediscrete formal syntax nowrap | wrap | wrap-reverse
examples setting flex container wrap values html <h4>this is an example for flex-wrap:wrap </h4> <div class="content"> <div class="red">1</div> <div class="green">2</div> <div class="blue">3</div> </div> <h4>this is an example for flex-wrap:nowrap </h4> <div class="content1"> <div class="red">1</div> <div class="green">2</div> <div class="blue">3</div> </div> <h4>this is an example for fle...
flex - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...| <'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 ra...
font-family - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...it also applies to ::first-letter and ::first-line.inheritedyescomputed valueas specifiedanimation typediscrete formal syntax [ <family-name> | <generic-family> ]#where <family-name> = <string> | <custom-ident>+<generic-family> = serif | sans-serif | cursive | fantasy | monospace
examples some common font families .serif { font-family: times, times new roman, georgia, serif; } .sansserif { font-family: verdana, arial, helvetica, sans-serif; } .monospace { font-family: lucida console, courier, monospace; } .cursive { font-family: cursive; } .fantasy { font-family: fantasy; } .emoji { font-family: emoji; } .math { font-family: math; } .fangsong { font-family...
font-feature-settings - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples enabling various font features /* use small-cap alternate glyphs */ .smallcaps { font-feature-settings: "smcp" on; } /* convert both upper and lowercase to small caps (affects punctuation also) */ .allsmallcaps { font-feature-settings: "c2sc", "smcp"; } /* use zeros with a slash through them to differentiate from "o" */ .nicezero { font-feature-settings: "zero"; } /* enable historical forms...
font-optical-sizing - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...it also applies to ::first-letter and ::first-line.inheritedyescomputed valueas specifiedanimation typediscrete formal syntax auto | none
examples disabling optical sizing <p class="optical-sizing">this paragraph is optically sized.
font-size - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...srefer to the parent element's font sizecomputed valueas specified, but with relative lengths converted into absolute lengthsanimation typea length formal syntax <absolute-size> | <relative-size> | <length-percentage>where <absolute-size> = xx-small | x-small | small | medium | large | x-large | xx-large | xxx-large<relative-size> = larger | smaller<length-percentage> = <length> | <percentage>
examples setting font sizes css .small { font-size: xx-small; } .larger { font-size: larger; } .point { font-size: 24pt; } .percent { font-size: 200%; } html <h1 class="small">small h1</h1> <h1 class="larger">larger h1</h1> <h1 class="point">24 point h1</h1> <h1 class="percent">200% h1</h1> result specifications specification status comment css fonts module l...
font-style - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples font styles <p class="normal">this paragraph is normal.</p> <p class="italic">this paragraph is italic.</p> <p class="oblique">this paragraph is oblique.</p> .normal { font-style: normal; } .italic { font-style: italic; } .oblique { font-style: oblique; } specifications specification status comment css fonts module level 4the definition of 'font-styl...
font-synthesis - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...it also applies to ::first-letter and ::first-line.inheritedyescomputed valueas specifiedanimation typediscrete formal syntax none | [ weight | style ]
examples disabling font synthesis html <em class="syn">synthesize me!
font-variant-caps - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...it also applies to ::first-letter and ::first-line.inheritedyescomputed valueas specifiedanimation typediscrete formal syntax normal | small-caps | all-small-caps | petite-caps | all-petite-caps | unicase | titling-caps
examples setting the small-caps font variant html <p class="small-caps">firefox rocks, small caps!</p> <p class="normal">firefox rocks, normal caps!</p> css .small-caps { font-variant-caps: small-caps; font-style: italic; } .normal { font-variant-caps: normal; font-style: italic; } result specifications specification status comment css fonts module level 3th...
font-variant-ligatures - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...e | [ <common-lig-values> || <discretionary-lig-values> || <historical-lig-values> || <contextual-alt-values> ]where <common-lig-values> = [ common-ligatures | no-common-ligatures ]<discretionary-lig-values> = [ discretionary-ligatures | no-discretionary-ligatures ]<historical-lig-values> = [ historical-ligatures | no-historical-ligatures ]<contextual-alt-values> = [ contextual | no-contextual ]
examples setting font ligatures and contextual forms html <link href="//fonts.googleapis.com/css?family=lora" rel="stylesheet"> <p class="normal"> normal<br> if fi ff tf ft jf fj </p> <p class="none"> none<br> if fi ff tf ft jf fj </p> <p class="common-ligatures"> common-ligatures<br> if fi ff tf ft jf fj </p> <p class="no-common-ligatures"> no-common-ligatures<br> if fi ff tf ft jf fj ...
font-variant-numeric - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...rst-line.inheritedyescomputed valueas specifiedanimation typediscrete formal syntax normal | [ <numeric-figure-values> | <numeric-spacing-values> | <numeric-fraction-values> | ordinal | slashed-zero ]where <numeric-figure-values> = [ lining-nums | oldstyle-nums ]<numeric-spacing-values> = [ proportional-nums | tabular-nums ]<numeric-fraction-values> = [ diagonal-fractions | stacked-fractions ]
examples setting ordinal numeric forms html <p class="ordinal">1st, 2nd, 3rd, 4th, 5th</p> css /* this example uses the source sans pro opentype font, developed by adobe and used here under the terms of the sil open font license, version 1.1: http://scripts.sil.org/cms/scripts/page.php?item_id=ofl_web */ @font-face { font-family: "source sans pro"; font-style: normal; font-weight: 400; src: ...
font-variant - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... | no-contextual ]<feature-value-name> = <custom-ident><numeric-figure-values> = [ lining-nums | oldstyle-nums ]<numeric-spacing-values> = [ proportional-nums | tabular-nums ]<numeric-fraction-values> = [ diagonal-fractions | stacked-fractions ]<east-asian-variant-values> = [ jis78 | jis83 | jis90 | jis04 | simplified | traditional ]<east-asian-width-values> = [ full-width | proportional-width ]
examples setting the small-caps font variant html <p class="normal">firefox rocks!</p> <p class="small">firefox rocks!</p> css p.normal { font-variant: normal; } p.small { font-variant: small-caps; } result specifications specification status comment css fonts module level 3the definition of 'font-variant' in that specification.
font-variation-settings - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...it also applies to ::first-letter and ::first-line.inheritedyescomputed valueas specifiedanimation typea transform formal syntax normal | [ <string> <number> ]#
examples you can find a number of other variable fonts
examples at our variable fonts guide, v-fonts.com, and axis-praxis.org.
font-weight - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...numerical value as specified, with bolder and lighter transformed to the real valueanimation typea font weight formal syntax <font-weight-absolute> | bolder | lighterwhere <font-weight-absolute> = normal | bold | <number <a href="/docs/css/value_definition_syntax#brackets" title="brackets: enclose several entities, combinators, and multipliers to transform them as a single component">[1,1000]>
examples setting font weights html <p> alice was beginning to get very tired of sitting by her sister on the bank, and of having nothing to do: once or twice she had peeped into the book her sister was reading, but it had no pictures or conversations in it, "and what is the use of a book," thought alice "without pictures or conversations?" </p> <div>i'm heavy<br/> <span>i'm lighter</span> ...
font - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...<'font-family'> ] | caption | icon | menu | message-box | small-caption | status-barwhere <font-variant-css21> = [ normal | small-caps ]
examples setting font properties /* set the font size to 12px and the line height to 14px.
gap (grid-gap) - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples flex layout html <div id="flexbox"> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> </div> css #flexbox { display: flex; flex-wrap: wrap; width: 300px; gap: 20px 5px; } #flexbox > div { border: 1px solid green; background-color: lime; flex: 1 1 auto; width: 100px; height: 50px; } result grid layout html <div id="grid"> <div></...
grid-area - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...] | [ span && [ <integer> | <custom-ident> ] ]
examples setting grid areas html <div id="grid"> <div id="item1"></div> <div id="item2"></div> <div id="item3"></div> </div> css #grid { display: grid; height: 100px; grid-template: repeat(4, 1fr) / 50px 100px; } #item1 { background-color: lime; grid-area: 2 / 2 / auto / span 3; } #item2 { background-color: yellow; } #item3 { background-color: blue; } result specifications...
grid-auto-columns - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...tion typediscrete formal syntax <track-size>+where <track-size> = <track-breadth> | minmax( <inflexible-breadth> , <track-breadth> ) | fit-content( [ <length> | <percentage> ] )where <track-breadth> = <length-percentage> | <flex> | min-content | max-content | auto<inflexible-breadth> = <length> | <percentage> | min-content | max-content | autowhere <length-percentage> = <length> | <percentage>
examples setting grid column size html <div id="grid"> <div id="item1"></div> <div id="item2"></div> <div id="item3"></div> </div> css #grid { height: 100px; display: grid; grid-template-areas: "a a"; grid-gap: 10px; grid-auto-columns: 200px; } #grid > div { background-color: lime; } result specifications specification status comment css grid layou...
grid-auto-flow - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... formal definition initial valuerowapplies togrid containersinheritednocomputed valueas specifiedanimation typediscrete formal syntax [ row | column ] | dense
examples setting grid auto-placement html <div id="grid"> <div id="item1"></div> <div id="item2"></div> <div id="item3"></div> <div id="item4"></div> <div id="item5"></div> </div> <select id="direction" onchange="changegridautoflow()"> <option value="column">column</option> <option value="row">row</option> </select> <input id="dense" type="checkbox" onchange="changegridautoflow()"> <label...
grid-auto-rows - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...ation typediscrete formal syntax <track-size>+where <track-size> = <track-breadth> | minmax( <inflexible-breadth> , <track-breadth> ) | fit-content( [ <length> | <percentage> ] )where <track-breadth> = <length-percentage> | <flex> | min-content | max-content | auto<inflexible-breadth> = <length> | <percentage> | min-content | max-content | autowhere <length-percentage> = <length> | <percentage>
examples setting grid row size html <div id="grid"> <div id="item1"></div> <div id="item2"></div> <div id="item3"></div> </div> css #grid { width: 200px; display: grid; grid-template-areas: "a a"; grid-gap: 10px; grid-auto-rows: 100px; } #grid > div { background-color: lime; } result specifications specification status comment css grid layoutthe de...
grid-column-end - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...] | [ span && [ <integer> | <custom-ident> ] ]
examples setting column end for a grid item html <div class="wrapper"> <div class="box1">one</div> <div class="box2">two</div> <div class="box3">three</div> <div class="box4">four</div> <div class="box5">five</div> </div> css .wrapper { display: grid; grid-template-columns: repeat(3, 1fr); grid-auto-rows: 100px; } .box1 { grid-column-start: 1; grid-column-end: 4; grid-row-star...
grid-column-start - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...] | [ span && [ <integer> | <custom-ident> ] ]
examples setting column start for a grid item html <div class="wrapper"> <div class="box1">one</div> <div class="box2">two</div> <div class="box3">three</div> <div class="box4">four</div> <div class="box5">five</div> </div> css .wrapper { display: grid; grid-template-columns: repeat(3, 1fr); grid-auto-rows: 100px; } .box1 { grid-column-start: 1; grid-column-end: 4; grid-row-st...
grid-column - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...] | [ span && [ <integer> | <custom-ident> ] ]
examples setting grid column size and location html <div id="grid"> <div id="item1"></div> <div id="item2"></div> <div id="item3"></div> </div> css #grid { display: grid; height: 100px; grid-template-columns: repeat(6, 1fr); grid-template-rows: 100px; } #item1 { background-color: lime; } #item2 { background-color: yellow; grid-column: 2 / 4; } #item3 { background-color: blue;...
grid-row-end - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...] | [ span && [ <integer> | <custom-ident> ] ]
examples setting row end for a grid item html <div class="wrapper"> <div class="box1">one</div> <div class="box2">two</div> <div class="box3">three</div> <div class="box4">four</div> <div class="box5">five</div> </div> css .wrapper { display: grid; grid-template-columns: repeat(3, 1fr); grid-auto-rows: 100px; } .box1 { grid-column-start: 1; grid-column-end: 4; grid-row-start: ...
grid-row-start - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...] | [ span && [ <integer> | <custom-ident> ] ]
examples setting row start for a grid item html <div class="wrapper"> <div class="box1">one</div> <div class="box2">two</div> <div class="box3">three</div> <div class="box4">four</div> <div class="box5">five</div> </div> css .wrapper { display: grid; grid-template-columns: repeat(3, 1fr); grid-auto-rows: 100px; } .box1 { grid-column-start: 1; grid-column-end: 4; grid-row-start...
grid-row - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...] | [ span && [ <integer> | <custom-ident> ] ]
examples setting grid row size and location html <div id="grid"> <div id="item1"></div> <div id="item2"></div> <div id="item3"></div> </div> css #grid { display: grid; height: 200px; grid-template-columns: 200px; grid-template-rows: repeat(6, 1fr); } #item1 { background-color: lime; } #item2 { background-color: yellow; grid-row: 2 / 4; } #item3 { background-color: blue; gri...
grid-template-areas - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... formal definition initial valuenoneapplies togrid containersinheritednocomputed valueas specifiedanimation typediscrete formal syntax none | <string>+
examples specifying named grid areas html <section id="page"> <header>header</header> <nav>navigation</nav> <main>main area</main> <footer>footer</footer> </section> css #page { display: grid; width: 100%; height: 250px; grid-template-areas: "head head" "nav main" "nav foot"; grid-template-rows: 50px 1fr 30px; grid-template-columns: ...
grid-template-columns - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...)where <track-breadth> = <length-percentage> | <flex> | min-content | max-content | auto<inflexible-breadth> = <length> | <percentage> | min-content | max-content | auto<fixed-breadth> = <length-percentage>where <length-percentage> = <length> | <percentage>
examples specifying grid column sizes html <div id="grid"> <div id="areaa">a</div> <div id="areab">b</div> </div> css #grid { display: grid; width: 100%; grid-template-columns: 50px 1fr; } #areaa { background-color: lime; } #areab { background-color: yellow; } result specifications specification status comment css grid layoutthe definition of 'grid-tem...
grid-template-rows - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...)where <track-breadth> = <length-percentage> | <flex> | min-content | max-content | auto<inflexible-breadth> = <length> | <percentage> | min-content | max-content | auto<fixed-breadth> = <length-percentage>where <length-percentage> = <length> | <percentage>
examples specifying grid row sizes html <div id="grid"> <div id="areaa">a</div> <div id="areab">b</div> </div> css #grid { display: grid; height: 100px; grid-template-rows: 30px 1fr; } #areaa { background-color: lime; } #areab { background-color: yellow; } result specifications specification status comment css grid layoutthe definition of 'grid-templat...
grid-template - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...<track-size> ]+ <line-names>?where <track-breadth> = <length-percentage> | <flex> | min-content | max-content | auto<inflexible-breadth> = <length> | <percentage> | min-content | max-content | autowhere <length-percentage> = <length> | <percentage>
examples defining a grid template css #page { display: grid; width: 100%; height: 200px; grid-template: [header-left] "head head" 30px [header-right] [main-left] "nav main" 1fr [main-right] [footer-left] "nav foot" 30px [footer-right] / 120px 1fr; } header { background-color: lime; grid-area: head; } nav { background-color: lightbl...
grid - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
.../ <'grid-template-columns'>
examples creating a grid layout html <div id="container"> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> </div> css #container { display: grid; grid: repeat(2, 60px) / auto-flow 80px; } #container > div { background-color: #8ca0ff; width: 50px; height: 50px; } result specifications specification status com...
height - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...a percentage height on the root element is relative to the initial containing block.computed valuea percentage or auto 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 height using pixels and percentages html <div id="taller">i'm 50 pixels tall.</div> <div id="shorter">i'm 25 pixels tall.</div> <div id="parent"> <div id="child"> i'm half the height of my parent.
hyphens - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... formal definition initial valuemanualapplies toall elementsinheritedyescomputed valueas specifiedanimation typediscrete formal syntax none | manual | auto
examples specifying text hyphenation this example uses three classes, one for each possible configuration of the hyphens property.
inline-size - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... formal definition initial valueautoapplies tosame as width and heightinheritednopercentagesinline-size of containing blockcomputed valuesame as width and heightanimation typea length, percentage or calc(); formal syntax <'width'>
examples setting inline size in pixels html <p class="exampletext">example text</p> css .exampletext { writing-mode: vertical-rl; background-color: yellow; inline-size: 110px; } result specifications specification status comment css logical properties and values level 1the definition of 'inline-size' in that specification.
isolation - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...in svg, it applies to container elements, graphics elements, and graphics referencing elements.inheritednocomputed valueas specifiedanimation typediscrete formal syntax auto | isolate
examples forcing a new stacking context for an element html <div id="b" class="a"> <div id="d"> <div class="a c">auto</div> </div> <div id="e"> <div class="a c">isolate</div> </div> </div> css .a { background-color: rgb(0,255,0); } #b { width: 200px; height: 210px; } .c { width: 100px; height: 100px; border: 1px solid black; padding: 2px; mix-blend-mode: difference; }...
justify-content - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...[ <content-position> | left | right ]where <content-distribution> = space-between | space-around | space-evenly | stretch<overflow-position> = unsafe | safe<content-position> = center | start | end | flex-start | flex-end
examples setting flex item distribution css #container { display: flex; justify-content: space-between; /* can be changed in the live sample */ } #container > div { width: 100px; height: 100px; background: linear-gradient(-45deg, #788cff, #b4c8ff); } html <div id="container"> <div></div> <div></div> <div></div> </div> <select id="justifycontent"> <option value="start">start</opti...
justify-items - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...baseline<overflow-position> = unsafe | safe<self-position> = center | start | end | self-start | self-end | flex-start | flex-end
examples simple demonstration in the following example we have a simple 2 x 2 grid layout.
justify-self - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...baseline<overflow-position> = unsafe | safe<self-position> = center | start | end | self-start | self-end | flex-start | flex-end
examples simple demonstration in the following example we have a simple 2 x 2 grid layout.
left - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... formal definition initial valueautoapplies topositioned elementsinheritednopercentagesrefer to the 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 positioning elements html <div id="wrap"> <div id="example_1"> <pre> position: absolute; left: 20px; top: 20px; </pre> <p>the only containing element for this div is the main window, so it positions itself in relation to it.</p> </div> <div id="example_2"> <pre> position: relative; top: 0; right: 0; </pre> <p>relative position ...
<length-percentage> - CSS: Cascading Style Sheets
examples length-percentage
examples the following simple example demonstrates several properties that use <length-percentage> values.
... html <p>you can use percentages and lengths in so many places.</p> css p { /* length-percentage
examples */ width: 75%; height: 200px; margin: 3rem; padding: 1%; border-radius: 10px 10%; font-size: 250%; line-height: 1.5em; /* length
examples */ text-shadow: 1px 1px 1px red; border: 5px solid red; letter-spacing: 3px; /* percentage example */ text-size-adjust: 20%; } result use in calc() where a <length-percentage> is specified as an allowable type, this means that the percentage resolves to a length and therefore can be used in a calc() expression.
letter-spacing - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...it also applies to ::first-letter and ::first-line.inheritedyescomputed valuean optimum value consisting of either an absolute length or the keyword normalanimation typea length formal syntax normal | <length>
examples setting letter spacing html <p class="normal">letter spacing</p> <p class="em-wide">letter spacing</p> <p class="em-wider">letter spacing</p> <p class="em-tight">letter spacing</p> <p class="px-wide">letter spacing</p> css .normal { letter-spacing: normal; } .em-wide { letter-spacing: 0.4em; } .em-wider { letter-spacing: 1em; } .em-tight { letter-spacing: -0.05em; } .px-wide { letter-sp...
line-height - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...it also applies to ::first-letter and ::first-line.inheritedyespercentagesrefer to the font size of the element itselfcomputed valuefor percentage and length values, the absolute length, otherwise as specifiedanimation typeeither number or length formal syntax normal | <number> | <length> | <percentage>
examples basic example /* all rules below have the same resultant line height */ div { line-height: 1.2; font-size: 10pt; } /* number/unitless */ div { line-height: 1.2em; font-size: 10pt; } /* length */ div { line-height: 120%; font-size: 10pt; } /* percentage */ div { font: 10pt/1.2 georgia,"bitstream charter",serif; } /* font shorthand */ it is often more convenient to set line-height by ...
list-style-image - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... formal definition initial valuenoneapplies tolist itemsinheritedyescomputed valuenone or the image with its uri made absoluteanimation typediscrete formal syntax <url> | none
examples setting list item images html <ul> <li>item 1</li> <li>item 2</li> </ul> css ul { list-style-image: url("https://mdn.mozillademos.org/files/11981/starsolid.gif"); } result specifications specification status comment css lists module level 3the definition of 'list-style-image' in that specification.
list-style-position - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... formal definition initial valueoutsideapplies tolist itemsinheritedyescomputed valueas specifiedanimation typediscrete formal syntax inside | outside
examples setting list item position html <ul class="inside">list 1 <li>list item 1-1</li> <li>list item 1-2</li> <li>list item 1-3</li> <li>list item 1-4</li> </ul> <ul class="outside">list 2 <li>list item 2-1</li> <li>list item 2-2</li> <li>list item 2-3</li> <li>list item 2-4</li> </ul> <ul class="inside-img">list 3 <li>list item 3-1</li> <li>list item 3-2</li> <li>list item 3-3...
list-style-type - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...d thoughts mdn understanding wcag, guideline 1.3 explanations understanding success criterion 1.3.1 | w3c understanding wcag 2.0 formal definition initial valuediscapplies tolist itemsinheritedyescomputed valueas specifiedanimation typediscrete formal syntax <counter-style> | <string> | nonewhere <counter-style> = <counter-style-name> | symbols()where <counter-style-name> = <custom-ident>
examples setting list item markers html list 1 <ol class="normal"> <li>hello</li> <li>world</li> <li>what's up?</li> </ol> list 2 <ol class="shortcut"> <li>looks</li> <li>like</li> <li>the</li> <li>same</li> </ol> css ol.normal { list-style-type: upper-alpha; } /* or use the shortcut "list-style": */ ol.shortcut { list-style: upper-alpha; } result specifications spe...
list-style - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...rthand: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 item c</li> </ul> css .one { list-style: circle; } .two { list-style: square inside; } result specifications specification status comment ...
margin-block-end - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... formal definition initial value0applies tosame as margininheritednopercentagesdepends on layout modelcomputed valueif specified as a length, the corresponding absolute length; if specified as a percentage, the specified value; otherwise, autoanimation typea length formal syntax <'margin-left'>
examples setting block end margin html <div> <p class="exampletext">example text</p> </div> css div { background-color: yellow; width: 120px; height: 120px; } .exampletext { writing-mode: vertical-rl; margin-block-end: 20px; background-color: #c8c800; } result specifications specification status comment css logical properties and values level 1the defi...
margin-block-start - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... formal definition initial value0applies tosame as margininheritednopercentagesdepends on layout modelcomputed valueif specified as a length, the corresponding absolute length; if specified as a percentage, the specified value; otherwise, autoanimation typea length formal syntax <'margin-left'>
examples setting block start margin html <div> <p class="exampletext">example text</p> </div> css div { background-color: yellow; width: 120px; height: 120px; } .exampletext { writing-mode: vertical-lr; margin-block-start: 20px; background-color: #c8c800; } result specifications specification status comment css logical properties and values level 1the ...
margin-bottom - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...it also applies to ::first-letter and ::first-line.inheritednopercentagesrefer to the width of the containing blockcomputed valuethe percentage as specified or the absolute lengthanimation typea length formal syntax <length> | <percentage> | auto
examples setting positive and negative bottom margins html <div class="container"> <div class="box0">box 0</div> <div class="box1">box 1</div> <div class="box2">box one's negative margin pulls me up</div> </div> css css for divs to set margin-bottom and height .box0 { margin-bottom:1em; height:3em; } .box1 { margin-bottom:-1.5em; height:4em; } .box2 { border:1px dashed black; ...
margin-inline-end - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... formal definition initial value0applies tosame as margininheritednopercentagesdepends on layout modelcomputed valueif specified as a length, the corresponding absolute length; if specified as a percentage, the specified value; otherwise, autoanimation typea length formal syntax <'margin-left'>
examples setting inline end margin html <div> <p class="exampletext">example text</p> </div> css div { background-color: yellow; width: 120px; height: 120px; } .exampletext { writing-mode: vertical-lr; margin-inline-end: 20px; background-color: #c8c800; } result specifications specification status comment css logical properties and values level 1the de...
margin-inline-start - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...formal definition initial value0applies tosame as margininheritednopercentagesdepends on layout modelcomputed valueif specified as a length, the corresponding absolute length; if specified as a percentage, the specified value; otherwise, autoanimation typea length formal syntax <'margin-left'>
examples setting inline start margin html <div> <p class="exampletext">example text</p> </div> css div { background-color: yellow; width: 120px; height: 120px; } .exampletext { writing-mode: vertical-lr; margin-inline-start: 20px; background-color: #c8c800; } result specifications specification status comment css logical properties and values level 1th...
margin-left - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...it also applies to ::first-letter and ::first-line.inheritednopercentagesrefer to the width of the containing blockcomputed valuethe percentage as specified or the absolute lengthanimation typea length formal syntax <length> | <percentage> | auto
examples setting left margin using pixels and percentages .content { margin-left: 5%; } .sidebox { margin-left: 10px; } .logo { margin-left: -5px; } specifications specification status comment css basic box modelthe definition of 'margin-left' in that specification.
margin-right - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...it also applies to ::first-letter and ::first-line.inheritednopercentagesrefer to the width of the containing blockcomputed valuethe percentage as specified or the absolute lengthanimation typea length formal syntax <length> | <percentage> | auto
examples setting right margin using pixels and percentages .content { margin-right: 5%; } .sidebox { margin-right: 10px; } .logo { margin-right: -5px; } specifications specification status comment css basic box modelthe definition of 'margin-right' in that specification.
margin-top - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...it also applies to ::first-letter and ::first-line.inheritednopercentagesrefer to the width of the containing blockcomputed valuethe percentage as specified or the absolute lengthanimation typea length formal syntax <length> | <percentage> | auto
examples setting positive and negative top margins .content { margin-top: 5%; } .sidebox { margin-top: 10px; } .logo { margin-top: -5px; } #footer { margin-top: 1em; } specifications specification status comment css basic box modelthe definition of 'margin-top' in that specification.
margin - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... formal syntax [ <length> | <percentage> | auto ]{1,4}
examples simple example html <div class="center">this element is centered.</div> <div class="outside">this element is positioned outside of its container.</div> css .center { margin: auto; background: lime; width: 66%; } .outside { margin: 3rem 0 0 -3rem; background: cyan; width: 66%; } more
examples margin: 5%; /* all sides: 5% margin */ margin: 10px; ...
max-block-size - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... formal definition initial value0applies tosame as width and heightinheritednopercentagesblock-size of containing blockcomputed valuesame as max-width and max-heightanimation typea length, percentage or calc(); formal syntax <'max-width'>
examples setting max-block-size with horizontal and vertical text in this example, the same text (the opening sentences from herman melville's novel moby-dick) is presented in both the horizontal-tb and vertical-rl writing modes.
max-height - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
..., 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 table { max-height: 75%; } form { max-height: none; } specifications specification status comment css box sizing module level 4the definition of 'max-height' in that specification.
max-inline-size - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... formal definition initial value0applies tosame as width and heightinheritednopercentagesinline-size of containing blockcomputed valuesame as max-width and max-heightanimation typea length, percentage or calc(); formal syntax <'max-width'>
examples setting max inline size in pixels html <p class="exampletext">example text</p> css .exampletext { writing-mode: vertical-rl; background-color: yellow; block-size: 100%; max-inline-size: 200px; } result specifications specification status comment css logical properties and values level 1the definition of 'max-inline-size' in that specification.
max-width - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...non-replaced inline elements, table rows, and row groupsinheritednopercentagesrefer to the width of the containing blockcomputed 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 width in pixels in this example, the "child" will be either 150 pixels wide or the width of the "parent," whichever is smaller.
max() - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... formal syntax max( <calc-sum># )where <calc-sum> = <calc-product> [ [ '+' | '-' ] <calc-product> ]*where <calc-product> = <calc-value> [ '*' <calc-value> | '/' <number> ]*where <calc-value> = <number> | <dimension> | <percentage> | ( <calc-sum> )
examples setting a minimum size for a font another use case for css functions is allow a font size to grow while ensuring it is at least a mimum size, enabling responsive font sizes while ensuring legibility.
min-block-size - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... formal definition initial value0applies tosame as width and heightinheritednopercentagesblock-size of containing blockcomputed valuesame as min-width and min-heightanimation typea length, percentage or calc(); formal syntax <'min-width'>
examples setting minimum block size for vertical text html <p class="exampletext">example text</p> css .exampletext { writing-mode: vertical-rl; background-color: yellow; min-block-size: 200px; } result specifications specification status comment css logical properties and values level 1the definition of 'min-block-size' in that specification.
min-height - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...citly (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: 0; } specifications specification status comment css box sizing module level 4the definition of 'min-height' in that specification.
min-inline-size - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... formal definition initial value0applies tosame as width and heightinheritednopercentagesinline-size of containing blockcomputed valuesame as min-width and min-heightanimation typea length, percentage or calc(); formal syntax <'min-width'>
examples setting minimum inline size for vertical text html <p class="exampletext">example text</p> css .exampletext { writing-mode: vertical-rl; background-color: yellow; block-size: 5%; min-inline-size: 200px; } result specifications specification status comment css logical properties and values level 1the definition of 'min-inline-size' in that specificati...
min-width - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...nts but non-replaced inline elements, table rows, and row groupsinheritednopercentagesrefer to the width of the containing blockcomputed 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 minimum element width table { min-width: 75%; } form { min-width: 0; } specifications specification status comment css box sizing module level 4the definition of 'min-width' in that specification.
min() - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... mdn understanding wcag, guideline 1.4 explanations understanding success criterion 1.4.4 | w3c understanding wcag 2.0
examples setting a maximum size for a label and input another use case for css functions is to set a maximum size on responsive form controls: enabling the width of labels and inputs to shrink as the width of the form shrinks.
minmax() - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... formal syntax minmax( [ <length> | <percentage> | min-content | max-content | auto ] , [ <length> | <percentage> | <flex> | min-content | max-content | auto ] ) css properties minmax() function can be used within: grid-template-columns grid-template-rows grid-auto-columns grid-auto-rows
examples css #container { display: grid; grid-template-columns: minmax(min-content, 300px) minmax(200px, 1fr) 150px; grid-gap: 5px; box-sizing: border-box; height: 200px; width: 100%; background-color: #8cffa0; padding: 10px; } #container > div { background-color: #8ca0ff; padding: 5px; } html <div id="container"> <div> item as wide as the content, but at most 300 pixels.
mix-blend-mode - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... formal definition initial valuenormalapplies toall elementsinheritednocomputed valueas specifiedanimation typediscretecreates stacking contextyes formal syntax <blend-mode>where <blend-mode> = normal | multiply | screen | overlay | darken | lighten | color-dodge | color-burn | hard-light | soft-light | difference | exclusion | hue | saturation | color | luminosity
examples effect of different mix-blend-mode values <div class="grid"> <div class="col"> <div class="note">blending in isolation (no blending with the background)</div> <div class="row isolate"> <div class="cell"> normal <div class="container normal"> <div class="group"> <div class="item firefox"></div> <svg viewbox="0 0 150 150"> <...
object-fit - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... formal definition initial valuefillapplies toreplaced elementsinheritednocomputed valueas specifiedanimation typediscrete formal syntax fill | contain | cover | none | scale-down
examples setting object-fit for an image html <section> <h2>object-fit: fill</h2> <img class="fill" src="https://udn.realityripple.com/samples/ae/248a9938d9.png" alt="mdn logo"> <img class="fill narrow" src="https://udn.realityripple.com/samples/ae/248a9938d9.png" alt="mdn logo"> <h2>object-fit: contain</h2> <img class="contain" src="https://udn.realityripple.com/samples/ae/248a9938d9.png" ...
object-position - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...| [ [ left | right ] <length-percentage> ] && [ [ top | bottom ] <length-percentage> ] ]where <length-percentage> = <length> | <percentage>
examples positioning image content html here we see html that includes two <img> elements, each displaying the mdn logo.
opacity - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... webaim: color contrast checker mdn understanding wcag, guideline 1.4 explanations understanding success criterion 1.4.3 | w3c understanding wcag 2.0 formal definition initial value1.0applies toall elementsinheritednocomputed valuethe specified value, clipped in the range [0,1]animation typea number formal syntax <alpha-value>where <alpha-value> = <number> | <percentage>
examples setting background opacity html <div class="light">you can barely see this.</div> <div class="medium">this is easier to see.</div> <div class="heavy">this is very easy to see.</div> css div { background-color: yellow; } .light { opacity: 0.2; /* barely see the text over the background */ } .medium { opacity: 0.5; /* see the text more clearly over the background */ } .heavy { opacity: 0...
order - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... & the 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.
outline-color - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...)where <alpha-value> = <number> | <percentage><hue> = <number> | <angle>
examples setting a solid blue outline html <p>my outline is blue, as you can see.</p> css p { outline: 2px solid; /* set the outline width and style */ outline-color: #0000ff; /* make the outline blue */ margin: 5px; } result specifications specification status comment css basic user interface module level 3the definition of 'outline-color' in that speci...
outline-offset - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... formal definition initial value0applies toall elementsinheritednocomputed valueas specified, but with relative lengths converted into absolute lengthsanimation typea length formal syntax <length>
examples setting outline offset in pixels html <p>gallia est omnis divisa in partes tres.</p> css p { outline: 1px dashed red; outline-offset: 10px; background: yellow; border: 1px solid blue; margin: 15px; } result specifications specification status comment css basic user interface module level 3the definition of 'outline-offset' in that specification.
outline-style - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... formal definition initial valuenoneapplies toall elementsinheritednocomputed valueas specifiedanimation typediscrete formal syntax auto | <'border-style'>
examples setting outline style to auto the auto value indicates a custom outline style — typically a style [that] is either a user interface default for the platform, or perhaps a style that is richer than can be described in detail in css, e.g.
outline-width - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... formal definition initial valuemediumapplies toall elementsinheritednocomputed valuean absolute length; if the keyword none is specified, the computed value is 0animation typea length formal syntax <line-width>where <line-width> = <length> | thin | medium | thick
examples setting an element's outline width html <span id="thin">thin</span> <span id="medium">medium</span> <span id="thick">thick</span> <span id="twopixels">2px</span> <span id="oneex">1ex</span> <span id="em">1.2em</span> css span { outline-style: solid; display: inline-block; margin: 20px; } #thin { outline-width: thin; } #medium { outline-width: medium; } #thick { outline-width:...
outline - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...the transparent keyword maps to rgba(0,0,0,0).outline-width: an absolute length; if the keyword none is specified, the computed value is 0outline-style: as specifiedanimation typeas each of the properties of the shorthand:outline-color: a coloroutline-width: a lengthoutline-style: discrete formal syntax [ <'outline-color'> | <'outline-style'> | <'outline-width'> ]
examples using outline to set a focus style html <a href="#">this link has a special focus style.</a> css a { border: 1px solid; border-radius: 3px; display: inline-block; margin: 10px; padding: 5px; } a:focus { outline: 4px dotted #e73; outline-offset: 4px; background: #ffa; } result specifications specification status comment css basic user interf...
overflow-wrap - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... formal definition initial valuenormalapplies tonon-replaced inline elementsinheritedyescomputed valueas specifiedanimation typediscrete formal syntax normal | break-word | anywhere
examples comparing overflow-wrap, word-break, and hyphens this example compares the results of overflow-wrap, word-break, and hyphens when breaking up a long word.
overflow-x - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... formal definition initial valuevisibleapplies toblock-containers, flex containers, and grid containersinheritednocomputed valueas specified, except with visible/clip computing to auto/hidden respectively if one of overflow-x or overflow-y is neither visible nor clipanimation typediscrete formal syntax visible | hidden | clip | scroll | auto
examples html <ul> <li><code>overflow-x:hidden</code> — hides the text outside the box <div id="div1"> abcdefghijklmopqrstuvwxyzabcdefghijklmopqrstuvwxyz </div> </li> <li><code>overflow-x:scroll</code> — always adds a scrollbar <div id="div2"> abcdefghijklmopqrstuvwxyzabcdefghijklmopqrstuvwxyz </div> </li> <li><code>overflow-x:visible</code> — displays the t...
overflow-y - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... formal definition initial valuevisibleapplies toblock-containers, flex containers, and grid containersinheritednocomputed valueas specified, except with visible/clip computing to auto/hidden respectively if one of overflow-x or overflow-y is neither visible nor clipanimation typediscrete formal syntax visible | hidden | clip | scroll | auto
examples setting overflow-y behavior html <ul> <li><code>overflow-y:hidden</code> — hides the text outside the box <div id="div1"> lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
overflow - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...horthand:overflow-x: as specified, except with visible/clip computing to auto/hidden respectively if one of overflow-x or overflow-y is neither visible nor clipoverflow-y: as specified, except with visible/clip computing to auto/hidden respectively if one of overflow-x or overflow-y is neither visible nor clipanimation typediscrete formal syntax [ visible | hidden | clip | scroll | auto ]{1,2}
examples setting different overflow values for text p { width: 12em; height: 6em; border: dotted; overflow: visible; /* content is not clipped */ } visible (default) sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium.
padding-block-end - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... formal definition initial value0applies toall elementsinheritednopercentageslogical-width of containing blockcomputed valueas <length>animation typea length formal syntax <'padding-left'>
examples setting block end padding for vertical text html content <div> <p class="exampletext">example text</p> </div> css content div { background-color: yellow; width: 120px; height: 120px; } .exampletext { writing-mode: vertical-lr; padding-block-end: 20px; background-color: #c8c800; } result specifications specification status comment css logical p...
padding-block-start - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... formal definition initial value0applies toall elementsinheritednopercentageslogical-width of containing blockcomputed valueas <length>animation typea length formal syntax <'padding-left'>
examples setting block start padding for vertical text html <div> <p class="exampletext">example text</p> </div> css div { background-color: yellow; width: 120px; height: 120px; } .exampletext { writing-mode: vertical-lr; padding-block-start: 20px; background-color: #c8c800; } result specifications specification status comment css logical properties an...
padding-bottom - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...it also applies to ::first-letter and ::first-line.inheritednopercentagesrefer to the width of the containing blockcomputed valuethe percentage as specified or the absolute lengthanimation typea length formal syntax <length> | <percentage>
examples setting padding bottom with pixels and percentages .content { padding-bottom: 5%; } .sidebox { padding-bottom: 10px; } specifications specification status comment css basic box modelthe definition of 'padding-bottom' in that specification.
padding-inline-end - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... formal definition initial value0applies toall elementsinheritednopercentageslogical-width of containing blockcomputed valueas <length>animation typea length formal syntax <'padding-left'>
examples setting inline end padding for vertical text html <div> <p class="exampletext">example text</p> </div> css div { background-color: yellow; width: 120px; height: 120px; } .exampletext { writing-mode: vertical-lr; padding-inline-end: 20px; background-color: #c8c800; } specifications specification status comment css logical properties and values l...
padding-inline-start - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... formal definition initial value0applies toall elementsinheritednopercentageslogical-width of containing blockcomputed valueas <length>animation typea length formal syntax <'padding-left'>
examples setting inline start padding for vertical text html <div> <p class="exampletext">example text</p> </div> css div { background-color: yellow; width: 120px; height: 120px; } .exampletext { writing-mode: vertical-lr; padding-inline-start: 20px; background-color: #c8c800; } specifications specification status comment css logical properties and valu...
padding-left - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...it also applies to ::first-letter and ::first-line.inheritednopercentagesrefer to the width of the containing blockcomputed valuethe percentage as specified or the absolute lengthanimation typea length formal syntax <length> | <percentage>
examples setting left padding using pixels and percentages .content { padding-left: 5%; } .sidebox { padding-left: 10px; } specifications specification status comment css basic box modelthe definition of 'padding-left' in that specification.
padding-right - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...it also applies to ::first-letter and ::first-line.inheritednopercentagesrefer to the width of the containing blockcomputed valuethe percentage as specified or the absolute lengthanimation typea length formal syntax <length> | <percentage>
examples setting right padding using pixels and percentages .content { padding-right: 5%; } .sidebox { padding-right: 10px; } specifications specification status comment css basic box modelthe definition of 'padding-right' in that specification.
padding-top - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...it also applies to ::first-letter and ::first-line.inheritednopercentagesrefer to the width of the containing blockcomputed valuethe percentage as specified or the absolute lengthanimation typea length formal syntax <length> | <percentage>
examples setting top padding using pixels and percentages .content { padding-top: 5%; } .sidebox { padding-top: 10px; } specifications specification status comment css basic box modelthe definition of 'padding-top' in that specification.
padding - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...aining blockcomputed valueas each of the properties of the shorthand:padding-bottom: the percentage as specified or the absolute lengthpadding-left: the percentage as specified or the absolute lengthpadding-right: the percentage as specified or the absolute lengthpadding-top: the percentage as specified or the absolute lengthanimation typea length formal syntax [ <length> | <percentage> ]{1,4}
examples setting padding with pixels html <h4>this element has moderate padding.</h4> <h3>the padding is huge in this element!</h3> css h4 { background-color: lime; padding: 20px 50px; } h3 { background-color: cyan; padding: 110px 50px 50px 110px; } result setting padding with pixels and percentages padding: 5%; /* all sides: 5% padding */ padding: 10px; /...
paint() - CSS: Cascading Style Sheets
parameters optional additional parameters to pass to the paintworklet
examples you can pass additional arguments via the css paint() function.
...> <li>item 5</li> <li>item 6</li> <li>item 7</li> <li>item 8</li> <li>item 9</li> <li>item 10</li> <li>item 11</li> <li>item 12</li> <li>item 13</li> <li>item 14</li> <li>item 15</li> <li>item 16</li> <li>item 17</li> <li>item 18</li> <li>item 19</li> <li>item 20</li> </ul> css.paintworklet.addmodule('https://mdn.github.io/houdini-
examples/csspaint/intro/worklets/hilite.js'); li { --boxcolor: hsla(55, 90%, 60%, 1.0); background-image: paint(hollowhighlights, stroke, 2px); } li:nth-of-type(3n) { --boxcolor: hsla(155, 90%, 60%, 1.0); background-image: paint(hollowhighlights, filled, 3px); } li:nth-of-type(3n+1) { --boxcolor: hsla(255, 90%, 60%, 1.0); background-image: paint(hollowhighlights, stroke, 1px); } we...
perspective-origin - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...| [ [ left | right ] <length-percentage> ] && [ [ top | bottom ] <length-percentage> ] ]where <length-percentage> = <length> | <percentage>
examples changing the perspective origin this example shows cubes with popular perspective-origin values.
perspective - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... formal definition initial valuenoneapplies totransformable elementsinheritednocomputed valuethe absolute length or noneanimation typea lengthcreates stacking contextyes formal syntax none | <length>
examples setting perspective this example shows a cube with the perspective set at different positions.
place-content - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples placing content in a flex container html <div id="container"> <div class="small">lorem</div> <div class="small">lorem<br/>ipsum</div> <div class="large">lorem</div> <div class="large">lorem<br/>impsum</div> <div class="large"></div> <div class="large"></div> </div> <code>writing-mode:</code><select id="writingmode"> <option value="horizontal-tb" selected>horizontal-tb</option>...
place-items - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples placing items in a flex container div > div { box-sizing: border-box; border: 2px solid #8c8c8c; width: 50px; display: flex; align-items: center; justify-content: center; } #item1 { background-color: #8cffa0; min-height: 30px; } #item2 { background-color: #a0c8ff; min-height: 50px; } #item3 { background-color: #ffa08c; min-height: 40px; } #item4 { background-color...
place-self - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples simple demonstration in the following example we have a simple 2 x 2 grid layout.
pointer-events - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... formal definition initial valueautoapplies toall elementsinheritedyescomputed valueas specifiedanimation typediscrete formal syntax auto | none | visiblepainted | visiblefill | visiblestroke | visible | painted | fill | stroke | all | inherit
examples disabling pointer events on all images this example disables pointer events (clicking, dragging, hovering, etc.) on all images.
position - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... formal definition initial valuestaticapplies toall elementsinheritednocomputed valueas specifiedanimation typediscretecreates stacking contextyes formal syntax static | relative | absolute | sticky | fixed
examples relative positioning relatively positioned elements are offset a given amount from their normal position within the document, but without the offset affecting other elements.
quotes - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... formal definition initial valuedepends on user agentapplies toall elementsinheritedyescomputed valueas specifiedanimation typediscrete formal syntax none | auto | [ <string> <string> ]+
examples basic quote marks html <q>to be or not to be.
resize - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... to the following: inline elements block elements for which the overflow property is set to visible formal definition initial valuenoneapplies toelements with overflow other than visible, and optionally replaced elements representing images or videos, and iframesinheritednocomputed valueas specifiedanimation typediscrete formal syntax none | both | horizontal | vertical | block | inline
examples disabling resizability of textareas in many browsers, <textarea> elements are resizable by default.
right - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... formal definition initial valueautoapplies topositioned elementsinheritednopercentagesrefer to the 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; righ...
row-gap (grid-row-gap) - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...applies tomulti-column elements, flex containers, grid containersinheritednopercentagesrefer to corresponding dimension of the content areacomputed valueas specified, with <length>s made absolute, and normal computing to zero except on multi-column elementsanimation typea length, percentage or calc(); formal syntax normal | <length-percentage>where <length-percentage> = <length> | <percentage>
examples flex layout html <div id="flexbox"> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> </div> css #flexbox { display: flex; flex-wrap: wrap; width: 300px; row-gap: 20px; } #flexbox > div { border: 1px solid green; background-color: lime; flex: 1 1 auto; width: 100px; height: 50px; } result grid layout html <div id="grid"> <div>...
scroll-behavior - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... formal definition initial valueautoapplies toscrolling boxesinheritednocomputed valueas specifiedanimation typediscrete formal syntax auto | smooth
examples setting smooth scroll behavior html <nav> <a href="#page-1">1</a> <a href="#page-2">2</a> <a href="#page-3">3</a> </nav> <scroll-container> <scroll-page id="page-1">1</scroll-page> <scroll-page id="page-2">2</scroll-page> <scroll-page id="page-3">3</scroll-page> </scroll-container> css a { display: inline-block; width: 50px; text-decoration: none; } nav, scroll-container { ...
scroll-margin-inline-end - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... formal definition initial value0applies toall elementsinheritednocomputed valueas specifiedanimation typeby computed value type formal syntax <length>
examples simple demonstration this example implements something very similar to the interactive example above, except that here we'll explain to you how it's implemented.
scroll-margin-inline-start - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... formal definition initial value0applies toall elementsinheritednocomputed valueas specifiedanimation typeby computed value type formal syntax <length>
examples simple demonstration this example implements something very similar to the interactive example above, except that here we'll explain to you how it's implemented.
scroll-margin - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... formal definition initial value0applies toall elementsinheritednocomputed valueas specifiedanimation typeby computed value type formal syntax <length>{1,4}
examples simple demonstration this example implements something very similar to the interactive example above, except that here we'll explain to you how it's implemented.
scroll-snap-type - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples snapping in different axes html <div class="holster"> <div class="container x mandatory-scroll-snapping" dir="ltr"> <div>x mand.
shape-image-threshold - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... formal definition initial value0.0applies tofloatsinheritednocomputed valuethe same as the specified value after clipping the <number> to the range [0.0, 1.0].animation typea number formal syntax <alpha-value>where <alpha-value> = <number> | <percentage>
examples aligning text to a gradient this example creates a <div> block with a gradient background image.
shape-margin - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... formal definition initial value0applies tofloatsinheritednopercentagesrefer to the width of the containing blockcomputed valueas specified, but with relative lengths converted into absolute lengthsanimation typea length, percentage or calc(); formal syntax <length-percentage>where <length-percentage> = <length> | <percentage>
examples adding a margin to a polygon html <section> <div class="shape"></div> we are not quite sure of any one thing in biology; our knowledge of geology is relatively very slight, and the economic laws of society are uncertain to every one except some individual who attempts to set them forth; but before the world was fashioned the square on the hypotenuse was equal to the sum of the squares on the o...
shape-outside - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...op>where <alpha-value> = <number> | <percentage><hue> = <number> | <angle><linear-color-stop> = <color> <color-stop-length>?<linear-color-hint> = <length-percentage><angular-color-stop> = <color> && <color-stop-angle>?<angular-color-hint> = <angle-percentage>where <color-stop-length> = <length-percentage>{1,2}<color-stop-angle> = <angle-percentage>{1,2}<angle-percentage> = <angle> | <percentage>
examples funneling text html <div class="main"> <div class="left"></div> <div class="right"></div> <p> sometimes a web page's text content appears to be funneling your attention towards a spot on the page to drive you to follow a particular link.
table-layout - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... formal definition initial valueautoapplies totable and inline-table elementsinheritednocomputed valueas specifiedanimation typediscrete formal syntax auto | fixed
examples fixed-width tables with text-overflow this example uses a fixed table layout, combined with the width property, to restrict the table's width.
text-align-last - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... formal definition initial valueautoapplies toblock containersinheritedyescomputed valueas specifiedanimation typediscrete formal syntax auto | start | end | left | right | center | justify
examples justifying the last line <p>integer elementum massa at nulla placerat varius.
text-align - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...f direction is ltr, right if direction is rtl if start is not supported by the browser.applies toblock containersinheritedyescomputed valueas specified, except for the match-parent value which is calculated against its parent's direction value and results in a computed value of either left or rightanimation typediscrete formal syntax start | end | left | right | center | justify | match-parent
examples left alignment html <p class="example"> integer elementum massa at nulla placerat varius.
text-decoration-color - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...)where <alpha-value> = <number> | <percentage><hue> = <number> | <angle>
examples <p>this paragraph has <s>some erroneous text</s> inside it that i want to call attention to.</p> p { text-decoration-line: underline; text-decoration-color: cyan; } s { text-decoration-line: line-through; text-decoration-color: red; text-decoration-style: wavy; } specifications specification status comment css text decoration module level 3the defi...
text-decoration-line - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...it also applies to ::first-letter and ::first-line.inheritednocomputed valueas specifiedanimation typediscrete formal syntax none | [ underline | overline | line-through | blink ] | spelling-error | grammar-error
examples <p class="wavy">here's some text with wavy red underline!</p> <p class="both">this text has lines both above and below it.</p> .wavy { text-decoration-line: underline; text-decoration-style: wavy; text-decoration-color: red; } .both { text-decoration-line: underline overline; } specifications specification status comment css text decoration module level ...
text-decoration-skip-ink - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... formal definition initial valueautoapplies toall elementsinheritedyescomputed valueas specifiedanimation typediscrete formal syntax auto | all | none
examples html <p>you should go on a quest for a cup of coffee.</p> <p class="no-skip-ink">or maybe you'd prefer some tea?</p> <p>この文は、 text-decoration-skip-ink: auto の使用例を示しています。</p> <p class="skip-ink-all">この文は、 text-decoration-skip-ink: all の使用例を示しています。</p> css p { font-size: 1.5em; text-decoration: underline blue; text-decor...
text-decoration-style - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...it also applies to ::first-letter and ::first-line.inheritednocomputed valueas specifiedanimation typediscrete formal syntax solid | double | dotted | dashed | wavy
examples setting a wavy underline .example { -moz-text-decoration-line: underline; -moz-text-decoration-style: wavy; -moz-text-decoration-color: red; -webkit-text-decoration-line: underline; -webkit-text-decoration-style: wavy; -webkit-text-decoration-color: red; } css .wavy { text-decoration-line: underline; text-decoration-style: wavy; text-decoration-color: re...
text-decoration - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...-decoration-color: computed colortext-decoration-thickness: as specifiedanimation typeas each of the properties of the shorthand:text-decoration-color: a colortext-decoration-style: discretetext-decoration-line: discretetext-decoration-thickness: by computed value type formal syntax <'text-decoration-line'> | <'text-decoration-style'> | <'text-decoration-color'> | <'text-decoration-thickness'>
examples .under { text-decoration: underline red; } .over { text-decoration: wavy overline lime; } .line { text-decoration: line-through; } .plain { text-decoration: none; } .underover { text-decoration: dashed underline overline; } .thick { text-decoration: solid underline purple 4px; } .blink { text-decoration: blink; } <p class="under">this text has a line underneath it.</p> <p c...
text-emphasis - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...:text-emphasis-style: nonetext-emphasis-color: currentcolorapplies toall elementsinheritednocomputed valueas each of the properties of the shorthand:text-emphasis-style: as specifiedtext-emphasis-color: computed coloranimation typeas each of the properties of the shorthand:text-emphasis-color: a colortext-emphasis-style: discrete formal syntax <'text-emphasis-style'> | <'text-emphasis-color'>
examples a heading with emphasis shape and color this example draws a heading with triangles used to emphasize each character.
text-indent - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...&& each-line?where <length-percentage> = <length> | <percentage>
examples simple indent html <p>lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.</p> <p>lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.</p> css p { text-indent: 5em; background: powderblue; } resul...
text-orientation - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... formal definition initial valuemixedapplies toall elements, except table row groups, rows, column groups, and columnsinheritedyescomputed valueas specifiedanimation typediscrete formal syntax mixed | upright | sideways
examples html <p>lorem ipsum dolet semper quisquam.</p> css p { writing-mode: vertical-rl; text-orientation: upright; } result specifications specification status comment css writing modes module level 3the definition of 'text-orientation' in that specification.
text-overflow - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... formal definition initial valueclipapplies toblock container elementsinheritednocomputed valueas specifiedanimation typediscrete formal syntax [ clip | ellipsis | <string> ]{1,2}
examples css p { width: 200px; border: 1px solid; padding: 2px 5px; /* both of the following are required for text-overflow */ white-space: nowrap; overflow: hidden; } .overflow-visible { white-space: initial; } .overflow-clip { text-overflow: clip; } .overflow-ellipsis { text-overflow: ellipsis; } .overflow-string { /* not supported in most browsers, see the 'browser compa...
text-shadow - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...)where <alpha-value> = <number> | <percentage><hue> = <number> | <angle>
examples simple shadow .red-text-shadow { text-shadow: red 0 -2px; } <p class="red-text-shadow">sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore.</p> multiple shadows .white-text-with-blue-shadow { text-shadow: 1px 1px 2px black, 0 0 1em blue, 0 0 0.2em blue; color: white; font: ...
text-transform - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...it also applies to ::first-letter and ::first-line.inheritedyescomputed valueas specifiedanimation typediscrete formal syntax none | capitalize | uppercase | lowercase | full-width | full-size-kana
examples none <p>initial string <strong>lorem ipsum dolor sit amet, consectetur adipisicing elit, ...</strong> </p> <p>text-transform: none <strong><span>lorem ipsum dolor sit amet, consectetur adipisicing elit, ...</span></strong> </p> span { text-transform: none; } strong { float: right; } this demonstrates no text transformation.
text-underline-position - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... formal definition initial valueautoapplies toall elementsinheritedyescomputed valueas specifiedanimation typediscrete formal syntax auto | from-font | [ under | [ left | right ] ]
examples a simple example let's take a couple of simple example paragraphs: <p class="horizontal">lorem ipsum dolor sit amet, consectetur adipiscing elit.
top - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... formal definition initial valueautoapplies topositioned elementsinheritednopercentagesrefer to the height 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 body { background: beige; } div { position: absolute; top: 10%; right: 40%; bottom: 20%; left: 15%; background: gold; border: 1px solid blue; } <div>the size of this content is determined by the position of its edges.</div> specifications specification status comment css positioned layout module level 3the definition of 'top' in that specificatio...
perspective() - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... 10000100001000−1/d1
examples html <p>without perspective:</p> <div class="no-perspective-box"> <div class="face front">a</div> <div class="face top">b</div> <div class="face left">c</div> </div> <p>with perspective (9cm):</p> <div class="perspective-box-far"> <div class="face front">a</div> <div class="face top">b</div> <div class="face left">c</div> </div> <p>with perspective (4cm):</p> <div class="perspecti...
rotate3d() - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... homogeneous coordinates on ℝℙ2 cartesian coordinates on ℝ3 1+(1-cos(a))(x2-1)z·sin(a)+xy(1-cos(a))-y·sin(a)+xz·(1-cos(a))-z·sin(a)+xy·(1-cos(a))1+(1-cos(a))(y2-1)x·sin(a)+yz·(1-cos(a))ysin(a) + xz(1-cos(a))-xsin(a)+yz(1-cos(a))1+(1-cos(a))(z2-1)t0001 homogeneous coordinates on ℝℙ3
examples rotating on the y-axis html <div>normal</div> <div class="rotated">rotated</div> css body { perspective: 800px; } div { width: 80px; height: 80px; background-color: skyblue; } .rotated { transform: rotate3d(0, 1, 0, 60deg); background-color: pink; } result rotating on a custom axis html <div>normal</div> <div class="rotated">rotated</div> css body { perspective: 800p...
rotateX() - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... 1000cos(a)-sin(a)0sin(a)cos(a) 10000cos(a)-sin(a)00sin(a)cos(a)00001
examples html <div>normal</div> <div class="rotated">rotated</div> css div { width: 80px; height: 80px; background-color: skyblue; } .rotated { transform: rotatex(45deg); background-color: pink; } result specifications specification status comment css transforms level 2the definition of 'rotatex()' in that specification.
rotateY() - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... cos(a)0sin(a)010-sin(a)0cos(a) cos(a)0sin(a)00100-sin(a)0cos(a)00001
examples html <div>normal</div> <div class="rotated">rotated</div> css div { width: 80px; height: 80px; background-color: skyblue; } .rotated { transform: rotatey(60deg); background-color: pink; } result specifications specification status comment css transforms level 2the definition of 'rotatey()' in that specification.
rotateZ() - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... cos(a)-sin(a)0sin(a)cos(a)0001 cos(a)-sin(a)00 sin(a)cos(a)00 0010 0001
examples html <div>normal</div> <div class="rotated">rotated</div> css div { width: 80px; height: 80px; background-color: skyblue; } .rotated { transform: rotatez(45deg); background-color: pink; } result specifications specification status comment css transforms level 2the definition of 'rotatez()' in that specification.
scale3d() - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... sx000sy000sz sx0000sy0000sz00001
examples without changing the origin html <div>normal</div> <div class="scaled">scaled</div> css div { width: 80px; height: 80px; background-color: skyblue; } .scaled { transform: perspective(500px) scale3d(2, 0.7, 0.2) translatez(100px); background-color: pink; } result translating the origin of the transformation html <div>normal</div> <div class="scaled">scaled</div> css div { ...
skew() - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... cartesian coordinates on ℝ2 homogeneous coordinates on ℝℙ2 cartesian coordinates on ℝ3 homogeneous coordinates on ℝℙ3 1tan(ax)tan(ay)1 1tan(ax)0tan(ay)10001 1tan(ax)0tan(ay)10001 1tan(ax)00tan(ay)10000100001 [1 tan(ay) tan(ax) 1 0 0]
examples using a single x-angle html <div>normal</div> <div class="skewed">skewed</div> css div { width: 80px; height: 80px; background-color: skyblue; } .skewed { transform: skew(10deg); /* equal to skewx(10deg) */ background-color: pink; } result using two angles html <div>normal</div> <div class="skewed">skewed</div> css div { width: 80px; height: 80px; background-color: ...
skewX() - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... cartesian coordinates on ℝ2 homogeneous coordinates on ℝℙ2 cartesian coordinates on ℝ3 homogeneous coordinates on ℝℙ3 1tan(a)01 1tan(a)0010001 1tan(a)0010001 1tan(a)00010000100001 [1 0 tan(a) 1 0 0]
examples html <div>normal</div> <div class="skewed">skewed</div> css div { width: 80px; height: 80px; background-color: skyblue; } .skewed { transform: skewx(10deg); /* equal to skew(10deg) */ background-color: pink; } result specifications specification status comment css transforms level 1the definition of 'skewx()' in that specification.
skewY() - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... cartesian coordinates on ℝ2 homogeneous coordinates on ℝℙ2 cartesian coordinates on ℝ3 homogeneous coordinates on ℝℙ3 10tan(a)1 100tan(a)10001 100tan(a)10001 1000tan(a)10000100001 [1 tan(a) 0 1 0 0]
examples html <div>normal</div> <div class="skewed">skewed</div> css div { width: 80px; height: 80px; background-color: skyblue; } .skewed { transform: skewy(40deg); background-color: pink; } result specifications specification status comment css transforms level 1the definition of 'skewy()' in that specification.
translate3d() - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... 100tx010ty001tz0001
examples using a single axis translation html <div>static</div> <div class="moved">moved</div> <div>static</div> css div { width: 60px; height: 60px; background-color: skyblue; } .moved { /* equivalent to perspective(500px) translatex(10px) */ transform: perspective(500px) translate3d(10px, 0, 0px); background-color: pink; } result combining z-axis and x-axis translation html <div...
transform-origin - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... to the size of bounding boxcomputed valuefor <length> the absolute value, otherwise a percentageanimation typesimple list of length, percentage, or calc formal syntax [ <length-percentage> | left | center | right | top | bottom ] | [ [ <length-percentage> | left | center | right ] && [ <length-percentage> | top | center | bottom ] ] <length>?where <length-percentage> = <length> | <percentage>
examples code sample transform: none; <div class="box1"> </div> .box1 { margin: 0.5em; width: 3em; height: 3em; border: solid 1px; background-color: palegreen; transform: none; -webkit-transform: none; } transform: rotate(30deg); <div class="box2"> </div> .box2 { margin: 0.5em; width: 3em; ...
transform-style - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... formal definition initial valueflatapplies totransformable elementsinheritednocomputed valueas specifiedanimation typediscretecreates stacking contextyes formal syntax flat | preserve-3d
examples transform style demonstration in this example we have a 3d cube created using transforms.
transform - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...th> )<scale3d()> = scale3d( <number> , <number> , <number> )<scalez()> = scalez( <number> )<rotate3d()> = rotate3d( <number> , <number> , <number> , [ <angle> | <zero> ] )<rotatex()> = rotatex( [ <angle> | <zero> ] )<rotatey()> = rotatey( [ <angle> | <zero> ] )<rotatez()> = rotatez( [ <angle> | <zero> ] )<perspective()> = perspective( <length> )where <length-percentage> = <length> | <percentage>
examples translating and rotating an element html <div>transformed element</div> css div { border: solid red; transform: translate(30px, 20px) rotate(20deg); width: 140px; height: 60px; } result more
examples please see using css transforms and <transform-function> for more
examples.
transition-delay - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... formal definition initial value0sapplies toall elements, ::before and ::after pseudo-elementsinheritednocomputed valueas specifiedanimation typediscrete formal syntax <time>#
examples transition-delay: 0.5s <div class="parent"> <div class="box">lorem</div> </div> .parent { width: 250px; height:125px;} .box { width: 100px; height: 100px; background-color: red; font-size: 20px; left: 0px; top: 0px; position:absolute; -webkit-transition-property: width height background-color font-size left top color; -webkit-transition-duration:2s;...
transition-duration - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... formal definition initial value0sapplies toall elements, ::before and ::after pseudo-elementsinheritednocomputed valueas specifiedanimation typediscrete formal syntax <time>#
examples transition-duration: 0.5s <div class="parent"> <div class="box">lorem</div> </div> .parent { width: 250px; height:125px;} .box { width: 100px; height: 100px; background-color: red; font-size: 20px; left: 0px; top: 0px; position:absolute; -webkit-transition-property: width height background-color font-size left top transform -webkit-transform color; ...
transition-property - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... formal definition initial valueallapplies toall elements, ::before and ::after pseudo-elementsinheritednocomputed valueas specifiedanimation typediscrete formal syntax none | <single-transition-property>#where <single-transition-property> = all | <custom-ident>
examples there are several
examples of css transitions included in the main css transitions article.
transition - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... a single component">[0,1]>, <number>, <number <a href="/docs/css/value_definition_syntax#brackets" title="brackets: enclose several entities, combinators, and multipliers to transform them as a single component">[0,1]>, <number>)<step-timing-function> = step-start | step-end | steps(<integer>[, <step-position>]?)where <step-position> = jump-start | jump-end | jump-none | jump-both | start | end
examples there are several more
examples of css transitions included in the using css transitions article.
var() - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples :root { --main-bg-color: pink; } body { background-color: var(--main-bg-color); } /* fallback */ /* in the component’s style: */ .component .header { color: var(--header-color, blue); /* header-color isn’t set, and so remains blue, the fallback value */ } .component .text { color: var(--text-color, black); } /* in the larger application’s style: */ .component { --text-color:...
vertical-align - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...it also applies to ::first-letter and ::first-line.inheritednopercentagesrefer to the line-height of the element itselfcomputed valuefor percentage and length values, the absolute length, otherwise the keyword as specifiedanimation typea length formal syntax baseline | sub | super | text-top | text-bottom | middle | top | bottom | <percentage> | <length>
examples basic example html <div>an <img src="https://udn.realityripple.com/samples/b4/e1f0faff5b.svg" alt="link" width="32" height="32" /> image with a default alignment.</div> <div>an <img class="top" src="https://udn.realityripple.com/samples/b4/e1f0faff5b.svg" alt="link" width="32" height="32" /> image with a text-top alignment.</div> <div>an <img class="bottom" src="https://udn.realityripple.com/s...
visibility - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... formal definition initial valuevisibleapplies toall elementsinheritedyescomputed valueas specifiedanimation typea visibility formal syntax visible | hidden | collapse
examples basic example html <p class="visible">the first paragraph is visible.</p> <p class="not-visible">the second paragraph is not visible.</p> <p class="visible">the third paragraph is visible.
white-space - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...rap preserve pre-wrap preserve preserve wrap hang pre-line preserve collapse wrap remove break-spaces preserve preserve wrap wrap formal definition initial valuenormalapplies toall elementsinheritedyescomputed valueas specifiedanimation typediscrete formal syntax normal | pre | nowrap | pre-wrap | pre-line | break-spaces
examples basic example code { white-space: pre; } line breaks inside <pre> elements pre { word-wrap: break-word; /* ie 5.5-7 */ white-space: pre-wrap; /* modern browsers */ } in action html <div id="css-code" class="box"> p { white-space: <select> <option>normal</option> <option>nowrap</option> <option>pre</option> <option>pre-wrap</option> <option>pre-line<...
width - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...l elements but non-replaced inline elements, table rows, and row groupsinheritednopercentagesrefer to the width of the containing blockcomputed valuea percentage or auto 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 default width p.goldie { background: gold; } <p class="goldie">the mozilla community produces a lot of great software.</p> pixels and ems .px_length { width: 200px; background-color: red; color: white; border: 1px solid black; } .em_length { width: 20em; background-color: white; color: red; border: 1px solid black; } <div class="px_length">width measured in px</div> <d...
word-break - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... formal definition initial valuenormalapplies toall elementsinheritedyescomputed valueas specifiedanimation typediscrete formal syntax normal | break-all | keep-all | break-word
examples html <p>1.
word-spacing - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples html <div id="mozdiv1">here are many words...</div> <div id="mozdiv2">...and many more!</div> css #mozdiv1 { word-spacing: 15px; } #mozdiv2 { word-spacing: 5em; } accessibility concerns a large positive or negative word-spacing value will make the sentences the styling is applied to unreadable.
writing-mode - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... formal definition initial valuehorizontal-tbapplies toall elements except table row groups, table column groups, table rows, and table columnsinheritedyescomputed valueas specifiedanimation typediscrete formal syntax horizontal-tb | vertical-rl | vertical-lr | sideways-rl | sideways-lr
examples using multiple writing modes this example demonstrates all of the writing modes, showing each with text in various languages.
z-index - CSS: Cascading Style Sheets
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... formal definition initial valueautoapplies topositioned elementsinheritednocomputed valueas specifiedanimation typean integercreates stacking contextyes formal syntax auto | <integer>
examples visually layering elements html <div class="dashed-box">dashed box <span class="gold-box">gold box</span> <span class="green-box">green box</span> </div> css .dashed-box { position: relative; z-index: 1; border: dashed; height: 8em; margin-bottom: 1em; margin-top: 2em; } .gold-box { position: absolute; z-index: 3; /* put .gold-box above .green-box and .dashed-box */ ba...
Audio and Video Delivery - Developer guides
a few
examples: http://example.com/video.ogv#t=10,20 specifies that the video should play the range 10 seconds through 20 seconds.
... h.264 support in firefox this article explains the state of support for the h.264 video format in firefox/firefox os, including code
examples, tips and tricks.
Printing - Developer guides
examples here are some common
examples.
...you can also try changing the code to use <code>beforeprint</code> to see the difference.</p> <p><a href="javascript: popuponclick()">open popup window</a></p> </body> </html> view live
examples print an external page without opening it if you want to be able to print an external page without opening it, you can utilize a hidden <iframe> (see: htmliframeelement), automatically removing it after the user prints its contents.
The HTML autocomplete attribute - HTML: Hypertext Markup Language
examples <div> <label for="cc-number">enter your credit card number</label> <input name="cc-number" id="cc-number" autocomplete="off"> </div> administrative levels in addresses the four administrative level fields (address-level1 through address-level4) describe the address in terms of increasing levels of precision within the country in which the address is located.
...below are some
examples; this is not meant to be an exhaustive list.
disabled - HTML: Hypertext Markup Language
examples when form controls are disabled, many browsers will display them in a lighter, greyed-out color by default.
... here are
examples of a disabled checkbox, radio button, <option> and <optgroup>, as well as some form controls that are disabled via the disabled attribute set on the ancestor <fieldset> element.
<a>: The Anchor element - HTML: Hypertext Markup Language
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...when href attribute is present, otherwise no corresponding role permitted aria roles when href attribute is present: button checkbox menuitem menuitemcheckbox menuitemradio option radio switch tab treeitem when href attribute is not present: any dom interface htmlanchorelement
examples linking to an absolute url html <a href="https://www.mozilla.com"> mozilla </a> result linking to relative urls html <a href="//example.com">scheme-relative url</a> <a href="/docs/web/html">origin-relative url</a> <a href="./p">directory-relative url</a> css a { display: block; margin-bottom: 0.5em } result linking to an element on the same page <!-- <a> element links to the ...
<abbr>: The Abbreviation element - HTML: Hypertext Markup Language
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples marking up an abbreviation semantically to mark up an abbreviation without providing an expansion or description, simply use <abbr> without any attributes, as seen in this example.
<area> - HTML: Hypertext Markup Language
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...(the w3c 5.3 fork of the html specification defines it as valid, but the canonical html specification doesn’t, and it has no effect in any user agents.)
examples <map name="primary"> <area shape="circle" coords="75,75,75" href="left.html" alt="click to go left"> <area shape="circle" coords="275,75,75" href="right.html" alt="click to go right"> </map> <img usemap="#primary" src="https://udn.realityripple.com/samples/6a/7e559101b3.png" alt="350 x 150 pic"> result specifications specification status comment referrer poli...
<aside>: The Aside element - HTML: Hypertext Markup Language
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using <aside> this example uses <aside> to mark up a paragraph in an article.
<bdo>: The Bidirectional Text Override element - HTML: Hypertext Markup Language
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples <!-- switch text direction --> <p>this text will go left to right.</p> <p><bdo dir="rtl">this text will go right to left.</bdo></p> result notes the html 4 specification did not specify events for this element; they were added in xhtml.
<br>: The Line Break element - HTML: Hypertext Markup Language
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples simple br in the following example we use <br> elements to create line breaks between the different lines of a postal address: mozilla<br> 331 e.
<col> - HTML: Hypertext Markup Language
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples please see the <table> page for
examples on <col>.
<colgroup> - HTML: Hypertext Markup Language
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples please see the <table> page for
examples on <colgroup>.
<data> - HTML: Hypertext Markup Language
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples the following example displays product names but also associates each name with a product number.
<datalist>: The HTML Data List element - HTML: Hypertext Markup Language
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples <label for="mybrowser">choose a browser from this list:</label> <input list="browsers" id="mybrowser" name="mybrowser" /> <datalist id="browsers"> <option value="chrome"> <option value="firefox"> <option value="internet explorer"> <option value="opera"> <option value="safari"> <option value="microsoft edge"> </datalist> result specifications specification status ...
<del>: The Deleted Text element - HTML: Hypertext Markup Language
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples <p><del>this text has been deleted</del>, here is the rest of the paragraph.</p> <del><p>this paragraph has been deleted.</p></del> result accessibility concerns the presence of the del element is not announced by most screen reading technology in its default configuration.
<details>: The Details disclosure element - HTML: Hypertext Markup Language
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... you can use an event listener for the toggle event to detect when the widget changes state: details.addeventlistener("toggle", event => { if (details.open) { /* the element was toggled open */ } else { /* the element was toggled closed */ } });
examples a simple disclosure example this example shows a <details> element with no provided summary.
<embed>: The Embed External Content element - HTML: Hypertext Markup Language
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples <embed type="video/quicktime" src="movie.mov" width="640" height="480" title="title of my video"> accessibility concerns use the title attribute on an embed element to label its content so that people navigating with assistive technology such as a screen reader can understand what it contains.
<fieldset>: The Field Set element - HTML: Hypertext Markup Language
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples simple fieldset this example shows a really simple <fieldset> example, with a <legend>, and a single control inside it.
<figure>: The Figure with Optional Caption element - HTML: Hypertext Markup Language
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples images <!-- just an image --> <figure> <img src="https://udn.realityripple.com/samples/6c/98485e5d8a.png" alt="the beautiful mdn logo."> </figure> <!-- image with a caption --> <figure> <img src="https://udn.realityripple.com/samples/6c/98485e5d8a.png" alt="the beautiful mdn logo."> <figcaption>mdn logo</figcaption> </figure> code snippets <figure> <figcaption>get browser ...
<footer> - HTML: Hypertext Markup Language
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples <footer> some copyright info or perhaps some author info for an <article>?
<form> - HTML: Hypertext Markup Language
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples html <!-- form which will send a get request to the current url --> <form> <label>name: <input name="submitted-name" autocomplete="name"> </label> <button>save</button> </form> <!-- form which will send a post request to the current url --> <form method="post"> <label>name: <input name="submitted-name" autocomplete="name"> </label> <button>save</button> </form> <!-- form w...
<header> - HTML: Hypertext Markup Language
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples page header <header> <h1>main page title</h1> <img src="mdn-logo-sm.png" alt="mdn logo"> </header> article header <article> <header> <h2>the planet earth</h2> <p>posted on wednesday, <time datetime="2017-10-04">4 october 2017</time> by jane smith</p> </header> <p>we live on a planet that's blue and green, with so many things still unseen.</p> <p><a href="https://janesmith...
<hgroup> - HTML: Hypertext Markup Language
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples <hgroup id="document-title"> <h1>html</h1> <h2>living standard — last updated 12 august 2016</h2> </hgroup> specifications specification status comment html living standardthe definition of '<hgroup>' in that specification.
<input type="button"> - HTML: Hypertext Markup Language
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples the below example shows a very simple drawing app created using a <canvas> element and some simple css and javascript (we'll hide the css for brevity).
<input type="date"> - HTML: Hypertext Markup Language
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples in this example, we create 2 sets of ui elements for choosing dates: a native <input type="date"> picker and a set of 3 <select> elements for older browsers that don't support the native date input.
<input type="datetime-local"> - HTML: Hypertext Markup Language
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples in this example we create two sets of ui elements for choosing datetimes — a native <input type="datetime-local"> picker, and a set of five <select> elements for choosing dates and times in older browsers that don't support the native input.
<input type="image"> - HTML: Hypertext Markup Language
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples a login form the following example shows the same button as before, but included in the context of a typical login form.
<input type="month"> - HTML: Hypertext Markup Language
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples in this example, we create two sets of ui elements, each designed to let the user select a month and year.
<input type="number"> - HTML: Hypertext Markup Language
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples we've already covered the fact that by default, the increment is 1, and you can use the step attribute to allow decimal inputs.
<input type="password"> - HTML: Hypertext Markup Language
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples requesting a social security number this example only accepts input which matches the format for a valid united states social security number.
<input type="radio"> - HTML: Hypertext Markup Language
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... providing a bigger hit area for your radio buttons in the above
examples, you may have noticed that you can select a radio button by clicking on its associated <label> element, as well as on the radio button itself.
<input type="text"> - HTML: Hypertext Markup Language
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...iv> <div> <button>submit</button> </div> </form> div { margin-bottom: 10px; position: relative; } p { font-size: 80%; color: #999; } input + span { padding-right: 30px; } input:invalid+span:after { position: absolute; content: '✖'; padding-left: 5px; } input:valid+span:after { position: absolute; content: '✓'; padding-left: 5px; } this renders like so:
examples you can see good
examples of text inputs used in context in our your first html form and how to structure an html form articles.
<input type="time"> - HTML: Hypertext Markup Language
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples in this example, we create two sets of interface elements for choosing times: a native picker created with <input type="time">, and a set of two <select> elements for choosing hours/minutes in older browsers that don't support the native input.
<input type="url"> - HTML: Hypertext Markup Language
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples there's not much else to say about url type inputs; check the pattern validation and using url inputs sections for numerous
examples.
<input type="week"> - HTML: Hypertext Markup Language
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples in this example we create two sets of ui elements for choosing weeks: a native picker created using <input type="week">, and a set of two <select> elements for choosing weeks/years in older browsers that don't support the week input type.
<ins> - HTML: Hypertext Markup Language
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples <ins>this text has been inserted</ins> result accessibility concerns the presence of the <ins> element is not announced by most screen reading technology in its default configuration.
<kbd>: The Keyboard Input element - HTML: Hypertext Markup Language
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples basic example <p>use the command <kbd>help mycommand</kbd> to view documentation for the command "mycommand".</p> representing keystrokes within an input to describe an input comprised of multiple keystrokes, you can nest multiple <kbd> elements, with an outer <kbd> element representing the overall input and each individual keystroke or component of the input enclosed within its own <kbd>.
<label> - HTML: Hypertext Markup Language
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples simple label example <label>click me <input type="text"></label> using the "for" attribute <label for="username">click me</label> <input type="text" id="username"> accessibility concerns interactive content don't place interactive elements such as anchors or buttons inside a label.
<legend> - HTML: Hypertext Markup Language
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples see <form> for
examples on <legend>.
<li> - HTML: Hypertext Markup Language
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples for more detailed
examples, see the <ol> and <ul> pages.
<map> - HTML: Hypertext Markup Language
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples <map name="primary"> <area shape="circle" coords="75,75,75" href="left.html"> <area shape="circle" coords="275,75,75" href="right.html"> </map> <img usemap="#primary" src="https://udn.realityripple.com/samples/6a/7e559101b3.png" alt="350 x 150 pic"> result expected live example output the live example above should appear similar to the following images (when using your keyboard tab key...
<mark>: The Mark Text element - HTML: Hypertext Markup Language
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples marking text of interest in this first example, a <mark> element is used to mark some text within a quote which is of particular interest to the user.
<meter>: The HTML Meter element - HTML: Hypertext Markup Language
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples simple example html <p>heat the oven to <meter min="200" max="500" value="350">350 degrees</meter>.</p> result on google chrome, the resulting meter looks like this: high and low range example note that in this example the min attribute is omitted.
<object> - HTML: Hypertext Markup Language
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...no percentages)
examples embed a flash movie <!-- embed a flash movie --> <object data="movie.swf" type="application/x-shockwave-flash"></object> <!-- embed a flash movie with parameters --> <object data="movie.swf" type="application/x-shockwave-flash"> <param name="foo" value="bar"> </object> specifications specification status comment html living standardthe definition of '<object>...
<ol>: The Ordered List element - HTML: Hypertext Markup Language
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples simple example <ol> <li>fee</li> <li>fi</li> <li>fo</li> <li>fum</li> </ol> the above html will output: using roman numeral type <ol type="i"> <li>introduction</li> <li>list of greivances</li> <li>conclusion</li> </ol> the above html will output: using the start attribute <p>finishing places of contestants not in the winners’ circle:</p> <ol start="4"> <li>speedwa...
<optgroup> - HTML: Hypertext Markup Language
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples <select> <optgroup label="group 1"> <option>option 1.1</option> </optgroup> <optgroup label="group 2"> <option>option 2.1</option> <option>option 2.2</option> </optgroup> <optgroup label="group 3" disabled> <option>option 3.1</option> <option>option 3.2</option> <option>option 3.3</option> </optgroup> </select> result specifications specificatio...
<picture>: The Picture element - HTML: Hypertext Markup Language
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples these
examples demonstrate how different attributes of the <source> element change the selection of the image inside <picture>.
<progress>: The Progress Indicator element - HTML: Hypertext Markup Language
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples <progress value="70" max="100">70 %</progress> result on windows 7, the resulting progress looks like this: specifications specification status comment html living standardthe definition of '<progress>' in that specification.
<rtc>: The Ruby Text Container element - HTML: Hypertext Markup Language
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples <div class="info"> <ruby> <rbc> <rb>旧</rb><rt>jiù</rt> <rb>金</rb><rt>jīn</rt> <rb>山</rb><rt>shān</rt> </rbc> <rtc>san francisco</rtc> </ruby> </div> .info { padding-top: 10px; font-size: 36px; } specifications specification status comment html 5.2the definition of '<rtc>' in that specification.
<ruby> - HTML: Hypertext Markup Language
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples example 1: character <ruby> 漢 <rp>(</rp><rt>kan</rt><rp>)</rp> 字 <rp>(</rp><rt>ji</rt><rp>)</rp> </ruby> example 2: word <ruby> 明日 <rp>(</rp><rt>ashita</rt><rp>)</rp> </ruby> specifications specification status comment html living standardthe definition of '<ruby>' in that specification.
<s> - HTML: Hypertext Markup Language
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples <s>today's special: salmon</s> sold out<br> <span style="text-decoration:line-through;">today's special: salmon</span> sold out accessibility concerns the presence of the s element is not announced by most screen reading technology in its default configuration.
<strong>: The Strong Importance element - HTML: Hypertext Markup Language
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples basic example <p>before proceeding, <strong>make sure you put on your safety goggles</strong>.</p> the resulting output: labeling warnings <p><strong>important:</strong> before proceeding, make sure you add plenty of butter.</p> this results in: specifications specification status comment html living standardthe definition of '<strong>' in that specificatio...
<style>: The Style Information element - HTML: Hypertext Markup Language
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples a simple stylesheet in the following example, we apply a very simple stylesheet to a document: <!doctype html> <html> <head> <style> p { color: red; } </style> </head> <body> <p>this is my paragraph.</p> </body> </html> multiple style elements in this example we've included two <style> elements — notice how the conflicting declarations in the later <style> element ove...
<sub>: The Subscript element - HTML: Hypertext Markup Language
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples footnote numbers traditional footnotes are denoted using numbers which are rendered in subscript.
<table>: The Table element - HTML: Hypertext Markup Language
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples simple table <table> <tr> <td>john</td> <td>doe</td> </tr> <tr> <td>jane</td> <td>doe</td> </tr> </table> more
examples <p>simple table with header</p> <table> <tr> <th>first name</th> <th>last name</th> </tr> <tr> <td>john</td> <td>doe</td> </tr> <tr> <td>jane</td> <td>doe</td> </tr> </table> <p>table with thead, tfoot, and tbod...
<textarea> - HTML: Hypertext Markup Language
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...for example, to give your textarea a different border depending on whether it is valid or invalid: textarea:invalid { border: 2px dashed red; } textarea:valid { border: 2px solid lime; }
examples basic example the following example show a very simple textarea, with a set numbers of rows and columns and some default content.
<th> - HTML: Hypertext Markup Language
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples see <table> for
examples on <th>.
<time> - HTML: Hypertext Markup Language
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...ng 2011-w47 a valid time string 14:54 14:54:39 14:54:39.929 a valid local date and time string 2011-11-18t14:54:39.929 2011-11-18 14:54:39.929 a valid global date and time string 2011-11-18t14:54:39.929z 2011-11-18t14:54:39.929-0400 2011-11-18t14:54:39.929-04:00 2011-11-18 14:54:39.929z 2011-11-18 14:54:39.929-0400 2011-11-18 14:54:39.929-04:00 a valid duration string pt4h18m3s
examples simple example html <p>the concert starts at <time datetime="2018-07-07t20:00:00">20:00</time>.</p> output datetime example html <p>the concert took place on <time datetime="2001-05-15t19:00">may 15</time>.</p> output specifications specification status comment html living standardthe definition of '<time>' in that specification.
<track>: The Embed Text Track element - HTML: Hypertext Markup Language
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... 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"> <source src="sample.mp4" type="video/mp4"> <source src="sample.ogv" type="video/ogv"> <track kind="captions" src="samplecaptions.vtt" srclang="en"> <track kind="descriptions" src="sampledescriptions.vtt" srclang="en"> <track kind="chapters" src="samplechapters.vtt" srclang="en"> <track kind="subtitles" src="samplesubtitles_de.vt...
<ul>: The Unordered List element - HTML: Hypertext Markup Language
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples simple example <ul> <li>first item</li> <li>second item</li> <li>third item</li> </ul> the above html will output: nesting a list <ul> <li>first item</li> <li>second item <!-- look, the closing </li> tag is not placed here!
<var>: The Variable element - HTML: Hypertext Markup Language
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...this can be overridden in css, like this: var { font: bold 15px "courier", "courier new", monospace; }
examples basic example here's a simple example, using <var> to denote variable names in a mathematical equation.
HTML: Hypertext Markup Language
html tutorials for articles about how to use html, as well as tutorials and complete
examples, check out our html learning area.
...includes
examples, links to palette-building tools, and more.
Content Security Policy (CSP) - HTTP
this article explains how to construct such headers properly, and provides
examples.
...
examples: common use cases this section provides
examples of some common security policy scenarios.
Feature Policy - HTTP
examples of what you can do with feature policy: change the default behavior of autoplay on mobile and third party videos.
... the features include (see features list): accelerometer ambient light sensor autoplay camera encrypted media fullscreen geolocation gyroscope magnetometer microphone midi paymentrequest picture-in-picture usb vr / xr
examples using feature policy see feature policy demos for example usage of many policies.
CSP: base-uri - HTTP
examples: http://*.example.com: matches all attempts to load from any subdomain of example.com using the http: url scheme.
...
examples meta tag configuration <meta http-equiv="content-security-policy" content="base-uri 'self'"> apache configuration <ifmodule mod_headers.c> header set content-security-policy "base-uri 'self'"; </ifmodule> nginx configuration add_header content-security-policy "base-uri 'self';" violation case since your domain isn't example.com, a <base> element with its href set to https://example.com wi...
CSP: child-src - HTTP
examples: http://*.example.com: matches all attempts to load from any subdomain of example.com using the http: url scheme.
...
examples violation cases given this csp header: content-security-policy: child-src https://example.com/ this <iframe> and worker are blocked and won't load: <iframe src="https://not-example.com"></iframe> <script> var blockedworker = new worker("data:application/javascript,..."); </script> specifications specification status comment content security policy level 3the defi...
CSP: connect-src - HTTP
examples: http://*.example.com: matches all attempts to load from any subdomain of example.com using the http: url scheme.
...
examples violation cases given this csp header: content-security-policy: connect-src https://example.com/ the following connections are blocked and won't load: <a ping="https://not-example.com"> <script> var xhr = new xmlhttprequest(); xhr.open('get', 'https://not-example.com/'); xhr.send(); var ws = new websocket("https://not-example.com/"); var es = new eventsource("https://not-example...
CSP: default-src - HTTP
examples: http://*.example.com: matches all attempts to load from any subdomain of example.com using the http: url scheme.
...
examples no inheritance with default-src if there are other directives specified, default-src does not influence them.
CSP: font-src - HTTP
examples: http://*.example.com: matches all attempts to load from any subdomain of example.com using the http: url scheme.
...
examples violation cases given this csp header: content-security-policy: font-src https://example.com/ the following font resource loading is blocked and won't load: <style> @font-face { font-family: "myfont"; src: url("https://not-example.com/font"); } body { font-family: "myfont"; } </style> specifications specification status comment content security p...
CSP: form-action - HTTP
examples: http://*.example.com: matches all attempts to load from any subdomain of example.com using the http: url scheme.
...
examples meta tag configuration <meta http-equiv="content-security-policy" content="form-action 'none'"> apache configuration <ifmodule mod_headers.c> header set content-security-policy "form-action 'none'; </ifmodule> nginx configuration add_header content-security-policy "form-action 'none';" violation case using a <form> element with an action set to inline javascript will result in a csp viola...
CSP: frame-ancestors - HTTP
examples: http://*.example.com: matches all attempts to load from any subdomain of example.com using the http: url scheme.
...
examples content-security-policy: frame-ancestors 'none'; content-security-policy: frame-ancestors 'self' https://www.example.org; specifications specification status comment content security policy level 3the definition of 'frame-ancestors' in that specification.
CSP: frame-src - HTTP
examples: http://*.example.com: matches all attempts to load from any subdomain of example.com using the http: url scheme.
...
examples violation cases given this csp header: content-security-policy: frame-src https://example.com/ the following <iframe> is blocked and won't load: <iframe src="https://not-example.com/"></iframe> specifications specification status comment content security policy level 3the definition of 'frame-src' in that specification.
CSP: img-src - HTTP
examples: http://*.example.com: matches all attempts to load from any subdomain of example.com using the http: url scheme.
...
examples violation cases given this csp header: content-security-policy: img-src https://example.com/ the following <img> is blocked and won't load: <img src="https://not-example.com/foo.jpg" alt="example picture"> specifications specification status comment content security policy level 3the definition of 'img-src' in that specification.
CSP: manifest-src - HTTP
examples: http://*.example.com: matches all attempts to load from any subdomain of example.com using the http: url scheme.
...
examples violation cases given this csp header: content-security-policy: manifest-src https://example.com/ the following <link> is blocked and won't load: <link rel="manifest" href="https://not-example.com/manifest"> specifications specification status comment content security policy level 3the definition of 'manifest-src' in that specification.
CSP: media-src - HTTP
examples: http://*.example.com: matches all attempts to load from any subdomain of example.com using the http: url scheme.
...
examples violation cases given this csp header: content-security-policy: media-src https://example.com/ the following <audio>, <video> and <track> elements are blocked and won't load: <audio src="https://not-example.com/audio"></audio> <video src="https://not-example.com/video"> <track kind="subtitles" src="https://not-example.com/subtitles"> </video> specifications specification sta...
CSP: navigate-to - HTTP
examples: http://*.example.com: matches all attempts to load from any subdomain of example.com using the http: url scheme.
...
examples meta tag configuration <meta http-equiv="content-security-policy" content="navigate-to 'none'"> violation case using a <form> element with an action set to inline javascript will result in a csp violation.
CSP: object-src - HTTP
examples: http://*.example.com: matches all attempts to load from any subdomain of example.com using the http: url scheme.
...
examples violation cases given this csp header: content-security-policy: object-src https://example.com/ the following <object>, <embed>, and <applet> elements are blocked and won't load: <embed src="https://not-example.com/flash"></embed> <object data="https://not-example.com/plugin"></object> <applet archive="https://not-example.com/java"></applet> specifications specification status ...
CSP: script-src - HTTP
examples: http://*.example.com: matches all attempts to load from any subdomain of example.com using the http: url scheme.
...
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.getelementb...
CSP: style-src-attr - HTTP
examples: http://*.example.com: matches all attempts to load from any subdomain of example.com using the http: url scheme.
...
examples todo: add
examples specifications specification status comment content security policy level 3the definition of 'style-src-attr' in that specification.
CSP: style-src-elem - HTTP
examples: http://*.example.com: matches all attempts to load from any subdomain of example.com using the http: url scheme.
...
examples todo: add
examples specifications specification status comment content security policy level 3the definition of 'style-src-elem' in that specification.
CSP: style-src - HTTP
examples: http://*.example.com: matches all attempts to load from any subdomain of example.com using the http: url scheme.
...
examples violation cases given this csp header: content-security-policy: style-src https://example.com/ the following stylesheets are blocked and won't load: <link href="https://not-example.com/styles/main.css" rel="stylesheet" type="text/css" /> <style> #inline-style { background: red; } </style> <style> @import url("https://not-example.com/styles/print.css") print; </style> as well as styles l...
CSP: worker-src - HTTP
examples: http://*.example.com: matches all attempts to load from any subdomain of example.com using the http: url scheme.
...
examples violation cases given this csp header: content-security-policy: worker-src https://example.com/ worker, sharedworker, serviceworker are blocked and won't load: <script> var blockedworker = new worker("data:application/javascript,..."); blockedworker = new sharedworker("https://not-example.com/"); navigator.serviceworker.register('https://not-example.com/sw.js'); </script> specificatio...
Content-Security-Policy - HTTP
content-security-policy: default-src 'self' http://example.com; connect-src 'none'; content-security-policy: connect-src http://example.com/; script-src http://example.com/
examples example: disable unsafe inline/eval, only allow loading of resources (images, fonts, scripts, etc.) over https: // header content-security-policy: default-src https: // meta tag <meta http-equiv="content-security-policy" content="default-src https:"> example: pre-existing site that uses too much inline code to fix but wants to ensure resources are loaded only over https and to disable plugin...
...s: content-security-policy: default-src https: 'unsafe-eval' 'unsafe-inline'; object-src 'none' example: do not implement the above policy yet; instead just report violations that would have occurred: content-security-policy-report-only: default-src https:; report-uri /csp-violation-report-endpoint/ see mozilla web security guidelines for more
examples.
Upgrade - HTTP
more detail and
examples are provided in the topic protocol upgrade mechanism.
...
examples connection: upgrade upgrade: http/2.0, shttp/1.3, irc/6.9, rta/x11 connection: upgrade upgrade: websocket specifications specification hypertext transfer protocol (http/1.1): message syntax and routing (http/1.1)# header.upgrade hypertext transfer protocol (http/1.1): semantics and content (http/1.1)# status.426 hypertext transfer protocol version 2 (http/2) (http/2)# informationa...
X-Frame-Options - HTTP
examples note: setting x-frame-options inside the <meta> element is useless!
... x-frame-options works only by setting through the http header, as in the
examples below.
Closures - JavaScript
in previous
examples, each closure had its own lexical environment.
...the following example instead appends to the existing prototype: function myobject(name, message) { this.name = name.tostring(); this.message = message.tostring(); } myobject.prototype.getname = function() { return this.name; }; myobject.prototype.getmessage = function() { return this.message; }; in the two previous
examples, the inherited prototype can be shared by all objects and the method definitions need not occur at every object creation.
Keyed collections - JavaScript
see also the map reference page for more
examples and the complete api.
...see also the set reference page for more
examples and the complete api.
Meta programming - JavaScript
additional
examples are available on the proxy reference page.
...see the reference pages for detailed explanations and
examples.
Assertions - JavaScript
examples: /\bm/ matches the "m" in "moon".
...
examples general boundary-type overview example // using regex boundaries to fix buggy string.
Character classes - JavaScript
examples looking for a series of digits var randomdata = "015 354 8787 687351 3512 8735"; var regexpfourdigits = /\b\d{4}\b/g; // \b indicates a boundary (i.e.
... var nonenglishtext = "Приключения Алисы в Стране чудес"; var regexpbmpword = /([\u0000-\u0019\u0021-\uffff])+/gu; // bmp goes through u+0000 to u+ffff but space is u+0020 console.table(nonenglishtext.match(regexpbmpword)); [ 'Приключения', 'Алисы', 'в', 'Стране', 'чудес' ] note for mdn editors: please do not try to add funny
examples with emoji as those characters are not handled by the platform (kuma).
Unicode property escapes - JavaScript
note: as there are many properties and values available, we will not describe them exhaustively here but rather provide various
examples rationale before es2018 there was no performance-efficient way to match characters from different sets based on scripts (like macedonian, greek, georgian etc.) or propertyname (like emoji etc) in javascript.
...
examples general categories general categories are used to classify unicode characters and subcategories are available to define a more precise categorization.
Regular expressions - JavaScript
the following pages provide lists of the different special characters that fit into each category, along with descriptions and
examples.
...
examples note: several
examples are also available in: the reference pages for exec(), test(), match(), matchall(), search(), replace(), split() this guide articles': character classes, assertions, groups and ranges, quantifiers, unicode property escapes using special characters to verify input in the following example, the user is expected to enter a phone number.
constructor - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using the constructor method this code snippet is taken from the classes sample (live demo).
extends - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using extends the first example creates a class called square from a class called polygon.
static - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...}
examples using static in classes the following example demonstrates several things: how a static method is implemented on a class.
TypeError: can't access property "x" of "y" - JavaScript
message typeerror: unable to get property {x} of undefined or null reference (edge) typeerror: can't access property {x} of {y} (firefox) typeerror: {y} is undefined, can't access property {x} of it (firefox) typeerror: {y} is null, can't access property {x} of it (firefox)
examples: typeerror: x is undefined, can't access property "prop" of it typeerror: x is null, can't access property "prop" of it typeerror: can't access property "prop" of undefined typeerror: can't access property "prop" of null error type typeerror.
...
examples invalid cases // undefined and null cases on which the substring method won't work var foo = undefined; foo.substring(1); // typeerror: x is undefined, can't access property "substring" of it var foo = null; foo.substring(1); // typeerror: x is null, can't access property "substring" of it fixing the issue to fix null pointer to undefined or null values, you can use the typeof operator, for example.
SyntaxError: illegal character - JavaScript
examples mismatched characters some characters look similar, but will cause the parser to fail interpreting your code.
... famous
examples of this are quotes, the minus or semicolon (greek questionmark (u+37e) looks same).
TypeError: "x" is (not) "y" - JavaScript
message typeerror: unable to get property {x} of undefined or null reference (edge) typeerror: "x" is (not) "y" (firefox)
examples: typeerror: "x" is undefined typeerror: "x" is null typeerror: "undefined" is not an object typeerror: "x" is not an object or null typeerror: "x" is not a symbol error type typeerror.
...
examples invalid cases // undefined and null cases on which the substring method won't work var foo = undefined; foo.substring(1); // typeerror: foo is undefined var foo = null; foo.substring(1); // typeerror: foo is null // certain methods might require a specific type var foo = {} symbol.keyfor(foo); // typeerror: foo is not a symbol var foo = 'bar' object.create(foo); // typeerror: "foo" is not an object or null fixing the issue to fix null pointer to undefined values, you can use the typeof operator, for example.
Default parameters - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...now, you can assign 1 as the default value for b in the function head: function multiply(a, b = 1) { return a * b } multiply(5, 2) // 10 multiply(5) // 5 multiply(5, undefined) // 5
examples passing undefined vs.
Method definitions - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... const obja = { method() {} } new obja.method // typeerror: obj.method is not a constructor const objb = { * g() {} } new objb.g // typeerror: obj.g is not a constructor (changed in es2016)
examples simple test case const obj = { a: 'foo', b() { return this.a } }; console.log(obj.b()) // "foo" computed property names the shorthand syntax also supports computed property names.
The arguments object - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples defining a function that concatenates several strings this example defines a function that concatenates several strings.
getter - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples defining a getter on new objects in object initializers this will create a pseudo-property latest for object obj, which will return the last array item in log.
Rest parameters - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... // -- or -- let normalarray = array.from(arguments) let first = normalarray.shift() // ok, gives the first argument let first = arguments.shift() // error (arguments is not a normal array) } // now, you can easily gain access to a normal array using a rest parameter function f(...args) { let normalarray = args let first = normalarray.shift() // ok, gives the first argument }
examples using rest parameters in this example, the first argument is mapped to a and the second to b, so these named arguments are used as normal.
setter - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... ( { set x(v) { }, set x(v) { } } and { x: ..., set x(v) { } } are forbidden )
examples defining a setter on new objects in object initializers the following example define a pseudo-property current of object language.
Array.prototype.reduce() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples sum all the values of an array let sum = [0, 1, 2, 3].reduce(function (accumulator, currentvalue) { return accumulator + currentvalue }, 0) // sum is 6 alternatively written with an arrow function: let total = [ 0, 1, 2, 3 ].reduce( ( accumulator, currentvalue ) => accumulator + currentvalue, 0 ) sum of values in an object array to sum up, the values contained in an array of objects...
Array.prototype.reduceRight() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...alue; if (arguments.length >= 2) { value = arguments[1]; } else { while (k >= 0 && !(k in t)) { k--; } if (k < 0) { throw new typeerror('reduce of empty array with no initial value'); } value = t[k--]; } for (; k >= 0; k--) { if (k in t) { value = callback(value, t[k], k, t); } } return value; }; }
examples sum up all values within an array var sum = [0, 1, 2, 3].reduceright(function(a, b) { return a + b; }); // sum is 6 flatten an array of arrays var flattened = [[0, 1], [2, 3], [4, 5]].reduceright(function(a, b) { return a.concat(b); }, []); // flattened is [4, 5, 2, 3, 0, 1] run a list of asynchronous functions with callbacks in series each passing their results to the next const w...
Array.prototype.concat() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples concatenating two arrays the following code concatenates two arrays: const letters = ['a', 'b', 'c']; const numbers = [1, 2, 3]; letters.concat(numbers); // result in ['a', 'b', 'c', 1, 2, 3] concatenating three arrays the following code concatenates three arrays: const num1 = [1, 2, 3]; const num2 = [4, 5, 6]; const num3 = [7, 8, 9]; const numbers = num1.concat(num2, num3); console.log...
Array.prototype.copyWithin() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... return o; }, configurable: true, writable: true }); }
examples using copywithin [1, 2, 3, 4, 5].copywithin(-2) // [1, 2, 3, 1, 2] [1, 2, 3, 4, 5].copywithin(0, 3) // [4, 5, 3, 4, 5] [1, 2, 3, 4, 5].copywithin(0, 3, 4) // [4, 2, 3, 4, 5] [1, 2, 3, 4, 5].copywithin(-2, -3, -1) // [1, 2, 3, 3, 4] [].copywithin.call({length: 5, 3: 1}, 0, 3) // {0: 1, 3: 1, length: 5} // es2015 typed arrays are subclasses of array var i32a = new int32array([1, 2, 3, 4, 5])...
Array.prototype.entries() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples iterating with index and element const a = ['a', 'b', 'c']; for (const [index, element] of a.entries()) console.log(index, element); // 0 'a' // 1 'b' // 2 'c' using a for…of loop var a = ['a', 'b', 'c']; var iterator = a.entries(); for (let e of iterator) { console.log(e); } // [0, 'a'] // [1, 'b'] // [2, 'c'] specifications specification ecmascript (ecma-262)the definition of 'array.prototype.entries' in that specification.
Array.prototype.fill() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using fill [1, 2, 3].fill(4) // [4, 4, 4] [1, 2, 3].fill(4, 1) // [1, 4, 4] [1, 2, 3].fill(4, 1, 2) // [1, 4, 3] [1, 2, 3].fill(4, 1, 1) // [1, 2, 3] [1, 2, 3].fill(4, 3, 3) // [1, 2, 3] [1, 2, 3].fill(4, -3, -2) // [4, 2, 3] [1, 2, 3].fill(4, nan, nan) // [1, 2, 3] [1, 2, 3].fill(4, 3, 5) // [1, 2, 3] array(3).fill(4) ...
Array.prototype.findIndex() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples find the index of a prime number in an array the following example returns the index of the first element in the array that is a prime number, or -1 if there is no prime number.
Array.prototype.flat() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...for reference, please check: https://discourse.mozilla.org/t/mdn-rfc-001-mdn-wiki-pages-shouldnt-be-a-distributor-of-polyfills/24500
examples flattening nested arrays const arr1 = [1, 2, [3, 4]]; arr1.flat(); // [1, 2, 3, 4] const arr2 = [1, 2, [3, 4, [5, 6]]]; arr2.flat(); // [1, 2, 3, 4, [5, 6]] const arr3 = [1, 2, [3, 4, [5, 6]]]; arr3.flat(2); // [1, 2, 3, 4, 5, 6] const arr4 = [1, 2, [3, 4, [5, 6, [7, 8, [9, 10]]]]]; arr4.flat(infinity); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] flattening and array holes the flat method removes ...
Array.prototype.flatMap() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...for reference, please check: https://discourse.mozilla.org/t/mdn-rfc-001-mdn-wiki-pages-shouldnt-be-a-distributor-of-polyfills/24500
examples map() and flatmap() let arr1 = [1, 2, 3, 4]; arr1.map(x => [x * 2]); // [[2], [4], [6], [8]] arr1.flatmap(x => [x * 2]); // [2, 4, 6, 8] // only one level is flattened arr1.flatmap(x => [[x * 2]]); // [[2], [4], [6], [8]] while the above could have been achieved by using map itself, here is an example that better showcases the use of flatmap.
Array.prototype.forEach() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... example code let ratings = [5, 4, 5]; let sum = 0; let sumfunction = async function (a, b) { return a + b } ratings.foreach(async function(rating) { sum = await sumfunction(sum, rating) }) console.log(sum) // naively expected output: 14 // actual output: 0
examples no operation for uninitialized values (sparse arrays) const arraysparse = [1,3,,7] let numcallbackruns = 0 arraysparse.foreach((element) => { console.log(element) numcallbackruns++ }) console.log("numcallbackruns: ", numcallbackruns) // 1 // 3 // 7 // numcallbackruns: 3 // comment: as you can see the missing value between 3 and 7 didn't invoke callback function.
Array.from() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...object(new c(len)) : new array(len); return getarray( t, a, len, setgetitemhandler(isiterator, items), isiterator, mapfn ); }; })(); }
examples array from a string array.from('foo'); // [ "f", "o", "o" ] array from a set const set = new set(['foo', 'bar', 'baz', 'foo']); array.from(set); // [ "foo", "bar", "baz" ] array from a map const map = new map([[1, 2], [2, 4], [4, 8]]); array.from(map); // [[1, 2], [2, 4], [4, 8]] const mapper = new map([['1', 'a'], ['2', 'b']]); array.from(mapper.values()); // ['a', 'b']; array.from(mappe...
Array.prototype.includes() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples [1, 2, 3].includes(2) // true [1, 2, 3].includes(4) // false [1, 2, 3].includes(3, 3) // false [1, 2, 3].includes(3, -1) // true [1, 2, nan].includes(nan) // true fromindex is greater than or equal to the array length if fromindex is greater than or equal to the length of the array, false is returned.
Array.prototype.indexOf() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... if (k in o && o[k] === searchelement) return k; } return -1; }; }
examples using indexof() the following example uses indexof() to locate values in an array.
Array.prototype.join() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples joining an array four different ways the following example creates an array, a, with three elements, then joins the array four times: using the default separator, then a comma and a space, then a plus and an empty string.
Array.prototype.keys() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples key iterator doesn't ignore holes var arr = ['a', , 'c']; var sparsekeys = object.keys(arr); var densekeys = [...arr.keys()]; console.log(sparsekeys); // ['0', '2'] console.log(densekeys); // [0, 1, 2] specifications specification ecmascript (ecma-262)the definition of 'array.prototype.keys' in that specification.
Array.prototype.lastIndexOf() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using lastindexof the following example uses lastindexof to locate values in an array.
Array.prototype.length - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples iterating over an array in the following example, the array numbers is iterated through by looking at the length property.
Array.prototype.map() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...return a return a; }; }
examples mapping an array of numbers to an array of square roots the following code takes an array of numbers and creates a new array containing the square roots of the numbers in the first array.
Array.prototype.pop() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples removing the last element of an array the following code creates the myfish array containing four elements, then removes its last element.
Array.prototype.push() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples adding elements to an array the following code creates the sports array containing two elements, then appends two elements to it.
Array.prototype.reverse() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples reversing the elements in an array the following example creates an array a, containing three elements, then reverses the array.
Array.prototype.shift() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples removing an element from an array the following code displays the myfish array before and after removing its first element.
Array.prototype.slice() - JavaScript
if you'd like to contribute to the interactive demo project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples return a portion of an existing array let fruits = ['banana', 'orange', 'lemon', 'apple', 'mango'] let citrus = fruits.slice(1, 3) // fruits contains ['banana', 'orange', 'lemon', 'apple', 'mango'] // citrus contains ['orange','lemon'] using slice> in the following example, slice creates a new array, newcar, from mycar.
Array.prototype.some() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...rict'; if (this == null) { throw new typeerror('array.prototype.some called on null or undefined'); } if (typeof fun !== 'function') { throw new typeerror(); } var t = object(this); var len = t.length >>> 0; for (var i = 0; i < len; i++) { if (i in t && fun.call(thisarg, t[i], i, t)) { return true; } } return false; }; }
examples testing value of array elements the following example tests whether any element in the array is bigger than 10.
Array.prototype.sort() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...', value: 37 } ]; // sort by value items.sort(function (a, b) { return a.value - b.value; }); // sort by name items.sort(function(a, b) { var namea = a.name.touppercase(); // ignore upper and lowercase var nameb = b.name.touppercase(); // ignore upper and lowercase if (namea < nameb) { return -1; } if (namea > nameb) { return 1; } // names must be equal return 0; });
examples creating, displaying, and sorting an array the following example creates four arrays and displays the original array, then the sorted arrays.
Array.prototype.splice() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples remove 0 (zero) elements before index 2, and insert "drum" let myfish = ['angel', 'clown', 'mandarin', 'sturgeon'] let removed = myfish.splice(2, 0, 'drum') // myfish is ["angel", "clown", "drum", "mandarin", "sturgeon"] // removed is [], no elements removed remove 0 (zero) elements before index 2, and insert "drum" and "guitar" let myfish = ['angel', 'clown', 'mandarin', 'sturgeon'] let rem...
Array.prototype.toLocaleString() - JavaScript
examples using locales and options the elements of the array are converted to strings using their tolocalestring methods.
... object: object.prototype.tolocalestring() number: number.prototype.tolocalestring() date: date.prototype.tolocalestring() always display the currency for the strings and numbers in the prices array: var prices = ['¥7', 500, 8123, 12]; prices.tolocalestring('ja-jp', { style: 'currency', currency: 'jpy' }); // "¥7,¥500,¥8,123,¥12" for more
examples, see also the intl, numberformat, and datetimeformat pages.
ArrayBuffer() constructor - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... var dv = arraybuffer(10); // typeerror: calling a builtin arraybuffer constructor // without new is forbidden var dv = new arraybuffer(10);
examples creating an arraybuffer in this example, we create a 8-byte buffer with a int32array view referring to the buffer: var buffer = new arraybuffer(8); var view = new int32array(buffer); specifications specification ecmascript (ecma-262)the definition of 'arraybuffer' in that specification.
ArrayBuffer.prototype.byteLength - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
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.
ArrayBuffer.isView() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using isview arraybuffer.isview(); // false arraybuffer.isview([]); // false arraybuffer.isview({}); // false arraybuffer.isview(null); // false arraybuffer.isview(undefined); // false arraybuffer.isview(new arraybuffer(10)); // false arraybuffer.isview(new uint8array()); // true arraybuffer.isview(new float32array()); // true arraybuffer.isview(new int8array(10).subarray(0, 3)); // true const buffer = new arraybuffer(2); const dv = new dataview(buffer); arraybuffer.isview(dv); // true specifications specification ...
ArrayBuffer.prototype.slice() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples copying an arraybuffer const buf1 = new arraybuffer(8); const buf2 = buf1.slice(0); specifications specification ecmascript (ecma-262)the definition of 'arraybuffer.prototype.slice' in that specification.
Atomics.add() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using add() const sab = new sharedarraybuffer(1024); const ta = new uint8array(sab); atomics.add(ta, 0, 12); // returns 0, the old value atomics.load(ta, 0); // 12 specifications specification ecmascript (ecma-262)the definition of 'atomics.add' in that specification.
Atomics.and() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... 5 0101 1 0001 ---- 1 0001
examples using and() const sab = new sharedarraybuffer(1024); const ta = new uint8array(sab); ta[0] = 5; atomics.and(ta, 0, 1); // returns 0, the old value atomics.load(ta, 0); // 1 specifications specification ecmascript (ecma-262)the definition of 'atomics.and' in that specification.
Atomics.compareExchange() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using compareexchange() const sab = new sharedarraybuffer(1024); const ta = new uint8array(sab); ta[0] = 7; atomics.compareexchange(ta, 0, 7, 12); // returns 7, the old value atomics.load(ta, 0); // 12 specifications specification ecmascript (ecma-262)the definition of 'atomics.compareexchange' in that specification.
Atomics.exchange() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using exchange() const sab = new sharedarraybuffer(1024); const ta = new uint8array(sab); atomics.exchange(ta, 0, 12); // returns 0, the old value atomics.load(ta, 0); // 12 specifications specification ecmascript (ecma-262)the definition of 'atomics.exchange' in that specification.
Atomics.isLockFree() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using islockfree atomics.islockfree(1); // true atomics.islockfree(2); // true atomics.islockfree(3); // false atomics.islockfree(4); // true atomics.islockfree(5); // false atomics.islockfree(6); // false atomics.islockfree(7); // false atomics.islockfree(8); // true specifications specification ecmascript (ecma-262)the definition of 'atomics.islockfree' in that specification.
Atomics.load() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using load const sab = new sharedarraybuffer(1024); const ta = new uint8array(sab); atomics.add(ta, 0, 12); atomics.load(ta, 0); // 12 specifications specification ecmascript (ecma-262)the definition of 'atomics.load' in that specification.
Atomics.or() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... 5 0101 1 0001 ---- 5 0101
examples using or const sab = new sharedarraybuffer(1024); const ta = new uint8array(sab); ta[0] = 2; atomics.or(ta, 0, 1); // returns 2, the old value atomics.load(ta, 0); // 3 specifications specification ecmascript (ecma-262)the definition of 'atomics.or' in that specification.
Atomics.store() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using store() var sab = new sharedarraybuffer(1024); var ta = new uint8array(sab); atomics.store(ta, 0, 12); // 12 specifications specification ecmascript (ecma-262)the definition of 'atomics.store' in that specification.
Atomics.sub() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using sub const sab = new sharedarraybuffer(1024); const ta = new uint8array(sab); ta[0] = 48; atomics.sub(ta, 0, 12); // returns 48, the old value atomics.load(ta, 0); // 36 specifications specification ecmascript (ecma-262)the definition of 'atomics.sub' in that specification.
Atomics.xor() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... 5 0101 1 0001 ---- 4 0100
examples using xor const sab = new sharedarraybuffer(1024); const ta = new uint8array(sab); ta[0] = 5; atomics.xor(ta, 0, 1); // returns 5, the old value atomics.load(ta, 0); // 4 specifications specification ecmascript (ecma-262)the definition of 'atomics.xor' in that specification.
BigInt.asIntN() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples staying in 64-bit ranges the bigint.asintn() method can be useful to stay in the range of 64-bit arithmetic.
BigInt.asUintN() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples staying in 64-bit ranges the bigint.asuintn() method can be useful to stay in the range of 64-bit arithmetic.
BigInt.prototype.toLocaleString() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using tolocalestring in basic use without specifying a locale, a formatted string in the default locale and with default options is returned.
BigInt.prototype.toString() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using tostring 17n.tostring(); // '17' 66n.tostring(2); // '1000010' 254n.tostring(16); // 'fe' -10n.tostring(2); // -1010' -0xffn.tostring(2); // '-11111111' negative-zero bigint there is no negative-zero bigint as there are no negative zeros in integers.
BigInt.prototype.valueOf() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using valueof typeof object(1n); // object typeof object(1n).valueof(); // bigint specifications specification ecmascript (ecma-262)the definition of 'bigint.prototype.valueof()' in that specification.
Boolean() constructor - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples creating boolean objects with an initial value of false var bnoparam = new boolean(); var bzero = new boolean(0); var bnull = new boolean(null); var bemptystring = new boolean(''); var bfalse = new boolean(false); creating boolean objects with an initial value of true var btrue = new boolean(true); var btruestring = new boolean('true'); var bfalsestring = new boolean('false'); var bsulin = new boolean('su lin'); var barrayproto = new boolean([]); var bobjproto = new boolean({}); specifications specification ecmascript (ecma-262)the definition of 'boolean constructor' in that specification.
Boolean.prototype.toString() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using tostring() in the following code, flag.tostring() returns "true": var flag = new boolean(true); var myvar = flag.tostring(); specifications specification ecmascript (ecma-262)the definition of 'boolean.prototype.tostring' in that specification.
Boolean.prototype.valueOf() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using valueof() x = new boolean(); myvar = x.valueof(); // assigns false to myvar specifications specification ecmascript (ecma-262)the definition of 'boolean.prototype.valueof' in that specification.
DataView() constructor - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using dataview var buffer = new arraybuffer(16); var view = new dataview(buffer, 0); view.setint16(1, 42); view.getint16(1); // 42 specifications specification ecmascript (ecma-262)the definition of 'dataview constructor' in that specification.
DataView.prototype.buffer - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
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.prototype.byteLength - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
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 ...
DataView.prototype.byteOffset - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using the byteoffset property var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.byteoffset; // 0 (no offset specified) var dataview2 = new dataview(buffer, 3); dataview2.byteoffset; // 3 (as specified when constructing the dataview) specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.byteoffset' in that specification.
DataView.prototype.getBigInt64() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using the getbigint64 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.getbigint64(0); // 0n specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.getbigint64()' in that specification.
DataView.prototype.getBigUint64() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using the getbiguint64 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.getbiguint64(0); // 0n specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.getbiguint64()' in that specification.
DataView.prototype.getFloat32() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using the getfloat32 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.getfloat32(1); // 0 specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.getfloat32' in that specification.
DataView.prototype.getFloat64() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using the getfloat64 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.getfloat64(0); // 0 specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.getfloat64' in that specification.
DataView.prototype.getInt16() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using the getint16 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.getint16(1); // 0 specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.getint16' in that specification.
DataView.prototype.getInt32() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using the getint32 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.getint32(1); // 0 specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.getint32' in that specification.
DataView.prototype.getInt8() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using the getint8 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.getint8(1); // 0 specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.getint8' in that specification.
DataView.prototype.getUint16() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using the getuint16 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.getuint16(1); // 0 specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.getuint16' in that specification.
DataView.prototype.getUint32() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using the getuint32 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.getuint32(1); // 0 specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.getuint32' in that specification.
DataView.prototype.getUint8() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using the getuint8 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.getuint8(1); // 0 specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.getuint8' in that specification.
DataView.prototype.setBigInt64() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using the setbigint64 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.setbigint64(0, 3n); dataview.getbigint64(0); // 3n specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.setbigint64()' in that specification.
DataView.prototype.setBigUint64() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using the setbiguint64 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.setbiguint64(0, 3n); dataview.getbiguint64(0); // 3n specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.setbiguint64()' in that specification.
DataView.prototype.setFloat32() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using the setfloat32 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.setfloat32(1, 3); dataview.getfloat32(1); // 3 specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.setfloat32' in that specification.
DataView.prototype.setFloat64() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using the setfloat64 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.setfloat64(0, 3); dataview.getfloat64(0); // 3 specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.setfloat64' in that specification.
DataView.prototype.setInt16() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using the setint16 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.setint16(1, 3); dataview.getint16(1); // 3 specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.setint16' in that specification.
DataView.prototype.setInt32() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using the setint32 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.setint32(1, 3); dataview.getint32(1); // 3 specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.setint32' in that specification.
DataView.prototype.setInt8() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using the setint8 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.setint8(1, 3); dataview.getint8(1); // 3 specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.setint8' in that specification.
DataView.prototype.setUint16() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using the setuint16 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.setuint16(1, 3); dataview.getuint16(1); // 3 specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.setuint16' in that specification.
DataView.prototype.setUint32() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using the setuint32 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.setuint32(1, 3); dataview.getuint32(1); // 3 specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.setuint32' in that specification.
DataView.prototype.setUint8() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using the setuint8 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.setuint8(1, 3); dataview.getuint8(1); // 3 specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.setuint8' in that specification.
Date() constructor - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples several ways to create a date object the following
examples show several ways to create javascript dates: note: parsing of date strings with the date constructor (and date.parse, they are equivalent) is strongly discouraged due to browser differences and inconsistencies.
Date.UTC() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using date.utc() the following statement creates a date object with the arguments treated as utc instead of local: let utcdate = new date(date.utc(2018, 11, 1, 0, 0, 0)); specifications specification ecmascript (ecma-262)the definition of 'date.utc' in that specification.
Date.prototype.getDate() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using getdate() the second statement below assigns the value 25 to the variable day, based on the value of the date object xmas95.
Date.prototype.getDay() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using getday() the second statement below assigns the value 1 to weekday, based on the value of the date object xmas95.
Date.prototype.getFullYear() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using getfullyear() the following example assigns the four-digit value of the current year to the variable year.
Date.prototype.getHours() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using gethours() the second statement below assigns the value 23 to the variable hours, based on the value of the date object xmas95.
Date.prototype.getMilliseconds() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using getmilliseconds() the following example assigns the milliseconds portion of the current time to the variable milliseconds: var today = new date(); var milliseconds = today.getmilliseconds(); specifications specification ecmascript (ecma-262)the definition of 'date.prototype.getmilliseconds' in that specification.
Date.prototype.getMonth() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using getmonth() the second statement below assigns the value 11 to the variable month, based on the value of the date object xmas95.
Date.prototype.getSeconds() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using getseconds() the second statement below assigns the value 30 to the variable seconds, based on the value of the date object xmas95.
Date.prototype.getTime() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using gettime() for copying dates constructing a date object with the identical time value.
Date.prototype.getTimezoneOffset() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using gettimezoneoffset() // get current timezone offset for host device let x = new date(); let currenttimezoneoffsetinhours = x.gettimezoneoffset() / 60; // 1 // get timezone offset for international labour day (may 1) in 2016 // be careful, the date() constructor uses 0-indexed months, so may is // represented with 4 (and not 5) let labourday = new date(2016, 4, 1) let labourdayoffset = lab...
Date.prototype.getUTCDay() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using getutcday() the following example assigns the weekday portion of the current date to the variable weekday.
Date.prototype.getUTCFullYear() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using getutcfullyear() the following example assigns the four-digit value of the current year to the variable year.
Date.prototype.getUTCHours() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using getutchours() the following example assigns the hours portion of the current time to the variable hours.
Date.prototype.getUTCMonth() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using getutcmonth() the following example assigns the month portion of the current date to the variable month.
Date.prototype.setDate() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using setdate() var thebigday = new date(1962, 6, 7); // 1962-07-07 (7th of july 1962) thebigday.setdate(24); // 1962-07-24 (24th of july 1962) thebigday.setdate(32); // 1962-08-01 (1st of august 1962) thebigday.setdate(22); // 1962-08-22 (22th of august 1962) thebigday.setdate(0); // 1962-07-31 (31th of july 1962) thebigday.setdate(98); // 1962-10-06 (6th of october 1962) thebigday.setda...
Date.prototype.setFullYear() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using setfullyear() var thebigday = new date(); thebigday.setfullyear(1997); specifications specification ecmascript (ecma-262)the definition of 'date.prototype.setfullyear' in that specification.
Date.prototype.setHours() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using sethours() var thebigday = new date(); thebigday.sethours(7); specifications specification ecmascript (ecma-262)the definition of 'date.prototype.sethours' in that specification.
Date.prototype.setMilliseconds() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using setmilliseconds() var thebigday = new date(); thebigday.setmilliseconds(100); specifications specification ecmascript (ecma-262)the definition of 'date.prototype.setmilliseconds' in that specification.
Date.prototype.setMinutes() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using setminutes() var thebigday = new date(); thebigday.setminutes(45); specifications specification ecmascript (ecma-262)the definition of 'date.prototype.setminutes' in that specification.
Date.prototype.setSeconds() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using setseconds() var thebigday = new date(); thebigday.setseconds(30); specifications specification ecmascript (ecma-262)the definition of 'date.prototype.setseconds' in that specification.
Date.prototype.setTime() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using settime() var thebigday = new date('july 1, 1999'); var sameasbigday = new date(); sameasbigday.settime(thebigday.gettime()); specifications specification ecmascript (ecma-262)the definition of 'date.prototype.settime' in that specification.
Date.prototype.setUTCDate() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using setutcdate() var thebigday = new date(); thebigday.setutcdate(20); specifications specification ecmascript (ecma-262)the definition of 'date.prototype.setutcdate' in that specification.
Date.prototype.setUTCFullYear() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using setutcfullyear() var thebigday = new date(); thebigday.setutcfullyear(1997); specifications specification ecmascript (ecma-262)the definition of 'date.prototype.setutcfullyear' in that specification.
Date.prototype.setUTCHours() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using setutchours() var thebigday = new date(); thebigday.setutchours(8); specifications specification ecmascript (ecma-262)the definition of 'date.prototype.setutchours' in that specification.
Date.prototype.setUTCMilliseconds() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using setutcmilliseconds() var thebigday = new date(); thebigday.setutcmilliseconds(500); specifications specification ecmascript (ecma-262)the definition of 'date.prototype.setutcmilliseconds' in that specification.
Date.prototype.setUTCMinutes() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using setutcminutes() var thebigday = new date(); thebigday.setutcminutes(43); specifications specification ecmascript (ecma-262)the definition of 'date.prototype.setutcminutes' in that specification.
Date.prototype.setUTCMonth() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using setutcmonth() var thebigday = new date(); thebigday.setutcmonth(11); specifications specification ecmascript (ecma-262)the definition of 'date.prototype.setutcmonth' in that specification.
Date.prototype.setUTCSeconds() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using setutcseconds() var thebigday = new date(); thebigday.setutcseconds(20); specifications specification ecmascript (ecma-262)the definition of 'date.prototype.setutcseconds' in that specification.
Date.prototype.toDateString() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples a basic usage of todatestring() var d = new date(1993, 5, 28, 14, 39, 7); console.log(d.tostring()); // logs mon jun 28 1993 14:39:07 gmt-0600 (pdt) console.log(d.todatestring()); // logs mon jun 28 1993 note: month are 0-indexed when used as an argument of date (thus 0 corresponds to january and 11 to december).
Date.prototype.toISOString() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... date.prototype.toisostring = function() { return this.getutcfullyear() + '-' + pad(this.getutcmonth() + 1) + '-' + pad(this.getutcdate()) + 't' + pad(this.getutchours()) + ':' + pad(this.getutcminutes()) + ':' + pad(this.getutcseconds()) + '.' + (this.getutcmilliseconds() / 1000).tofixed(3).slice(2, 5) + 'z'; }; })(); }
examples using toisostring() let today = new date('05 october 2011 14:48 utc') console.log(today.toisostring()) // returns 2011-10-05t14:48:00.000z the above example uses parsing of a non–standard string value that may not be correctly parsed in non–mozilla browsers.
Date.prototype.toJSON() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using tojson() var jsondate = (new date()).tojson(); var backtodate = new date(jsondate); console.log(jsondate); //2015-10-26t07:46:36.611z specifications specification ecmascript (ecma-262)the definition of 'date.prototype.tojson' in that specification.
Date.prototype.toLocaleDateString() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using tolocaledatestring() in basic use without specifying a locale, a formatted string in the default locale and with default options is returned.
Date.prototype.toLocaleTimeString() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using tolocaletimestring() in basic use without specifying a locale, a formatted string in the default locale and with default options is returned.
Date.prototype.toString() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using tostring() the following assigns the tostring() value of a date object to myvar: var x = new date(); var myvar = x.tostring(); // assigns a string value to myvar in the same format as: // mon sep 08 1998 14:36:22 gmt-0700 (pdt) specifications specification ecmascript (ecma-262)the definition of 'date.prototype.tostring' in that specification...
Date.prototype.toTimeString() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples a basic usage of totimestring() var d = new date(1993, 6, 28, 14, 39, 7); console.log(d.tostring()); // wed jul 28 1993 14:39:07 gmt-0600 (pdt) console.log(d.totimestring()); // 14:39:07 gmt-0600 (pdt) specifications specification ecmascript (ecma-262)the definition of 'date.prototype.totimestring' in that specification.
Date.prototype.toUTCString() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using toutcstring() let today = new date('wed, 14 jun 2017 00:00:00 pdt'); let utcstring = today.toutcstring(); // wed, 14 jun 2017 07:00:00 gmt specifications specification ecmascript (ecma-262)the definition of 'date.prototype.toutcstring' in that specification.
Date - JavaScript
examples several ways to create a date object the following
examples show several ways to create javascript dates: note: parsing of date strings with the date constructor (and date.parse, they are equivalent) is strongly discouraged due to browser differences and inconsistencies.
... let date = new date(98, 1) // sun feb 01 1998 00:00:00 gmt+0000 (gmt) // deprecated method; 98 maps to 1998 here as well date.setyear(98) // sun feb 01 1998 00:00:00 gmt+0000 (gmt) date.setfullyear(98) // sat feb 01 0098 00:00:00 gmt+0000 (bst) calculating elapsed time the following
examples show how to determine the elapsed time between two javascript dates in milliseconds.
Function() constructor - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples specifying arguments with the function constructor the following code creates a function object that takes two arguments.
Function.prototype.bind() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples creating a bound function the simplest use of bind() is to make a function that, no matter how it is called, is called with a particular this value.
Function.prototype.call() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using call to chain constructors for an object you can use call to chain constructors for an object (similar to java).
Function.length - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using function length console.log(function.length); /* 1 */ console.log((function() {}).length); /* 0 */ console.log((function(a) {}).length); /* 1 */ console.log((function(a, b) {}).length); /* 2 etc.
Function.name - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples function statement name the name property returns the name of a function statement.
Function.prototype.toString() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples comparing actual source code and tostring results function function.prototype.tostring result function f(){} "function f(){}" class a { a(){} } "class a { a(){} }" function* g(){} "function* g(){}" a => a "a => a" ({ a(){} }.a) ...
Infinity - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using infinity console.log(infinity ); /* infinity */ console.log(infinity + 1 ); /* infinity */ console.log(math.pow(10, 1000)); /* infinity */ console.log(math.log(0) ); /* -infinity */ console.log(1 / infinity ); /* 0 */ console.log(1 / 0 ); /* infinity */ specifications specification ecmascript (ecma-262)the definition of 'infini...
Intl.Collator.prototype.compare() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using compare for array sort use the compare getter function for sorting arrays.
Intl.Collator.prototype.resolvedOptions() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using the resolvedoptions method var de = new intl.collator('de', { sensitivity: 'base' }) var usedoptions = de.resolvedoptions(); usedoptions.locale; // "de" usedoptions.usage; // "sort" usedoptions.sensitivity; // "base" usedoptions.ignorepunctuation; // false usedoptions.collation; // "default" usedoptions.numeric; // false specifications ...
Intl.Collator.supportedLocalesOf() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using supportedlocalesof assuming a runtime that supports indonesian and german but not balinese in collation, supportedlocalesof returns the indonesian and german language tags unchanged, even though pinyin collation is not used with indonesian and a specialized german for indonesia is unlikely to be supported.
Intl.Collator - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using collator the following example demonstrates the different potential results for a string occurring before, after, or at the same level as another: console.log(new intl.collator().compare('a', 'c')); // → a negative value console.log(new intl.collator().compare('c', 'a')); // → a positive value console.log(new intl.collator().compare('a', 'a')); // → 0 note that the results shown ...
Intl.DateTimeFormat() constructor - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using datetimeformat in basic use without specifying a locale, datetimeformat uses the default locale and default options.
Intl.DateTimeFormat.prototype.formatRange() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... syntax intl.datetimeformat.prototype.formatrange(startdate, enddate)
examples basic formatrange usage this method receives two dates and formats the date range in the most concise way based on the locale and options provided when instantiating intl.datetimeformat.
Intl.DateTimeFormat.prototype.formatRangeToParts() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... syntax intl.datetimeformat.prototype.formatrangetoparts(startdate, enddate)
examples basic formatrangetoparts usage this method receives two dates and returns an array of objects containing the locale-specific tokens representing each part of the formatted date range.
Intl.DateTimeFormat.prototype.resolvedOptions() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using the resolvedoptions method var germanfakeregion = new intl.datetimeformat('de-xx', { timezone: 'utc' }); var usedoptions = germanfakeregion.resolvedoptions(); usedoptions.locale; // "de" usedoptions.calendar; // "gregory" usedoptions.numberingsystem; // "latn" usedoptions.timezone; // "utc" usedoptions.month; // "numeric" specifications specif...
Intl.DateTimeFormat.supportedLocalesOf() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using supportedlocalesof assuming a runtime that supports indonesian and german but not balinese in date and time formatting, supportedlocalesof returns the indonesian and german language tags unchanged, even though pinyin collation is neither relevant to date and time formatting nor used with indonesian, and a specialized german for indonesia is unlikely to be supported.
Intl.DateTimeFormat - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using datetimeformat in basic use without specifying a locale, datetimeformat uses the default locale and default options.
Intl.DisplayNames() constructor - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... "code" "none"
examples basic usage in basic use without specifying a locale, a formatted string in the default locale and with default options is returned.
Intl.DisplayNames.prototype.of() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using the of method let regionnames = new intl.displaynames(['en'], {type: 'region'}); regionnames.of('419'); // "latin america" let languagenames = new intl.displaynames(['en'], {type: 'language'}); languagenames.of('fr'); // "french" let currencynames = new intl.displaynames(['en'], {type: 'currency'}); currencynames.of('eur'); // "euro" specifications specification ...
Intl.DisplayNames - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples region code display names to create an intl.displaynames for a locale and get the display name for a region code.
Intl.ListFormat() constructor - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using format the following example shows how to create a list formatter using the english language.
Intl.ListFormat - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using format the following example shows how to create a list formatter using the english language.
Intl.Locale.prototype.toString() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using tostring let mylocale = new intl.locale("fr-latn-fr", {hourcycle: "h24", calendar: "gregory"}); console.log(mylocale.basename); // prints "fr-latn-fr" console.log(mylocale.tostring()); // prints "fr-latn-fr-u-ca-gregory-hc-h24" specifications specification ecmascript internationalization api (ecma-402) ...
Intl.NumberFormat() constructor - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples basic usage in basic use without specifying a locale, a formatted string in the default locale and with default options is returned.
Intl.NumberFormat.prototype.format() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using format use the format getter function for formatting a single currency value, here for russia: var options = { style: 'currency', currency: 'rub' }; var numberformat = new intl.numberformat('ru-ru', options); console.log(numberformat.format(654321.987)); // → "654 321,99 руб." using format with map use the format getter function for formatting all numbers in an array.
Intl.NumberFormat.prototype.resolvedOptions() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using the resolvedoptions method var de = new intl.numberformat('de-de'); var usedoptions = de.resolvedoptions(); usedoptions.locale; // "de-de" usedoptions.numberingsystem; // "latn" usedoptions.notation; // "standard" usedoptions.signdisplay; // "auto" usedoption.style; // "decimal" usedoptions.minimumintegerdigits; // 1 usedoptio...
Intl.NumberFormat.supportedLocalesOf() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using supportedlocalesof assuming a runtime that supports indonesian and german but not balinese in number formatting, supportedlocalesof returns the indonesian and german language tags unchanged, even though pinyin collation is neither relevant to number formatting nor used with indonesian, and a specialized german for indonesia is unlikely to be supported.
Intl.NumberFormat - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples basic usage in basic use without specifying a locale, a formatted string in the default locale and with default options is returned.
Intl.RelativeTimeFormat.prototype.format() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples basic format usage the following example shows how to create a relative time formatter using the english language.
Intl.RelativeTimeFormat.prototype.formatToParts() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using formattoparts const rtf = new intl.relativetimeformat("en", { numeric: "auto" }); // format relative time using the day unit rtf.formattoparts(-1, "day"); // > [{ type: "literal", value: "yesterday"}] rtf.formattoparts(100, "day"); // > [{ type: "literal", value: "in " }, // > { type: "integer", value: "100", unit: "day" }, // > { type: "literal", value: " days" }] specifications ...
Intl.RelativeTimeFormat.prototype.resolvedOptions() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using the resolvedoptions method var de = new intl.relativetimeformat('de-de'); var usedoptions = de.resolvedoptions(); usedoptions.locale; // "de-de" usedoptions.style; // "long" usedoptions.numeric; // "always" usedoptions.numberingsystem; // "latn" specifications specification status comment ecmascript internationalization api (ecma-402)...
Intl.RelativeTimeFormat.supportedLocalesOf() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using supportedlocalesof assuming a runtime that supports indonesian and german but not balinese in date and time formatting, supportedlocalesof returns the indonesian and german language tags unchanged, even though pinyin collation is neither relevant to date and time formatting nor used with indonesian, and a specialized german for indonesia is unlikely to be supported.
Intl.RelativeTimeFormat - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples basic format usage the following example shows how to use a relative time formatter for the english language.
Intl.getCanonicalLocales() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using getcanonicallocales intl.getcanonicallocales('en-us'); // ["en-us"] intl.getcanonicallocales(['en-us', 'fr']); // ["en-us", "fr"] intl.getcanonicallocales('en_us'); // rangeerror:'en_us' is not a structurally valid language tag specifications specification ecmascript internationalization api (ecma-402)the definition of 'intl.getcanonicallocales' in that specification.
Intl - JavaScript
examples: "de-de-u-co-phonebk": use the phonebook variant of the german sort order, which interprets umlauted vowels as corresponding character pairs: ä → ae, ö → oe, ü → ue.
...
examples formatting dates and numbers you can use intl to format dates and numbers in a form that's conventional for a specific language and region: const count = 26254.39; const date = new date("2012-05-24"); function log(locale) { console.log( `${new intl.datetimeformat(locale).format(date)} ${new intl.numberformat(locale).format(count)}` ); } log("en-us"); // expected output: 5/24/2012 26,...
JSON.parse() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... throw new syntaxerror("json.parse"); }; }
examples using json.parse() json.parse('{}'); // {} json.parse('true'); // true json.parse('"foo"'); // "foo" json.parse('[1, 5, "false"]'); // [1, 5, "false"] json.parse('null'); // null using the reviver parameter if a reviver is specified, the value computed by parsing is transformed before being returned.
JSON.stringify() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using json.stringify json.stringify({}); // '{}' json.stringify(true); // 'true' json.stringify('foo'); // '"foo"' json.stringify([1, 'false', false]); // '[1,"false",false]' json.stringify([nan, null, infinity]); // '[null,null,null]' json.stringify({ x: 5 }); // '{"x":5}' json.stringify(new date(2006, 0, 2, 15, 4, 5)) // '"20...
Map.prototype[@@iterator]() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using [@@iterator]() const mymap = new map() mymap.set('0', 'foo') mymap.set(1, 'bar') mymap.set({}, 'baz') const mapiter = mymap[symbol.iterator]() console.log(mapiter.next().value) // ["0", "foo"] console.log(mapiter.next().value) // [1, "bar"] console.log(mapiter.next().value) // [object, "baz"] using [@@iterator]() with for..of const mymap = new map() mymap.set('0', 'foo') mymap.set(1, 'bar') mymap.set({}, 'baz') for (const entry of mymap) { console.log(entry) } // ["0", "foo"] // [1, "bar"] // [{}, "baz"] for (const [key, value] of mymap) { console.log(`${key}: ${value}`) } // 0: foo // 1: bar // [object]: baz specifications specification ...
Map.prototype[@@toStringTag] - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... property attributes of map.prototype[@@tostringtag] writable no enumerable no configurable yes syntax map[symbol.tostringtag]
examples using tostringtag object.prototype.tostring.call(new map()) // "[object map]" specifications specification ecmascript (ecma-262)the definition of 'map.prototype[@@tostringtag]' in that specification.
Map.prototype.clear() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using clear() var mymap = new map(); mymap.set('bar', 'baz'); mymap.set(1, 'foo'); mymap.size; // 2 mymap.has('bar'); // true mymap.clear(); mymap.size; // 0 mymap.has('bar') // false specifications specification ecmascript (ecma-262)the definition of 'map.prototype.clear' in that specification.
Map.prototype.delete() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using delete() var mymap = new map(); mymap.set('bar', 'foo'); mymap.delete('bar'); // returns true.
Map.prototype.entries() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using entries() let mymap = new map() mymap.set('0', 'foo') mymap.set(1, 'bar') mymap.set({}, 'baz') let mapiter = mymap.entries() console.log(mapiter.next().value) // ["0", "foo"] console.log(mapiter.next().value) // [1, "bar"] console.log(mapiter.next().value) // [object, "baz"] specifications specification ecmascript (ecma-262)the definition of 'map.prototype.entries' in that specification.
Map.prototype.forEach() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples printing the contents of a map object the following code logs a line for each element in an map object: function logmapelements(value, key, map) { console.log(`map.get('${key}') = ${value}`) } new map([['foo', 3], ['bar', {}], ['baz', undefined]]).foreach(logmapelements) // logs: // "map.get('foo') = 3" // "map.get('bar') = [object object]" // "map.get('baz') = undefined" specifications ...
Map.prototype.get() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using get() let mymap = new map(); mymap.set('bar', 'foo'); mymap.get('bar'); // returns "foo" mymap.get('baz'); // returns undefined specifications specification ecmascript (ecma-262)the definition of 'map.prototype.get' in that specification.
Map.prototype.has() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using has() let mymap = new map() mymap.set('bar', "foo") mymap.has('bar') // returns true mymap.has('baz') // returns false specifications specification ecmascript (ecma-262)the definition of 'map.prototype.has' in that specification.
Map.prototype.keys() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using keys() var mymap = new map(); mymap.set('0', 'foo'); mymap.set(1, 'bar'); mymap.set({}, 'baz'); var mapiter = mymap.keys(); console.log(mapiter.next().value); // "0" console.log(mapiter.next().value); // 1 console.log(mapiter.next().value); // object specifications specification ecmascript (ecma-262)the definition of 'map.prototype.keys' in that specification.
Map.prototype.set() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using set() let mymap = new map() // add new elements to the map mymap.set('bar', 'foo') mymap.set(1, 'foobar') // update an element in the map mymap.set('bar', 'baz') using the set() with chaining since the set() method returns back the same map object, you can chain the method call like below: // add new elements to the map with chaining.
Map.prototype.size - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using size var mymap = new map(); mymap.set('a', 'alpha'); mymap.set('b', 'beta'); mymap.set('g', 'gamma'); mymap.size // 3 specifications specification ecmascript (ecma-262)the definition of 'map.prototype.size' in that specification.
Map.prototype.values() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using values() var mymap = new map(); mymap.set('0', 'foo'); mymap.set(1, 'bar'); mymap.set({}, 'baz'); var mapiter = mymap.values(); console.log(mapiter.next().value); // "foo" console.log(mapiter.next().value); // "bar" console.log(mapiter.next().value); // "baz" specifications specification ecmascript (ecma-262)the definition of 'map.prototype.values' in that specification.
Math.E - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using math.e the following function returns e: function getnapier() { return math.e; } getnapier(); // 2.718281828459045 specifications specification ecmascript (ecma-262)the definition of 'math.e' in that specification.
Math.LN10 - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using math.ln10 the following function returns the natural log of 10: function getnatlog10() { return math.ln10; } getnatlog10(); // 2.302585092994046 specifications specification ecmascript (ecma-262)the definition of 'math.ln10' in that specification.
Math.LN2 - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using math.ln2 the following function returns the natural log of 2: function getnatlog2() { return math.ln2; } getnatlog2(); // 0.6931471805599453 specifications specification ecmascript (ecma-262)the definition of 'math.ln2' in that specification.
Math.LOG10E - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using math.log10e the following function returns the base 10 logarithm of e: function getlog10e() { return math.log10e; } getlog10e(); // 0.4342944819032518 specifications specification ecmascript (ecma-262)the definition of 'math.log10e' in that specification.
Math.LOG2E - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using math.log2e the following function returns the base 2 logarithm of e: function getlog2e() { return math.log2e; } getlog2e(); // 1.4426950408889634 specifications specification ecmascript (ecma-262)the definition of 'math.log2e' in that specification.
Math.PI - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using math.pi the following function uses math.pi to calculate the circumference of a circle with a passed radius.
Math.SQRT1_2 - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using math.sqrt1_2 the following function returns 1 over the square root of 2: function getroot1_2() { return math.sqrt1_2; } getroot1_2(); // 0.7071067811865476 specifications specification ecmascript (ecma-262)the definition of 'math.sqrt1_2' in that specification.
Math.SQRT2 - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using math.sqrt2 the following function returns the square root of 2: function getroot2() { return math.sqrt2; } getroot2(); // 1.4142135623730951 specifications specification ecmascript (ecma-262)the definition of 'math.sqrt2' in that specification.
Math.abs() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples behavior of math.abs() passing an empty object, an array with more than one member, a non-numeric string or undefined/empty variable returns nan.
Math.acos() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using math.acos() math.acos(-2); // nan math.acos(-1); // 3.141592653589793 math.acos(0); // 1.5707963267948966 math.acos(0.5); // 1.0471975511965979 math.acos(1); // 0 math.acos(2); // nan for values less than -1 or greater than 1, math.acos() returns nan.
Math.acosh() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... polyfill for all x≥1x \geq 1, we have arcosh(x)=ln(x+x2-1)\operatorname {arcosh} (x) = \ln \left(x + \sqrt{x^{2} - 1} \right) and so this can be emulated with the following function: math.acosh = math.acosh || function(x) { return math.log(x + math.sqrt(x * x - 1)); };
examples using math.acosh() math.acosh(-1); // nan math.acosh(0); // nan math.acosh(0.5); // nan math.acosh(1); // 0 math.acosh(2); // 1.3169578969248166 for values less than 1 math.acosh() returns nan.
Math.asin() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using math.asin() math.asin(-2); // nan math.asin(-1); // -1.5707963267948966 (-pi/2) math.asin(0); // 0 math.asin(0.5); // 0.5235987755982989 math.asin(1); // 1.5707963267948966 (pi/2) math.asin(2); // nan for values less than -1 or greater than 1, math.asin() returns nan.
Math.asinh() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using math.asinh() math.asinh(1); // 0.881373587019543 math.asinh(0); // 0 specifications specification ecmascript (ecma-262)the definition of 'math.asinh' in that specification.
Math.atan() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using math.atan() math.atan(1); // 0.7853981633974483 math.atan(0); // 0 math.atan(-0); // -0 math.atan(infinity); // 1.5707963267948966 math.atan(-infinity); // -1.5707963267948966 // the angle that the line [(0,0);(x,y)] forms with the x-axis in a cartesian coordinate system math.atan(y / x); note that you may want to avoid using ±infinity for stylistic reasons.
Math.atan2() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using math.atan2() math.atan2(90, 15); // 1.4056476493802699 math.atan2(15, 90); // 0.16514867741462683 math.atan2(±0, -0); // ±pi.
Math.atanh() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... polyfill for |x|<1\left|x\right| < 1, we have artanh(x)=12ln(1+x1-x)\operatorname {artanh} (x) = \frac{1}{2}\ln \left( \frac{1 + x}{1 - x} \right) so this can be emulated by the following function: math.atanh = math.atanh || function(x) { return math.log((1+x)/(1-x)) / 2; };
examples using math.atanh() math.atanh(-2); // nan math.atanh(-1); // -infinity math.atanh(0); // 0 math.atanh(0.5); // 0.5493061443340548 math.atanh(1); // infinity math.atanh(2); // nan for values greater than 1 or less than -1, nan is returned.
Math.cbrt() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...-pow(-x, 1/3) : pow(x, 1/3); }; })(math.pow); // localize math.pow to increase efficiency }
examples using math.cbrt() math.cbrt(nan); // nan math.cbrt(-1); // -1 math.cbrt(-0); // -0 math.cbrt(-infinity); // -infinity math.cbrt(0); // 0 math.cbrt(1); // 1 math.cbrt(infinity); // infinity math.cbrt(null); // 0 math.cbrt(2); // 1.2599210498948732 specifications specification ecmascript (ecma-262)the definition of 'math.cbrt' in that specification.
Math.ceil() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using math.ceil() the following example shows example usage of math.ceil().
Math.clz32() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... var asuint = x >>> 0; if (asuint === 0) { return 32; } return 31 - (log(asuint) / ln2 | 0) |0; // the "| 0" acts like math.floor }; })(math.log, math.ln2);
examples using math.clz32() math.clz32(1); // 31 math.clz32(1000); // 22 math.clz32(); // 32 var stuff = [nan, infinity, -infinity, 0, -0, false, null, undefined, 'foo', {}, []]; stuff.every(n => math.clz32(n) == 32); // true math.clz32(true); // 31 math.clz32(3.5); // 30 specifications specification ecmascript (ecma-262)the definitio...
Math.cos() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using math.cos() math.cos(0); // 1 math.cos(1); // 0.5403023058681398 math.cos(math.pi); // -1 math.cos(2 * math.pi); // 1 specifications specification ecmascript (ecma-262)the definition of 'math.cos' in that specification.
Math.cosh() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... polyfill this can be emulated with the help of the math.exp() function: math.cosh = math.cosh || function(x) { return (math.exp(x) + math.exp(-x)) / 2; } or using only one call to the math.exp() function: math.cosh = math.cosh || function(x) { var y = math.exp(x); return (y + 1 / y) / 2; };
examples using math.cosh() math.cosh(0); // 1 math.cosh(1); // 1.5430806348152437 math.cosh(-1); // 1.5430806348152437 specifications specification ecmascript (ecma-262)the definition of 'math.cosh' in that specification.
Math.exp() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using math.exp() math.exp(-1); // 0.36787944117144233 math.exp(0); // 1 math.exp(1); // 2.718281828459045 specifications specification ecmascript (ecma-262)the definition of 'math.exp' in that specification.
Math.expm1() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... polyfill this can be emulated with the help of the math.exp() function: math.expm1 = math.expm1 || function(x) { return math.exp(x) - 1; };
examples using math.expm1() math.expm1(-1); // -0.6321205588285577 math.expm1(0); // 0 math.expm1(1); // 1.718281828459045 specifications specification ecmascript (ecma-262)the definition of 'math.expm1' in that specification.
Math.floor() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using math.floor() math.floor( 45.95); // 45 math.floor( 45.05); // 45 math.floor( 4 ); // 4 math.floor(-45.05); // -46 math.floor(-45.95); // -46 decimal adjustment /** * decimal adjustment of a number.
Math.fround() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... var mantissa = math.round((leading - arg / powexp) * 0x800000); if (mantissa <= -0x800000) return sign * infinity; return sign * powexp * (leading - mantissa / 0x800000); };
examples using math.fround() the number 1.5 can be precisely represented in the binary numeral system, and is identical in 32-bit and 64-bit: math.fround(1.5); // 1.5 math.fround(1.5) === 1.5; // true however, the number 1.337 cannot be precisely represented in the binary numeral system, so it differs in 32-bit and 64-bit: math.fround(1.337); // 1.3370000123977661 math.fround(1.337) === 1.337; // fa...
Math.hypot() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...1 / 0 : max * math.sqrt(s)); };
examples using math.hypot() math.hypot(3, 4); // 5 math.hypot(3, 4, 5); // 7.0710678118654755 math.hypot(); // 0 math.hypot(nan); // nan math.hypot(nan, infinity); // infinity math.hypot(3, 4, 'foo'); // nan, since +'foo' => nan math.hypot(3, 4, '5'); // 7.0710678118654755, +'5' => 5 math.hypot(-3); // 3, the same as math.abs(-3) specifications ...
Math.imul() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...we can remove an integer coersion from the statement above because: // 0x1fffff7fc00001 + 0xffc00000 = 0x1fffffff800001 // 0x1fffffff800001 < number.max_safe_integer /*0x1fffffffffffff*/ if (opa & 0xffc00000 /*!== 0*/) result += (opa & 0xffc00000) * opb |0; return result |0; };
examples using math.imul() math.imul(2, 4); // 8 math.imul(-1, 8); // -8 math.imul(-2, -2); // 4 math.imul(0xffffffff, 5); // -5 math.imul(0xfffffffe, 5); // -10 specifications specification ecmascript (ecma-262)the definition of 'math.imul' in that specification.
Math.log() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using math.log() math.log(-1); // nan, out of range math.log(0); // -infinity math.log(1); // 0 math.log(10); // 2.302585092994046 using math.log() with a different base the following function returns the logarithm of y with base x (ie.
Math.log10() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using math.log10() math.log10(2); // 0.3010299956639812 math.log10(1); // 0 math.log10(0); // -infinity math.log10(-2); // nan math.log10(100000); // 5 polyfill this can be emulated with the following function: math.log10 = math.log10 || function(x) { return math.log(x) * math.log10e; }; specifications specification ecmascript (ecma-262)the definiti...
Math.log1p() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...x : x * (math.log(x + 1) / nearx); };
examples using math.log1p() math.log1p(1); // 0.6931471805599453 math.log1p(0); // 0 math.log1p(-1); // -infinity math.log1p(-2); // nan specifications specification ecmascript (ecma-262)the definition of 'math.log1p' in that specification.
Math.log2() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... if (!math.log2) math.log2 = function(x) { return math.log(x) * math.log2e; };
examples using math.log2() math.log2(3); // 1.584962500721156 math.log2(2); // 1 math.log2(1); // 0 math.log2(0); // -infinity math.log2(-2); // nan math.log2(1024); // 10 specifications specification ecmascript (ecma-262)the definition of 'math.log2' in that specification.
Math.max() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using math.max() math.max(10, 20); // 20 math.max(-10, -20); // -10 math.max(-10, 20); // 20 getting the maximum element of an array array.reduce() can be used to find the maximum element in a numeric array, by comparing each value: var arr = [1,2,3]; var max = arr.reduce(function(a, b) { return math.max(a, b); }); the following function uses function.prototype.apply() to get the...
Math.min() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using math.min() this finds the min of x and y and assigns it to z: var x = 10, y = -20; var z = math.min(x, y); clipping a value with math.min() math.min() is often used to clip a value so that it is always less than or equal to a boundary.
Math.pow() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using math.pow() // simple math.pow(7, 2); // 49 math.pow(7, 3); // 343 math.pow(2, 10); // 1024 // fractional exponents math.pow(4, 0.5); // 2 (square root of 4) math.pow(8, 1/3); // 2 (cube root of 8) math.pow(2, 0.5); // 1.4142135623730951 (square root of 2) math.pow(2, 1/3); // 1.2599210498948732 (cube root of 2) // signed exponents math.pow(7, -2); // 0.02040816326530612 (1/4...
Math.round() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using round math.round( 20.49); // 20 math.round( 20.5 ); // 21 math.round( 42 ); // 42 math.round(-20.5 ); // -20 math.round(-20.51); // -21 specifications specification ecmascript (ecma-262)the definition of 'math.round' in that specification.
Math.sign() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using math.sign() math.sign(3); // 1 math.sign(-3); // -1 math.sign('-3'); // -1 math.sign(0); // 0 math.sign(-0); // -0 math.sign(nan); // nan math.sign('foo'); // nan math.sign(); // nan specifications specification ecmascript (ecma-262)the definition of 'math.sign' in that specification.
Math.sin() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using math.sin() math.sin(0); // 0 math.sin(1); // 0.8414709848078965 math.sin(math.pi / 2); // 1 specifications specification ecmascript (ecma-262)the definition of 'math.sin' in that specification.
Math.sinh() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... polyfill this can be emulated with the help of the math.exp() function: math.sinh = math.sinh || function(x) { return (math.exp(x) - math.exp(-x)) / 2; } or using only one call to the math.exp() function: math.sinh = math.sinh || function(x) { var y = math.exp(x); return (y - 1 / y) / 2; }
examples using math.sinh() math.sinh(0); // 0 math.sinh(1); // 1.1752011936438014 specifications specification ecmascript (ecma-262)the definition of 'math.sinh' in that specification.
Math.sqrt() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using math.sqrt() math.sqrt(9); // 3 math.sqrt(2); // 1.414213562373095 math.sqrt(1); // 1 math.sqrt(0); // 0 math.sqrt(-1); // nan math.sqrt(-0); // -0 specifications specification ecmascript (ecma-262)the definition of 'math.sqrt' in that specification.
Math.tan() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using math.tan() math.tan(1); // 1.5574077246549023 because the math.tan() function accepts radians, but it is often easier to work with degrees, the following function accepts a value in degrees, converts it to radians and returns the tangent.
Math.trunc() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...math.ceil(v) : math.floor(v); }; }
examples using math.trunc() math.trunc(13.37); // 13 math.trunc(42.84); // 42 math.trunc(0.123); // 0 math.trunc(-0.123); // -0 math.trunc('-1.123'); // -1 math.trunc(nan); // nan math.trunc('foo'); // nan math.trunc(); // nan specifications specification ecmascript (ecma-262)the definition of 'math.trunc' in that specification.
NaN - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
..."foo"/3)
examples testing against nan nan compares unequal (via ==, !=, ===, and !==) to any other value -- including to another nan value.
Number.EPSILON - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... polyfill if (number.epsilon === undefined) { number.epsilon = math.pow(2, -52); }
examples testing equality x = 0.2; y = 0.3; z = 0.1; equal = (math.abs(x - y + z) < number.epsilon); specifications specification ecmascript (ecma-262)the definition of 'number.epsilon' in that specification.
Number.MAX_SAFE_INTEGER - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... polyfill if (!number.max_safe_integer) { number.max_safe_integer = 9007199254740991; // math.pow(2, 53) - 1; }
examples return value of max_safe_integer number.max_safe_integer; // 9007199254740991 numbers higher than safe integer this returns 2 because in floating points, the value is actually the decimal trailing "1" except for in subnormal precision cases such as zero.
Number.MAX_VALUE - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using max_value the following code multiplies two numeric values.
Number.MIN_SAFE_INTEGER - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using min_safe_integer number.min_safe_integer // -9007199254740991 -(math.pow(2, 53) - 1) // -9007199254740991 specifications specification ecmascript (ecma-262)the definition of 'number.min_safe_integer' in that specification.
Number.MIN_VALUE - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using min_value the following code divides two numeric values.
Number.NEGATIVE_INFINITY - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using negative_infinity in the following example, the variable smallnumber is assigned a value that is smaller than the minimum value.
Number.POSITIVE_INFINITY - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using positive_infinity in the following example, the variable bignumber is assigned a value that is larger than the maximum value.
Number.isFinite() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... polyfill if (number.isfinite === undefined) number.isfinite = function(value) { return typeof value === 'number' && isfinite(value); }
examples using isfinite number.isfinite(infinity); // false number.isfinite(nan); // false number.isfinite(-infinity); // false number.isfinite(0); // true number.isfinite(2e64); // true number.isfinite('0'); // false, would've been true with // global isfinite('0') number.isfinite(null); // false, would've been true with ...
Number.isInteger() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... polyfill number.isinteger = number.isinteger || function(value) { return typeof value === 'number' && isfinite(value) && math.floor(value) === value; };
examples using isinteger number.isinteger(0); // true number.isinteger(1); // true number.isinteger(-100000); // true number.isinteger(99999999999999999999999); // true number.isinteger(0.1); // false number.isinteger(math.pi); // false number.isinteger(nan); // false number.isinteger(infinity); // false number.isinteger(-infinity); // false number.isinteger('10'); ...
Number.isNaN() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... number.isnan = number.isnan || function isnan(input) { return typeof input === 'number' && input !== input; }
examples using isnan number.isnan(nan); // true number.isnan(number.nan); // true number.isnan(0 / 0); // true // e.g.
Number.isSafeInteger() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... polyfill number.issafeinteger = number.issafeinteger || function (value) { return number.isinteger(value) && math.abs(value) <= number.max_safe_integer; };
examples using issafeinteger number.issafeinteger(3); // true number.issafeinteger(math.pow(2, 53)); // false number.issafeinteger(math.pow(2, 53) - 1); // true number.issafeinteger(nan); // false number.issafeinteger(infinity); // false number.issafeinteger('3'); // false number.issafeinteger(3.1); // false number.i...
Number.prototype.toExponential() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using toexponential var numobj = 77.1234; console.log(numobj.toexponential()); // logs 7.71234e+1 console.log(numobj.toexponential(4)); // logs 7.7123e+1 console.log(numobj.toexponential(2)); // logs 7.71e+1 console.log(77.1234.toexponential()); // logs 7.71234e+1 console.log(77 .toexponential()); // logs 7.7e+1 specifications specification ecmascript (ecma-262)the de...
Number.prototype.toFixed() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using tofixed let numobj = 12345.6789 numobj.tofixed() // returns '12346': note rounding, no fractional part numobj.tofixed(1) // returns '12345.7': note rounding numobj.tofixed(6) // returns '12345.678900': note added zeros (1.23e+20).tofixed(2) // returns '123000000000000000000.00' (1.23e-10).tofixed(2) // returns '0.00' 2.34.tofixed(1) // returns '2.3' 2.35.tofixed(...
Number.prototype.toLocaleString() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using tolocalestring in basic use without specifying a locale, a formatted string in the default locale and with default options is returned.
Number.prototype.toString() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using tostring let count = 10 console.log(count.tostring()) // displays '10' console.log((17).tostring()) // displays '17' console.log((17.2).tostring()) // displays '17.2' let x = 6 console.log(x.tostring(2)) // displays '110' console.log((254).tostring(16)) // displays 'fe' console.log((-10).tostring(2)) // displays '-1010' console.log((-0xff).tostring(2)) // displays '-...
Number.prototype.valueOf() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using valueof let numobj = new number(10) console.log(typeof numobj) // object let num = numobj.valueof() console.log(num) // 10 console.log(typeof num) // number specifications specification ecmascript (ecma-262)the definition of 'number.prototype.valueof' in that specification.
Object.assign() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...nextsource !== null && nextsource !== undefined) { for (var nextkey in nextsource) { // avoid bugs when hasownproperty is shadowed if (object.prototype.hasownproperty.call(nextsource, nextkey)) { to[nextkey] = nextsource[nextkey]; } } } } return to; }, writable: true, configurable: true }); }
examples cloning an object const obj = { a: 1 }; const copy = object.assign({}, obj); console.log(copy); // { a: 1 } warning for deep clone for deep cloning, we need to use alternatives, because object.assign() copies property values.
Object.create() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...s browser's implementation of object.create is a shim and doesn't support 'null' as the first argument."); } if (typeof propertiesobject != 'undefined') { throw new error("this browser's implementation of object.create is a shim and doesn't support a second argument."); } function f() {} f.prototype = proto; return new f(); }; }
examples classical inheritance with object.create() below is an example of how to use object.create() to achieve classical inheritance.
Object.defineProperties() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...(typeof obj !== 'object' || obj === null) throw new typeerror('bad obj'); properties = object(properties); var keys = object.keys(properties); var descs = []; for (var i = 0; i < keys.length; i++) descs.push([keys[i], converttodescriptor(properties[keys[i]])]); for (var i = 0; i < descs.length; i++) object.defineproperty(obj, descs[i][0], descs[i][1]); return obj; }
examples using object.defineproperties var obj = {}; object.defineproperties(obj, { 'property1': { value: true, writable: true }, 'property2': { value: 'hello', writable: false } // etc.
Object.defineProperty() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...object.defineproperty(obj, 'key', withvalue('static')); // if freeze is available, prevents adding or // removing the object prototype properties // (value, get, set, enumerable, writable, configurable) (object.freeze || object)(object.prototype);
examples if you want to see how to use the object.defineproperty method with a binary-flags-like syntax, see additional
examples.
Object.entries() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples const obj = { foo: 'bar', baz: 42 }; console.log(object.entries(obj)); // [ ['foo', 'bar'], ['baz', 42] ] // array like object const obj = { 0: 'a', 1: 'b', 2: 'c' }; console.log(object.entries(obj)); // [ ['0', 'a'], ['1', 'b'], ['2', 'c'] ] // array like object with random key ordering const anobj = { 100: 'a', 2: 'b', 7: 'c' }; console.log(object.entries(anobj)); // [ ['2', 'b'], ['7', 'c']...
Object.freeze() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples freezing objects var obj = { prop: function() {}, foo: 'bar' }; // before freezing: new properties may be added, // and existing properties may be changed or removed obj.foo = 'baz'; obj.lumpy = 'woof'; delete obj.prop; // freeze.
Object.fromEntries() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples converting a map to an object with object.fromentries, you can convert from map to object: const map = new map([ ['foo', 'bar'], ['baz', 42] ]); const obj = object.fromentries(map); console.log(obj); // { foo: "bar", baz: 42 } converting an array to an object with object.fromentries, you can convert from array to object: const arr = [ ['0', 'a'], ['1', 'b'], ['2', 'c'] ]; const obj = objec...
Object.getOwnPropertyDescriptor() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using object.getownpropertydescriptor var o, d; o = { get foo() { return 17; } }; d = object.getownpropertydescriptor(o, 'foo'); // d is { // configurable: true, // enumerable: true, // get: /*the getter function*/, // set: undefined // } o = { bar: 42 }; d = object.getownpropertydescriptor(o, 'bar'); // d is { // configurable: true, // enumerable: true, // value: 42, // writa...
Object.getOwnPropertySymbols() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using getownpropertysymbols var obj = {}; var a = symbol('a'); var b = symbol.for('b'); obj[a] = 'localsymbol'; obj[b] = 'globalsymbol'; var objectsymbols = object.getownpropertysymbols(obj); console.log(objectsymbols.length); // 2 console.log(objectsymbols); // [symbol(a), symbol(b)] console.log(objectsymbols[0]); // symbol(a) specifications specification ecm...
Object.getPrototypeOf() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using getprototypeof var proto = {}; var obj = object.create(proto); object.getprototypeof(obj) === proto; // true non-object coercion in es5, it will throw a typeerror exception if the obj parameter isn't an object.
Object.prototype.hasOwnProperty() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... o = new object(); o.propone = null; o.hasownproperty('propone'); // returns true o.proptwo = undefined; o.hasownproperty('proptwo'); // returns true
examples using hasownproperty to test for a property's existence the following example determines whether the o object contains a property named prop: o = new object(); o.hasownproperty('prop'); // returns false o.prop = 'exists'; o.hasownproperty('prop'); // returns true direct vs.
Object.isExtensible() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using object.isextensible // new objects are extensible.
Object.isFrozen() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using object.isfrozen // a new object is extensible, so it is not frozen.
Object.prototype.isPrototypeOf() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using isprototypeof this example demonstrates that baz.prototype, bar.prototype, foo.prototype and object.prototype exist in the prototype chain for object baz: function foo() {} function bar() {} function baz() {} bar.prototype = object.create(foo.prototype); baz.prototype = object.create(bar.prototype); var baz = new baz(); console.log(baz.prototype.isprototypeof(baz)); // true console.lo...
Object.isSealed() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using object.issealed // objects aren't sealed by default.
Object.keys() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using object.keys // simple array const arr = ['a', 'b', 'c']; console.log(object.keys(arr)); // console: ['0', '1', '2'] // array-like object const obj = { 0: 'a', 1: 'b', 2: 'c' }; console.log(object.keys(obj)); // console: ['0', '1', '2'] // array-like object with random key ordering const anobj = { 100: 'a', 2: 'b', 7: 'c' }; console.log(object.keys(anobj)); // console: ['2', '7', '100'] ...
Object.preventExtensions() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using object.preventextensions // object.preventextensions returns the object // being made non-extensible.
Object.prototype.propertyIsEnumerable() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples a basic use of propertyisenumerable the following example shows the use of propertyisenumerable on objects and arrays: var o = {}; var a = []; o.prop = 'is enumerable'; a[0] = 'is enumerable'; o.propertyisenumerable('prop'); // returns true a.propertyisenumerable(0); // returns true user-defined vs.
Object.seal() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using object.seal var obj = { prop: function() {}, foo: 'bar' }; // new properties may be added, existing properties // may be changed or removed.
Object.prototype.toLocaleString() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... objects overriding tolocalestring array: array.prototype.tolocalestring() number: number.prototype.tolocalestring() date: date.prototype.tolocalestring() typedarray: typedarray.prototype.tolocalestring() bigint: bigint.prototype.tolocalestring()
examples array tolocalestring() override on array objects, tolocalestring() can be used to print array values as a string, optionally with locale-specific identifiers (such as currency symbols) appended to them: for example: const testarray = [4, 7, 10]; let europrices = testarray.tolocalestring('fr', { style: 'currency', currency: 'eur'}); // "4,00 €,7,00 €,10,00 €" date tolocalestring() over...
Object.prototype.toString() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples overriding the default tostring method you can create a function to be called in place of the default tostring() method.
Object.prototype.valueOf() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using valueof on custom types function mynumbertype(n) { this.number = n; } mynumbertype.prototype.valueof = function() { return this.number; }; var myobj = new mynumbertype(4); myobj + 3; // 7 using unary plus +"5" // 5 (string to number) +"" // 0 (string to number) +"1 + 2" // nan (doesn't evaluate) +new date() // same as (new date()).gettime() +"foo" // nan (string to number) +{...
Object.values() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using object.values const obj = { foo: 'bar', baz: 42 }; console.log(object.values(obj)); // ['bar', 42] // array-like object const arraylikeobj1 = { 0: 'a', 1: 'b', 2: 'c' }; console.log(object.values(arraylikeobj1 )); // ['a', 'b', 'c'] // array-like object with random key ordering // when using numeric keys, the values are returned in the keys' numerical order const arraylikeobj2 = { 100: ...
Promise() constructor - JavaScript
if you'd like to contribute to the interactive demo project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples creating a new promise a promise object is created using the new keyword and its constructor.
Promise.all() - JavaScript
if you'd like to contribute to the interactive demo project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using promise.all promise.all waits for all fulfillments (or the first rejection).
Promise.reject() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using the static promise.reject() method promise.reject(new error('fail')).then(function() { // not called }, function(error) { console.error(error); // stacktrace }); specifications specification ecmascript (ecma-262)the definition of 'promise.reject' in that specification.
Promise.prototype.then() - JavaScript
if you'd like to contribute to the interactive demo project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using the then method var p1 = new promise((resolve, reject) => { resolve('success!'); // or // reject(new error("error!")); }); p1.then(value => { console.log(value); // success!
Promise - JavaScript
examples basic example let myfirstpromise = new promise((resolve, reject) => { // we call resolve(...) when what we were doing asynchronously was successful, and reject(...) when it failed.
... loading an image with xhr another simple example using promise and xmlhttprequest to load an image is available at the mdn github js-
examples repository.
handler.apply() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples trapping a function call the following code traps a function call.
handler.construct() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples trapping the new operator the following code traps the new operator.
handler.defineProperty() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples trapping of defineproperty the following code traps object.defineproperty().
handler.deleteProperty() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples trapping the delete operator the following code traps the delete operator.
handler.get() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples trap for getting a property value the following code traps getting a property value.
handler.getOwnPropertyDescriptor() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples trapping of getownpropertydescriptor the following code traps object.getownpropertydescriptor().
handler.getPrototypeOf() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples basic usage const obj = {}; const proto = {}; const handler = { getprototypeof(target) { console.log(target === obj); // true console.log(this === handler); // true return proto; } }; const p = new proxy(obj, handler); console.log(object.getprototypeof(p) === proto); // true five ways to trigger the getprototypeof trap const obj = {}; const p = new proxy...
handler.has() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples trapping the in operator the following code traps the in operator.
handler.isExtensible() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples trapping of isextensible the following code traps object.isextensible().
handler.ownKeys() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples trapping of getownpropertynames the following code traps object.getownpropertynames().
handler.preventExtensions() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples trapping of preventextensions the following code traps object.preventextensions().
handler.set() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples trap setting of a property value the following code traps setting a property value.
handler.setPrototypeOf() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples if you want to disallow setting a new prototype for your object, your handler's setprototypeof() method can either return false, or it can throw an exception.
Reflect.apply() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using reflect.apply() reflect.apply(math.floor, undefined, [1.75]); // 1; reflect.apply(string.fromcharcode, undefined, [104, 101, 108, 108, 111]) // "hello" reflect.apply(regexp.prototype.exec, /ab/, ['confabulation']).index // 4 reflect.apply(''.charat, 'ponies', [3]) // "i" specifications specification ecmascript (ecma-262)the definition of 'reflect.apply' in that spe...
Reflect.construct() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...} let obj3 = object.create(otherclass.prototype); oneclass.apply(obj3, args) // output: // oneclass // undefined
examples using reflect.construct() let d = reflect.construct(date, [1776, 6, 4]) d instanceof date // true d.getfullyear() // 1776 specifications specification ecmascript (ecma-262)the definition of 'reflect.construct' in that specification.
Reflect.defineProperty() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using reflect.defineproperty() let obj = {} reflect.defineproperty(obj, 'x', {value: 7}) // true obj.x // 7 checking if property definition has been successful with object.defineproperty, which returns an object if successful, or throws a typeerror otherwise, you would use a try...catch block to catch any error that occurred while defining a property.
Reflect.deleteProperty() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using reflect.deleteproperty() let obj = { x: 1, y: 2 } reflect.deleteproperty(obj, 'x') // true obj // { y: 2 } let arr = [1, 2, 3, 4, 5] reflect.deleteproperty(arr, '3') // true arr // [1, 2, 3, undefined, 5] // returns true if no such property exists reflect.deleteproperty({}, 'foo') // true // returns false if a property is u...
Reflect.get() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using reflect.get() // object let obj = { x: 1, y: 2 } reflect.get(obj, 'x') // 1 // array reflect.get(['zero', 'one'], 1) // "one" // proxy with a get handler let x = {p: 1}; let obj = new proxy(x, { get(t, k, r) { return k + 'bar' } }) reflect.get(obj, 'foo') // "foobar" //proxy with get handler and receiver let x = {p: 1, foo: 2}; let y = {foo: 3}; let obj = new proxy(x, { ...
Reflect.getOwnPropertyDescriptor() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using reflect.getownpropertydescriptor() reflect.getownpropertydescriptor({x: 'hello'}, 'x') // {value: "hello", writable: true, enumerable: true, configurable: true} reflect.getownpropertydescriptor({x: 'hello'}, 'y') // undefined reflect.getownpropertydescriptor([], 'length') // {value: 0, writable: true, enumerable: false, configurable: false} difference to object.getownpropertydescripto...
Reflect.getPrototypeOf() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using reflect.getprototypeof() reflect.getprototypeof({}) // object.prototype reflect.getprototypeof(object.prototype) // null reflect.getprototypeof(object.create(null)) // null compared to object.getprototypeof() // same result for objects object.getprototypeof({}) // object.prototype reflect.getprototypeof({}) // object.prototype // both throw in es5 for non-object...
Reflect.has() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using reflect.has() reflect.has({x: 0}, 'x') // true reflect.has({x: 0}, 'y') // false // returns true for properties in the prototype chain reflect.has({x: 0}, 'tostring') // proxy with .has() handler method obj = new proxy({}, { has(t, k) { return k.startswith('door') } }); reflect.has(obj, 'doorbell') // true reflect.has(obj, 'dormitory') // false reflect.has returns true for any ...
Reflect.isExtensible() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using reflect.isextensible() see also object.isextensible().
Reflect.ownKeys() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using reflect.ownkeys() reflect.ownkeys({z: 3, y: 2, x: 1}) // [ "z", "y", "x" ] reflect.ownkeys([]) // ["length"] let sym = symbol.for('comet') let sym2 = symbol.for('meteor') let obj = {[sym]: 0, 'str': 0, '773': 0, '0': 0, [sym2]: 0, '-1': 0, '8': 0, 'second str': 0} reflect.ownkeys(obj) // [ "0", "8", "773", "str", "-1", "second str", symbol(comet), symbol(mete...
Reflect.preventExtensions() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using reflect.preventextensions() see also object.preventextensions().
Reflect.set() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using reflect.set() // object let obj = {} reflect.set(obj, 'prop', 'value') // true obj.prop // "value" // array let arr = ['duck', 'duck', 'duck'] reflect.set(arr, 2, 'goose') // true arr[2] // "goose" // it can truncate an array.
Reflect.setPrototypeOf() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using reflect.setprototypeof() reflect.setprototypeof({}, object.prototype) // true // it can change an object's [[prototype]] to null.
get RegExp[@@species] - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples species in ordinary objects the species property returns the default constructor function, which is the regexp constructor for regexp objects: regexp[symbol.species]; // function regexp() species in derived objects in a derived collection object (e.g.
RegExp() constructor - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples literal notation and constructor there are two ways to create a regexp object: a literal notation and a constructor.
RegExp.prototype.exec() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... "quick\s(brown).+?(jumps)"
examples finding successive matches if your regular expression uses the "g" flag, you can use the exec() method multiple times to find successive matches in the same string.
RegExp.prototype.flags - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... polyfill if (regexp.prototype.flags === undefined) { object.defineproperty(regexp.prototype, 'flags', { configurable: true, get: function() { return this.tostring().match(/[gimsuy]*$/)[0]; } }); }
examples using flags /foo/ig.flags; // "gi" /bar/myu.flags; // "muy" specifications specification ecmascript (ecma-262)the definition of 'regexp.prototype.flags' in that specification.
RegExp.prototype.global - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using global var regex = new regexp('foo', 'g'); console.log(regex.global); // true var str = 'fooexamplefoo'; var str1 = str.replace(regex, ''); console.log(str1); // output: example var regex1 = new regexp('foo'); var str2 = str.replace(regex1, ''); console.log(str2); // output: examplefoo specifications specification ecmascript (ecma-262)the definition of 'regex...
RegExp.prototype.ignoreCase - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using ignorecase var regex = new regexp('foo', 'i'); console.log(regex.ignorecase); // true specifications specification ecmascript (ecma-262)the definition of 'regexp.prototype.ignorecase' in that specification.
RegExp.prototype.multiline - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using multiline var regex = new regexp('foo', 'm'); console.log(regex.multiline); // true specifications specification ecmascript (ecma-262)the definition of 'regexp.prototype.multiline' in that specification.
RegExp.prototype.source - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... property attributes of regexp.prototype.source writable no enumerable no configurable yes
examples using source var regex = /foobar/ig; console.log(regex.source); // "foobar", doesn't contain /.../ and "ig".
RegExp.prototype.test() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using test() simple example that tests if "hello" is contained at the very beginning of a string, returning a boolean result.
RegExp.prototype.toString() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using tostring() the following example displays the string value of a regexp object: var myexp = new regexp('a+b+c'); console.log(myexp.tostring()); // logs '/a+b+c/' var foo = new regexp('bar', 'g'); console.log(foo.tostring()); // logs '/bar/g' empty regular expressions and escaping starting with ecmascript 5, an empty regular expression returns the string "/(?:)/" and line terminators such as "\n" are escaped: new regexp().tostring(); // "/(?:)/" new regex...
RegExp.prototype.unicode - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using the unicode property var regex = new regexp('\u{61}', 'u'); console.log(regex.unicode); // true specifications specification ecmascript (ecma-262)the definition of 'regexp.prototype.unicode' in that specification.
Set.prototype[@@iterator]() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using [@@iterator]() const myset = new set(); myset.add('0'); myset.add(1); myset.add({}); const setiter = myset[symbol.iterator](); console.log(setiter.next().value); // "0" console.log(setiter.next().value); // 1 console.log(setiter.next().value); // object using [@@iterator]() with for..of const myset = new set(); myset.add('0'); myset.add(1); myset.add({}); for (const v of myset) { console.log(v); } specifications specification ecmascript (ecma-262)the definition of 'set.prototype[@@iterator]' in that specification.
Set() constructor - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using the set object let myset = new set() myset.add(1) // set [ 1 ] myset.add(5) // set [ 1, 5 ] myset.add(5) // set [ 1, 5 ] myset.add('some text') // set [ 1, 5, 'some text' ] let o = {a: 1, b: 2} myset.add(o) specifications specification ecmascript (ecma-262)the definition of 'set constructor' in that specification.
Set.prototype.add() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using the add method var myset = new set(); myset.add(1); myset.add(5).add('some text'); // chainable console.log(myset); // set [1, 5, "some text"] specifications specification ecmascript (ecma-262)the definition of 'set.prototype.add' in that specification.
Set.prototype.clear() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using the clear method var myset = new set(); myset.add(1); myset.add('foo'); myset.size; // 2 myset.has('foo'); // true myset.clear(); myset.size; // 0 myset.has('bar') // false specifications specification ecmascript (ecma-262)the definition of 'set.prototype.clear' in that specification.
Set.prototype.delete() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using the delete() method const myset = new set(); myset.add('foo'); myset.delete('bar'); // returns false.
Set.prototype.entries() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using entries() var myset = new set(); myset.add('foobar'); myset.add(1); myset.add('baz'); var setiter = myset.entries(); console.log(setiter.next().value); // ["foobar", "foobar"] console.log(setiter.next().value); // [1, 1] console.log(setiter.next().value); // ["baz", "baz"] specifications specification ecmascript (ecma-262)the definition of 'set.prototype.entries' in that specification.
Set.prototype.forEach() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
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 ecmascri...
Set.prototype.has() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using the has method var myset = new set(); myset.add('foo'); myset.has('foo'); // returns true myset.has('bar'); // returns false var set1 = new set(); var obj1 = {'key1': 1}; set1.add(obj1); set1.has(obj1); // returns true set1.has({'key1': 1}); // returns false because they are different object references set1.add({'key1': 1}); // now set1 contains 2 entries specifications specification ecmascript (ecma-262)the definition of '...
Set.prototype.size - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using size var myset = new set(); myset.add(1); myset.add(5); myset.add('some text') myset.size; // 3 specifications specification ecmascript (ecma-262)the definition of 'set.prototype.size' in that specification.
Set.prototype.values() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using values() var myset = new set(); myset.add('foo'); myset.add('bar'); myset.add('baz'); var setiter = myset.values(); console.log(setiter.next().value); // "foo" console.log(setiter.next().value); // "bar" console.log(setiter.next().value); // "baz" specifications specification ecmascript (ecma-262)the definition of 'set.prototype.values' in that specification.
Set - JavaScript
examples using the set object let myset = new set() myset.add(1) // set [ 1 ] myset.add(5) // set [ 1, 5 ] myset.add(5) // set [ 1, 5 ] myset.add('some text') // set [ 1, 5, 'some text' ] let o = {a: 1, b: 2} myset.add(o) myset.add({a: 1, b: 2}) // o is referencing a different object, so this is okay myset.has(1) // true myset.has(3) // false,...
... let _difference = new set(seta) for (let elem of setb) { if (_difference.has(elem)) { _difference.delete(elem) } else { _difference.add(elem) } } return _difference } function difference(seta, setb) { let _difference = new set(seta) for (let elem of setb) { _difference.delete(elem) } return _difference } //
examples let seta = new set([1, 2, 3, 4]) let setb = new set([2, 3]) let setc = new set([3, 4, 5, 6]) issuperset(seta, setb) // => true union(seta, setc) // => set [1, 2, 3, 4, 5, 6] intersection(seta, setc) // => set [3, 4] symmetricdifference(seta, setc) // => set [1, 2, 5, 6] difference(seta, setc) // => set [1, 2] relation with array objects let myarray = ['...
SharedArrayBuffer() constructor - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples always use the new operator to create a sharedarraybuffer sharedarraybuffer constructors are required to be constructed with a new operator.
SharedArrayBuffer.prototype.byteLength - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
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.
SharedArrayBuffer.prototype.slice() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
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.s...
String.prototype[@@iterator]() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using [@@iterator]() var str = 'a\ud835\udc68'; var striter = str[symbol.iterator](); console.log(striter.next().value); // "a" console.log(striter.next().value); // "\ud835\udc68" using [@@iterator]() with for..of var str = 'a\ud835\udc68b\ud835\udc69c\ud835\udc6a'; for (var v of str) { console.log(v); } // "a" // "\ud835\udc68" // "b" // "\ud835\udc69" // "c" // "\ud835\udc6a" specifications specification ecmascript (ecma-262)the definition of 'string.prototype[@@iterator]()' in that specification.
String.prototype.charAt() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples displaying characters at different locations in a string the following example displays characters at different locations in the string "brave new world": var anystring = 'brave new world'; console.log("the character at index 0 is '" + anystring.charat() + "'"); // no index was provided, used 0 as default console.log("the character at index 0 is '" + anystring.charat(0) + "'"); consol...
String.prototype.codePointAt() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...coding#surrogate-formulae return (first - 0xd800) * 0x400 + second - 0xdc00 + 0x10000; } } return first; }; if (defineproperty) { defineproperty(string.prototype, 'codepointat', { 'value': codepointat, 'configurable': true, 'writable': true }); } else { string.prototype.codepointat = codepointat; } }()); }
examples using codepointat() 'abc'.codepointat(1) // 66 '\ud800\udc00'.codepointat(0) // 65536 'xyz'.codepointat(42) // undefined looping with codepointat() for (let codepoint of '\ud83d\udc0e\ud83d\udc71\u2764') { console.log(codepoint.codepointat(0).tostring(16)) } // '1f40e', '1f471', '2764' specifications specification ecmascript (ecma-262)the defini...
String.prototype.concat() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using concat() the following example combines strings into a new string.
String.prototype.endsWith() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...however, you can polyfill string.prototype.endswith() with the following snippet: if (!string.prototype.endswith) { string.prototype.endswith = function(search, this_len) { if (this_len === undefined || this_len > this.length) { this_len = this.length; } return this.substring(this_len - search.length, this_len) === search; }; }
examples using endswith() let str = 'to be, or not to be, that is the question.' console.log(str.endswith('question.')) // true console.log(str.endswith('to be')) // false console.log(str.endswith('to be', 19)) // true specifications specification ecmascript (ecma-262)the definition of 'string.prototype.endswith' in that specification.
String.fromCharCode() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using fromcharcode() bmp characters, in utf-16, use a single code unit: string.fromcharcode(65, 66, 67); // returns "abc" string.fromcharcode(0x2014); // returns "—" string.fromcharcode(0x12014); // also returns "—"; the digit 1 is truncated and ignored string.fromcharcode(8212); // also returns "—"; 8212 is the decimal form of 0x2014 complete utf 16 table.
String.fromCodePoint() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...th = 0; } } return result + stringfromcharcode.apply(null, codeunits); }; try { // ie 8 only supports `object.defineproperty` on dom elements object.defineproperty(string, "fromcodepoint", { "value": fromcodepoint, "configurable": true, "writable": true }); } catch(e) { string.fromcodepoint = fromcodepoint; } }(string.fromcharcode));
examples using fromcodepoint() valid input: string.fromcodepoint(42); // "*" string.fromcodepoint(65, 90); // "az" string.fromcodepoint(0x404); // "\u0404" == "Є" string.fromcodepoint(0x2f804); // "\ud87e\udc04" string.fromcodepoint(194564); // "\ud87e\udc04" string.fromcodepoint(0x1d306, 0x61, 0x1d307); // "\ud834\udf06a\ud834\udf07" invalid input: string.fromcodepoint('_'); // ...
String.prototype.includes() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... however, you can easily polyfill this method: if (!string.prototype.includes) { string.prototype.includes = function(search, start) { 'use strict'; if (search instanceof regexp) { throw typeerror('first argument must not be a regexp'); } if (start === undefined) { start = 0; } return this.indexof(search, start) !== -1; }; }
examples using includes() const str = 'to be, or not to be, that is the question.' console.log(str.includes('to be')) // true console.log(str.includes('question')) // true console.log(str.includes('nonexistent')) // false console.log(str.includes('to be', 1)) // false console.log(str.includes('to be')) // false console.log(str.includes('')) // true specifications ...
String.prototype.indexOf() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...therefore, when checking if a specific string exists within another string, the correct way to check would be: 'blue whale'.indexof('blue') !== -1 // true 'blue whale'.indexof('bloe') !== -1 // false ~('blue whale'.indexof('bloe')) // 0, which is falsy
examples using indexof() the following example uses indexof() to locate values in the string "brave new world".
String.prototype.lastIndexOf() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...for example, the following expression returns -1: 'blue whale, killer whale'.lastindexof('blue'); // returns -1
examples using indexof() and lastindexof() the following example uses indexof() and lastindexof() to locate values in the string "brave new world".
String.prototype.localeCompare() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using localecompare() // the letter "a" is before "c" yielding a negative value 'a'.localecompare('c'); // -2 or -1 (or some other negative value) // alphabetically the word "check" comes after "against" yielding a positive value 'check'.localecompare('against'); // 2 or 1 (or some other positive value) // "a" and "a" are equivalent yielding a neutral value of zero 'a'.localecompare('a'); // ...
String.prototype.match() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using match() in the following example, match() is used to find 'chapter' followed by 1 or more numeric characters followed by a decimal point and numeric character 0 or more times.
String.prototype.matchAll() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples regexp.exec() and matchall() prior to the addition of matchall to javascript, it was possible to use calls to regexp.exec (and regexes with the /g flag) in a loop to obtain all the matches: const regexp = regexp('foo[a-z]*','g'); const str = 'table football, foosball'; let match; while ((match = regexp.exec(str)) !== null) { console.log(`found ${match[0]} start=${match.index} end=${regexp.lastindex}.`); // expected output: "found football start=6...
String.prototype.normalize() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using normalize() // initial string // u+1e9b: latin small letter long s with dot above // u+0323: combining dot below let str = '\u1e9b\u0323'; // canonically-composed form (nfc) // u+1e9b: latin small letter long s with dot above // u+0323: combining dot below str.normalize('nfc'); // '\u1e9b\u0323' str.normalize(); // same as above // canonically-decomposed form (nfd) // u+017f: ...
String.prototype.padEnd() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using padend 'abc'.padend(10); // "abc " 'abc'.padend(10, "foo"); // "abcfoofoof" 'abc'.padend(6, "123456"); // "abc123" 'abc'.padend(1); // "abc" specifications specification ecmascript (ecma-262)the definition of 'string.prototype.padend' in that specification.
String.prototype.padStart() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples basic
examples 'abc'.padstart(10); // " abc" 'abc'.padstart(10, "foo"); // "foofoofabc" 'abc'.padstart(6,"123465"); // "123abc" 'abc'.padstart(8, "0"); // "00000abc" 'abc'.padstart(1); // "abc" fixed width string number conversion // javascript version of: (unsigned) // printf "%0*d" width num function leftfillnum(num, targetlength) { return num.tostring().pad...
String.prototype.repeat() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...dle // strings 1 << 28 chars or longer, so: if (str.length * count >= 1 << 28) throw new rangeerror('repeat count must not overflow maximum string size'); var maxcount = str.length * count; count = math.floor(math.log(count) / math.log(2)); while (count) { str += str; count--; } str += str.substring(0, maxcount - str.length); return str; } }
examples using repeat 'abc'.repeat(-1) // rangeerror 'abc'.repeat(0) // '' 'abc'.repeat(1) // 'abc' 'abc'.repeat(2) // 'abcabc' 'abc'.repeat(3.5) // 'abcabcabc' (count will be converted to integer) 'abc'.repeat(1/0) // rangeerror ({ tostring: () => 'abc', repeat: string.prototype.repeat }).repeat(2) // 'abcabc' (repeat() is a generic method) specifications specification ...
String.prototype.replace() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
..., if so, how many parenthesized submatches it specifies.) the following example will set newstring to 'abc - 12345 - #$*%': function replacer(match, p1, p2, p3, offset, string) { // p1 is nondigits, p2 digits, and p3 non-alphanumerics return [p1, p2, p3].join(' - '); } let newstring = 'abc12345#$*%'.replace(/([^\d]*)(\d*)([^\w]*)/, replacer); console.log(newstring); // abc - 12345 - #$*%
examples defining the regular expression in replace() in the following example, the regular expression is defined in replace() and includes the ignore case flag.
String.prototype.replaceAll() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... (the exact number of arguments depends on whether the first argument is a regexp object—and, if so, how many parenthesized submatches it specifies.)
examples using replaceall 'aabbcc'.replaceall('b', '.'); // 'aa..cc' non-global regex throws when using a regular expression search value, it must be global.
String.prototype.search() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using search() the following example searches a string with two different regex objects to show a successful search (positive value) vs.
String.prototype.slice() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using slice() to create a new string the following example uses slice() to create a new string.
String.prototype.split() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using split() when the string is empty, split() returns an array containing one empty string, rather than an empty array.
String.prototype.startsWith() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using startswith() //startswith let str = 'to be, or not to be, that is the question.' console.log(str.startswith('to be')) // true console.log(str.startswith('not to be')) // false console.log(str.startswith('not to be', 10)) // true specifications specification ecmascript (ecma-262)the definition of 'string.prototype.startswith' in that specification.
String.prototype.substr() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...this.length + start : start, length) } }(string.prototype.substr); }
examples using substr() var astring = 'mozilla'; console.log(astring.substr(0, 1)); // 'm' console.log(astring.substr(1, 0)); // '' console.log(astring.substr(-1, 1)); // 'a' console.log(astring.substr(1, -1)); // '' console.log(astring.substr(-3)); // 'lla' console.log(astring.substr(1)); // 'ozilla' console.log(astring.substr(-20, 2)); // 'mo' console.log(astring.substr(20, 2)); // ''...
String.prototype.toLocaleLowerCase() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using tolocalelowercase() 'alphabet'.tolocalelowercase(); // 'alphabet' '\u0130'.tolocalelowercase('tr') === 'i'; // true '\u0130'.tolocalelowercase('en-us') === 'i'; // false let locales = ['tr', 'tr', 'tr-tr', 'tr-u-co-search', 'tr-x-turkish']; '\u0130'.tolocalelowercase(locales) === 'i'; // true specifications specification ecmascript (ecma-262)the definition of 'st...
String.prototype.toLocaleUpperCase() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...the following can return false: x.tolocalelowercase() === x.tolocaleuppercase().tolocalelowercase()
examples using tolocaleuppercase() 'alphabet'.tolocaleuppercase(); // 'alphabet' 'gesäß'.tolocaleuppercase(); // 'gesÄss' 'i\u0307'.tolocaleuppercase('lt-lt'); // 'i' let locales = ['lt', 'lt', 'lt-lt', 'lt-u-co-phonebk', 'lt-x-lietuva']; 'i\u0307'.tolocaleuppercase(locales); // 'i' specifications specification ecmascript (ecma-262)the definition of 'string.prototype.tolocaleup...
String.prototype.toLowerCase() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using tolowercase() console.log('alphabet'.tolowercase()); // 'alphabet' specifications specification ecmascript (ecma-262)the definition of 'string.prototype.tolowercase' in that specification.
String.prototype.toUpperCase() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples basic usage console.log('alphabet'.touppercase()); // 'alphabet' conversion of non-string this values to strings this method will convert any non-string value to a string, when you set its this to a value that is not a string: const a = string.prototype.touppercase.call({ tostring: function tostring() { return 'abcdef'; } }); const b = string.prototype.touppercase.call(true); // p...
String.prototype.trim() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... if (!string.prototype.trim) { string.prototype.trim = function () { return this.replace(/^[\s\ufeff\xa0]+|[\s\ufeff\xa0]+$/g, ''); }; }
examples using trim() the following example displays the lowercase string 'foo': var orig = ' foo '; console.log(orig.trim()); // 'foo' // another example of .trim() removing whitespace from just one side.
String.prototype.trimEnd() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...in some engines this means: string.prototype.trimright.name === "trimend";
examples using trimend() the following example displays the lowercase string ' foo': var str = ' foo '; console.log(str.length); // 8 str = str.trimend(); console.log(str.length); // 6 console.log(str); // ' foo' specifications specification ecmascript (ecma-262)the definition of 'string.prototype.trimend' in that specification.
String.prototype.trimStart() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... return this.replace(r,'') } } })(proto,'trimstart'); })(window); /* es6: (w=>{ const string=w.string, proto=string.prototype; ((o,p)=>{ if(p in o?o[p]?false:true:true){ const r=/^\s+/; o[p]=o.trimleft||function(){ return this.replace(r,'') } } })(proto,'trimstart'); })(window); */
examples using trimstart() the following example displays the lowercase string 'foo ': var str = ' foo '; console.log(str.length); // 8 str = str.trimstart(); console.log(str.length); // 5 console.log(str); // 'foo ' specifications specification ecmascript (ecma-262)the definition of ' string.prototype.trimstart' in that specification.
Symbol() constructor - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples creating symbols to create a new primitive symbol, you write symbol() with an optional string as its description: let sym1 = symbol() let sym2 = symbol('foo') let sym3 = symbol('foo') the above code creates three new symbols.
Symbol.asyncIterator - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... property attributes of symbol.asynciterator writable no enumerable no configurable no
examples user-defined async iterables you can define your own async iterable by setting the [symbol.asynciterator] property on an object.
Symbol.for() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using symbol.for symbol.for('foo'); // create a new global symbol symbol.for('foo'); // retrieve the already created symbol // same global symbol, but not locally symbol.for('bar') === symbol.for('bar'); // true symbol('bar') === symbol('bar'); // false // the key is also used as the description var sym = symbol.for('mario'); sym.tostring(); // "symbol(mario)" to avoid name clashes with you...
Symbol.hasInstance - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... property attributes of symbol.hasinstance writable no enumerable no configurable no
examples custom instanceof behavior you could implement your custom instanceof behavior like this, for example: class myarray { static [symbol.hasinstance](instance) { return array.isarray(instance) } } console.log([] instanceof myarray); // true function myarray() { } object.defineproperty(myarray, symbol.hasinstance, { value: function(instance) { return array.isarray(instance); } }); console.log([] instanceof myarray); // true specifications specification ecmascript (ecma-262)the definition of 'symbol.hasinstance' in that specification.
Symbol.isConcatSpreadable - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... property attributes of symbol.isconcatspreadable writable no enumerable no configurable no
examples arrays by default, array.prototype.concat() spreads (flattens) arrays into its result: let alpha = ['a', 'b', 'c'], let numeric = [1, 2, 3] let alphanumeric = alpha.concat(numeric) console.log(alphanumeric) // result: ['a', 'b', 'c', 1, 2, 3] when setting symbol.isconcatspreadable to false, you can disable the default behavior: let alpha = ['a', 'b', 'c'], let numeric = [1, 2, 3] numeri...
Symbol.iterator - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... property attributes of symbol.iterator writable no enumerable no configurable no
examples user-defined iterables we can make our own iterables like this: var myiterable = {} myiterable[symbol.iterator] = function* () { yield 1; yield 2; yield 3; }; [...myiterable] // [1, 2, 3] or iterables can be defined directly inside a class or object using a computed property: class foo { *[symbol.iterator] () { yield 1; yield 2; yield 3; } } const someobj = { ...
Symbol.keyFor() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using keyfor var globalsym = symbol.for('foo'); // create a new global symbol symbol.keyfor(globalsym); // "foo" var localsym = symbol(); symbol.keyfor(localsym); // undefined // well-known symbols are not symbols registered // in the global symbol registry symbol.keyfor(symbol.iterator) // undefined specifications specification ecmascript (ecma-262)the definition of 'symbol.keyfor' in that specification.
Symbol.match - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... property attributes of symbol.match writable no enumerable no configurable no
examples disabling the isregexp check the following code will throw a typeerror: '/bar/'.startswith(/bar/); // throws typeerror, as /bar/ is a regular expression // and symbol.match is not modified.
Symbol.replace - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... property attributes of symbol.replace writable no enumerable no configurable no
examples using symbol.replace class customreplacer { constructor(value) { this.value = value; } [symbol.replace](string) { return string.replace(this.value, '#!@?'); } } console.log('football'.replace(new customreplacer('foo'))); // expected output: "#!@?tball" specifications specification ecmascript (ecma-262)the definition of 'symbol.replace' in that specification.
Symbol.search - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... property attributes of symbol.search writable no enumerable no configurable no
examples custom string search class caseinsensitivesearch { constructor(value) { this.value = value.tolowercase(); } [symbol.search](string) { return string.tolowercase().indexof(this.value); } } console.log('foobar'.search(new caseinsensitivesearch('bar'))); // expected output: 3 specifications specification ecmascript (ecma-262)the definition of 'symbol.search' in that specification.
Symbol.species - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... property attributes of symbol.species writable no enumerable no configurable no
examples using species you might want to return array objects in your derived array class myarray.
Symbol.split - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... property attributes of symbol.split writable no enumerable no configurable no
examples custom reverse split class reversesplit { [symbol.split](string) { const array = string.split(' '); return array.reverse(); } } console.log('another one bites the dust'.split(new reversesplit())); // expected output: [ "dust", "the", "bites", "one", "another" ] specifications specification ecmascript (ecma-262)the definition of 'symbol.split' in that specification.
Symbol.toPrimitive - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... property attributes of symbol.toprimitive writable no enumerable no configurable no
examples modifying primitive values converted from an object following example describes how symbol.toprimitive property can modify the primitive value converted from an object.
Symbol.prototype.toString() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... no string concatenation while you can call tostring() on symbols, you cannot use string concatenation with them: symbol('foo') + 'bar' // typeerror: can't convert symbol to string
examples using tostring symbol('desc').tostring() // "symbol(desc)" // well-known symbols symbol.iterator.tostring() // "symbol(symbol.iterator) // global symbols symbol.for('foo').tostring() // "symbol(foo)" specifications specification ecmascript (ecma-262)the definition of 'symbol.prototype.tostring' in that specification.
Symbol.toStringTag - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... property attributes of symbol.tostringtag writable no enumerable no configurable no
examples default tags object.prototype.tostring.call('foo'); // "[object string]" object.prototype.tostring.call([1, 2]); // "[object array]" object.prototype.tostring.call(3); // "[object number]" object.prototype.tostring.call(true); // "[object boolean]" object.prototype.tostring.call(undefined); // "[object undefined]" object.prototype.tostring.call(null); // "[object null]" // ...
Symbol.unscopables - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... property attributes of symbol.unscopables writable no enumerable no configurable no
examples scoping in with statements the following code works fine in es5 and below.
TypedArray.BYTES_PER_ELEMENT - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using bytes_per_element int8array.bytes_per_element; // 1 uint8array.bytes_per_element; // 1 uint8clampedarray.bytes_per_element; // 1 int16array.bytes_per_element; // 2 uint16array.bytes_per_element; // 2 int32array.bytes_per_element; // 4 uint32array.bytes_per_element; // 4 float32array.bytes_per_element; // 4 float64array.bytes_per_element; ...
TypedArray.prototype.buffer - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
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.byteLength - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
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) specif...
TypedArray.prototype.copyWithin() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using copywithin var buffer = new arraybuffer(8); var uint8 = new uint8array(buffer); uint8.set([1,2,3]); console.log(uint8); // uint8array [ 1, 2, 3, 0, 0, 0, 0, 0 ] uint8.copywithin(3,0,3); console.log(uint8); // uint8array [ 1, 2, 3, 1, 2, 3, 0, 0 ] specifications specification ecmascript (ecma-262)the definition of 'typedarray.prototype.copywithin' in that specifica...
TypedArray.prototype.entries() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples iteration using for...of loop var arr = new uint8array([10, 20, 30, 40, 50]); var earray = arr.entries(); // your browser must support for..of loop // and let-scoped variables in for loops for (let n of earray) { console.log(n); } alternative iteration var arr = new uint8array([10, 20, 30, 40, 50]); var earr = arr.entries(); console.log(earr.next().value); // [0, 10] console.log(earr.next().value); // [1, 20] console.log(earr.next().value); // [2, 30] console.log(earr.next().value); // [3, 40] console.log(earr.next().value); // [4, 50] specifications specification ecmascript (ecma-262)the definition of '%typedarray%.prototype.entries()' in that specification.
TypedArray.prototype.every() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples testing size of all typed array elements the following example tests whether all elements in the typed array are bigger than 10.
TypedArray.prototype.fill() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... // https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.fill if (!uint8array.prototype.fill) { uint8array.prototype.fill = array.prototype.fill; }
examples using fill new uint8array([1, 2, 3]).fill(4); // uint8array [4, 4, 4] new uint8array([1, 2, 3]).fill(4, 1); // uint8array [1, 4, 4] new uint8array([1, 2, 3]).fill(4, 1, 2); // uint8array [1, 4, 3] new uint8array([1, 2, 3]).fill(4, 1, 1); // uint8array [1, 2, 3] new uint8array([1, 2, 3]).fill(4, -3, -2); // uint8array [4, 2, 3] specifications specification ...
TypedArray.prototype.filter() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples filtering out all small values the following example uses filter() to create a filtered typed array that has all elements with values less than 10 removed.
TypedArray.prototype.find() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples find a prime number in a typed array the following example finds an element in the typed array that is a prime number (or returns undefined if there is no prime number).
TypedArray.prototype.findIndex() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...; if (thisarg === undefined) { // optimize for thisarg for (i in this) { if (evaluator(this[i], i, this)) { return i; } } return -1; } for (i in this) { if (evaluator.call(thisarg, this[i], i, this)) { return i; } } return -1; };
examples find the index of a prime number in a typed array the following example finds the index of an element in the typed array that is a prime number (or returns -1 if there is no prime number).
TypedArray.from() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...a = []; for(var i = 0; i < obj.length; i++) { copy_data.push(obj[i]); } copy_data = copy_data.map(func, thisobj); var typed_array = new this(copy_data.length); for(var i = 0; i < typed_array.length; i++) { typed_array[i] = copy_data[i]; } return typed_array; } })(); }
examples from an iterable object (set) const s = new set([1, 2, 3]); uint8array.from(s); // uint8array [ 1, 2, 3 ] from a string int16array.from('123'); // int16array [ 1, 2, 3 ] use with arrow function and map using an arrow function as the map function to manipulate the elements float32array.from([1, 2, 3], x => x + x); // float32array [ 2, 4, 6 ] generate a sequence of numbers uint8array.fr...
TypedArray.prototype.includes() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using includes var uint8 = new uint8array([1,2,3]); uint8.includes(2); // true uint8.includes(4); // false uint8.includes(3, 3); // false // nan handling (only true for float32 and float64) new uint8array([nan]).includes(nan); // false, since the nan passed to the constructor gets converted to 0 new float32array([nan]).includes(nan); // true; new float64array([nan]).includes(nan); // true; specifications specification ecmascript (ecma-262)the definition of 'typedarray.prototype.includes' in that specif...
TypedArray.prototype.indexOf() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using indexof var uint8 = new uint8array([2, 5, 9]); uint8.indexof(2); // 0 uint8.indexof(7); // -1 uint8.indexof(9, 2); // 2 uint8.indexof(2, -1); // -1 uint8.indexof(2, -3); // 0 specifications specification ecmascript (ecma-262)the definition of 'typedarray.prototype.indexof' in that specification.
TypedArray.prototype.join() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using join var uint8 = new uint8array([1,2,3]); uint8.join(); // '1,2,3' uint8.join(' / '); // '1 / 2 / 3' uint8.join(''); // '123' specifications specification ecmascript (ecma-262)the definition of 'typedarray.prototype.join' in that specification.
TypedArray.prototype.keys() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples iteration using for...of loop var arr = new uint8array([10, 20, 30, 40, 50]); var earray = arr.keys(); // your browser must support for..of loop // and let-scoped variables in for loops for (let n of earray) { console.log(n); } alternative iteration var arr = new uint8array([10, 20, 30, 40, 50]); var earr = arr.keys(); console.log(earr.next().value); // 0 console.log(earr.next().value); // 1 console.log(earr.next().value); // 2 console.log(earr.next().value); // 3 console.log(earr.next().value); // 4 specifications specification ecmascript (ecma-262)the definition of '%typedarray%.prototype.keys()' in that specification.
TypedArray.prototype.lastIndexOf() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using lastindexof var uint8 = new uint8array([2, 5, 9, 2]); uint8.lastindexof(2); // 3 uint8.lastindexof(7); // -1 uint8.lastindexof(2, 3); // 3 uint8.lastindexof(2, 2); // 0 uint8.lastindexof(2, -2); // 0 uint8.lastindexof(2, -1); // 3 specifications specification ecmascript (ecma-262)the definition of 'typedarray.prototype.lastindexof' in that specification.
TypedArray.prototype.length - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using the length property var buffer = new arraybuffer(8); var uint8 = new uint8array(buffer); uint8.length; // 8 (matches the length of the buffer) var uint8 = new uint8array(buffer, 1, 5); uint8.length; // 5 (as specified when constructing the uint8array) var uint8 = new uint8array(buffer, 2); uint8.length; // 6 (due to the offset of the constructed uint8array) specifications speci...
TypedArray.prototype.map() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples mapping a typed array to a typed array of square roots the following code takes a typed array and creates a new typed array containing the square roots of the numbers in the first typed array.
TypedArray.name - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using name int8array.name; // "int8array" uint8array.name; // "uint8array" uint8clampedarray.name; // "uint8clampedarray" int16array.name; // "int16array" uint16array.name; // "uint16array" int32array.name; // "int32array" uint32array.name; // "uint32array" float32array.name; // "float32array" float64array.name; // "float64array" specification...
TypedArray.of() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using of uint8array.of(1); // uint8array [ 1 ] int8array.of('1', '2', '3'); // int8array [ 1, 2, 3 ] float32array.of(1, 2, 3); // float32array [ 1, 2, 3 ] int16array.of(undefined); // int16array [ 0 ] specifications specification ecmascript (ecma-262)the definition of '%typedarray%.of' in that specification.
TypedArray.prototype.reduce() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples sum up all values within an array var total = new uint8array([0, 1, 2, 3]).reduce(function(a, b) { return a + b; }); // total == 6 specifications specification ecmascript (ecma-262)the definition of '%typedarray%.prototype.reduce' in that specification.
TypedArray.prototype.reverse() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using reverse var uint8 = new uint8array([1, 2, 3]); uint8.reverse(); console.log(uint8); // uint8array [3, 2, 1] specifications specification ecmascript (ecma-262)the definition of 'typedarray.prototype.reverse' in that specification.
TypedArray.prototype.set() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using set() var buffer = new arraybuffer(8); var uint8 = new uint8array(buffer); uint8.set([1, 2, 3], 3); console.log(uint8); // uint8array [ 0, 0, 0, 1, 2, 3, 0, 0 ] specifications specification ecmascript (ecma-262)the definition of 'typedarray.prototype.set' in that specification.
TypedArray.prototype.slice() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples return a portion of an existing typed array const uint8 = new uint8array([1,2,3]); uint8.slice(1); // uint8array [ 2, 3 ] uint8.slice(2); // uint8array [ 3 ] uint8.slice(-2); // uint8array [ 2, 3 ] uint8.slice(0,1); // uint8array [ 1 ] specifications specification ecmascript (ecma-262)the definition of '%typedarray%.prototype.slice' in that specification.
TypedArray.prototype.some() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples testing size of all typed array elements the following example tests whether any element in the typed array is bigger than 10.
TypedArray.prototype.sort() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using sort for more
examples, see also the array.prototype.sort() method.
TypedArray.prototype.subarray() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using the subarray method var buffer = new arraybuffer(8); var uint8 = new uint8array(buffer); uint8.set([1,2,3]); console.log(uint8); // uint8array [ 1, 2, 3, 0, 0, 0, 0, 0 ] var sub = uint8.subarray(0,4); console.log(sub); // uint8array [ 1, 2, 3, 0 ] specifications specification ecmascript (ecma-262)the definition of 'typedarray.prototype.subarray' in that specifica...
TypedArray.prototype.toString() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples the typedarray objects override the tostring method of object.
TypedArray.prototype.values() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples iteration using for...of loop var arr = new uint8array([10, 20, 30, 40, 50]); var earray = arr.values(); // your browser must support for..of loop // and let-scoped variables in for loops for (let n of earray) { console.log(n); } alternative iteration var arr = new uint8array([10, 20, 30, 40, 50]); var earr = arr.values(); console.log(earr.next().value); // 10 console.log(earr.next().value); // 20 console.log(earr.next().value); // 30 console.log(earr.next().value); // 40 console.log(earr.next().value); // 50 specifications specification ecmascript (ecma-262)the definition of '%typedarray%.prototype.values()' in that specification.
TypedArray - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples new is required starting with ecmascript 2015, typedarray constructors must be constructed with the new operator.
WeakMap.prototype.delete() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using the delete method var wm = new weakmap(); wm.set(window, 'foo'); wm.delete(window); // returns true.
WeakMap.prototype.get() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using the get method var wm = new weakmap(); wm.set(window, 'foo'); wm.get(window); // returns "foo".
WeakMap.prototype.has() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using the has method var wm = new weakmap(); wm.set(window, 'foo'); wm.has(window); // returns true wm.has('baz'); // returns false specifications specification ecmascript (ecma-262)the definition of 'weakmap.prototype.has' in that specification.
WeakMap.prototype.set() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using the set method var wm = new weakmap(); var obj = {}; // add new elements to the weakmap wm.set(obj, 'foo').set(window, 'bar'); // chainable // update an element in the weakmap wm.set(obj, 'baz'); specifications specification ecmascript (ecma-262)the definition of 'weakmap.prototype.set' in that specification.
WeakSet.prototype.add() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using add var ws = new weakset(); ws.add(window); // add the window object to the weakset ws.has(window); // true // weakset only takes objects as arguments ws.add(1); // results in "typeerror: invalid value used in weak set" in chrome // and "typeerror: 1 is not a non-null object" in firefox specifications specification ecmascript (ecma-262)the definition of 'weakset.prototype.add' in that specification.
WeakSet.prototype.delete() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using the delete method var ws = new weakset(); var obj = {}; ws.add(window); ws.delete(obj); // returns false.
WeakSet.prototype.has() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using the has method var ws = new weakset(); var obj = {}; ws.add(window); myset.has(window); // returns true myset.has(obj); // returns false specifications specification ecmascript (ecma-262)the definition of 'weakset.prototype.has' in that specification.
decodeURI() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples decoding a cyrillic url decodeuri('https://developer.mozilla.org/ru/docs/javascript_%d1%88%d0%b5%d0%bb%d0%bb%d1%8b'); // "https://developer.mozilla.org/ru/docs/javascript_шеллы" catching errors try { var a = decodeuri('%e0%a4%a'); } catch(e) { console.error(e); } // urierror: malformed uri sequence specifications specification ecmascript (ecma-262)the defini...
decodeURIComponent() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples decoding a cyrillic url component decodeuricomponent('javascript_%d1%88%d0%b5%d0%bb%d0%bb%d1%8b'); // "javascript_шеллы" catching errors try { var a = decodeuricomponent('%e0%a4%a'); } catch(e) { console.error(e); } // urierror: malformed uri sequence decoding query parameters from a url decodeuricomponent cannot be used directly to parse query parameters from a url.
encodeURI() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...~ * ' ( ) #
examples encodeuri vs encodeuricomponent encodeuri() differs from encodeuricomponent() as follows: var set1 = ";,/?:@&=+$#"; // reserved characters var set2 = "-_.!~*'()"; // unreserved marks var set3 = "abc abc 123"; // alphanumeric characters + space console.log(encodeuri(set1)); // ;,/?:@&=+$# console.log(encodeuri(set2)); // -_.!~*'() console.log(encodeuri(set3)); // abc%20abc%20123 (the space g...
encodeURIComponent() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... to be more stringent in adhering to rfc 3986 (which reserves !, ', (, ), and *), even though these characters have no formalized uri delimiting uses, the following can be safely used: function fixedencodeuricomponent(str) { return encodeuricomponent(str).replace(/[!'()*]/g, function(c) { return '%' + c.charcodeat(0).tostring(16); }); }
examples encoding for content-disposition and link headers the following example provides the special encoding required within utf-8 content-disposition and link server response header parameters (e.g., utf-8 filenames): var filename = 'my file(2).txt'; var header = "content-disposition: attachment; filename*=utf-8''" + encoderfc5987valuechars(filename); console.log(header); // logs "cont...
eval() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using eval in the following code, both of the statements containing eval() return 42.
globalThis - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples search for the global across environments prior to globalthis, the only reliable cross-platform way to get the global object for an environment was function('return this')().
isFinite() - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using isfinite isfinite(infinity); // false isfinite(nan); // false isfinite(-infinity); // false isfinite(0); // true isfinite(2e64); // true isfinite(910); // true isfinite(null); // true, would've been false with the // more robust number.isfinite(null) isfinite('0'); // true, would've been false with the // mo...
null - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...it is not defined and has never been initialized: foo; //referenceerror: foo is not defined // foo is known to exist now but it has no type or value: var foo = null; foo; //null
examples difference between null and undefined when checking for null or undefined, beware of the differences between equality (==) and identity (===) operators, as the former performs type-conversion.
undefined - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... // don't do this // logs "foo string" (function() { var undefined = 'foo'; console.log(undefined, typeof undefined); })(); // logs "foo string" (function(undefined) { console.log(undefined, typeof undefined); })('foo');
examples strict equality and undefined you can use undefined and the strict equality and inequality operators to determine whether a variable has a value.
Addition (+) - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... syntax operator: x + y
examples numeric addition // number + number -> addition 1 + 2 // 3 // boolean + number -> addition true + 1 // 2 // boolean + boolean -> addition false + false // 0 string concatenation // string + string -> concatenation 'foo' + 'bar' // "foobar" // number + string -> concatenation 5 + 'foo' // "5foo" // string + boolean -> concatenation 'foo' + false // "foofalse" specifications specification ecmascript (ecma-262)the definition of 'addition operator' in that specification.
Addition assignment (+=) - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... syntax operator: x += y meaning: x = x + y
examples using addition assignment // assuming the following variables // foo = 'foo' // bar = 5 // baz = true // number + number -> addition bar += 2 // 7 // boolean + number -> addition baz += 1 // 2 // boolean + boolean -> addition baz += false // 1 // number + string -> concatenation bar += 'foo' // "5foo" // string + boolean -> concatenation foo += false // "foofalse" // string + string -> concatenation foo += 'bar' // "foobar" specifications specification ecmascript (ecma-262)the definition of 'assignment operators' in that specification.
Assignment (=) - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... syntax operator: x = y
examples simple assignment and chaining // assuming the following variables // x = 5 // y = 10 // z = 25 x = y // x is 10 x = y = z // x, y and z are all 25 specifications specification ecmascript (ecma-262)the definition of 'assignment operators' in that specification.
Bitwise AND (&) - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using bitwise and // 5: 00000000000000000000000000000101 // 2: 00000000000000000000000000000010 5 & 2; // 0 specifications specification ecmascript (ecma-262)the definition of 'bitwise and expression' in that specification.
Bitwise AND assignment (&=) - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... syntax operator: x &= y meaning: x = x & y
examples using bitwise and assignment let a = 5; // 5: 00000000000000000000000000000101 // 2: 00000000000000000000000000000010 a &= 2; // 0 specifications specification ecmascript (ecma-262)the definition of 'assignment operators' in that specification.
Bitwise NOT (~) - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using bitwise not ~0; // -1 ~-1; // 0 ~1; // -2 specifications specification ecmascript (ecma-262)the definition of 'unary not expression' in that specification.
Bitwise OR (|) - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using bitwise or // 9 (00000000000000000000000000001001) // 14 (00000000000000000000000000001110) 14 | 9; // 15 (00000000000000000000000000001111) specifications specification ecmascript (ecma-262)the definition of 'bitwise or expression' in that specification.
Bitwise OR assignment (|=) - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... syntax operator: x |= y meaning: x = x | y
examples using bitwise or assignment let a = 5; a |= 2; // 7 // 5: 00000000000000000000000000000101 // 2: 00000000000000000000000000000010 // ----------------------------------- // 7: 00000000000000000000000000000111 specifications specification ecmascript (ecma-262)the definition of 'assignment operators' in that specification.
Bitwise XOR (^) - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using bitwise xor // 9 (00000000000000000000000000001001) // 14 (00000000000000000000000000001110) 14 ^ 9; // 7 (00000000000000000000000000000111) specifications specification ecmascript (ecma-262)the definition of 'bitwise xor expression' in that specification.
Bitwise XOR assignment (^=) - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... syntax operator: x ^= y meaning: x = x ^ y
examples using bitwise xor assignment let a = 5; // 00000000000000000000000000000101 a ^= 3; // 00000000000000000000000000000011 console.log(a); // 00000000000000000000000000000110 // 6 let b = 5; // 00000000000000000000000000000101 b ^= 0; // 00000000000000000000000000000000 console.log(b); // 00000000000000000000000000000101 // 5 specifications specification ecmascript (ecma-262)the definition of 'assignment operators' in that specification.
Comma operator (,) - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples if a is a 2-dimensional array with 10 elements on each side, the following code uses the comma operator to increment i and decrement j at once.
Conditional (ternary) operator - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples a simple example var age = 26; var beverage = (age >= 21) ?
Decrement (--) - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples postfix decrement let x = 3; y = x--; // y = 3 // x = 2 prefix decrement let a = 2; b = --a; // a = 1 // b = 1 specifications specification ecmascript (ecma-262)the definition of 'decrement operator' in that specification.
Destructuring assignment - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples array destructuring basic variable assignment const foo = ['one', 'two', 'three']; const [red, yellow, green] = foo; console.log(red); // "one" console.log(yellow); // "two" console.log(green); // "three" assignment separate from declaration a variable can be assigned its value via destructuring separate from the variable's declaration.
Division (/) - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... syntax operator: x / y
examples basic division 1 / 2 // 0.5 math.floor(3 / 2) // 1 1.0 / 2.0 // 0.5 division by zero 2.0 / 0 // infinity 2.0 / 0.0 // infinity, because 0.0 === 0 2.0 / -0.0 // -infinity specifications specification ecmascript (ecma-262)the definition of 'division operator' in that specification.
Division assignment (/=) - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... syntax operator: x /= y meaning: x = x / y
examples using division assignment // assuming the following variable // bar = 5 bar /= 2 // 2.5 bar /= 'foo' // nan bar /= 0 // infinity specifications specification ecmascript (ecma-262)the definition of 'assignment operators' in that specification.
Equality (==) - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples comparison with no type conversion 1 == 1; // true "hello" == "hello"; // true comparison with type conversion "1" == 1; // true 1 == "1"; // true 0 == false; // true 0 == null; // false 0 == undefined; // false 0 == !!null; // true, look at logical not operator 0 == !!undefined; // true, look at logical not operato...
Exponentiation (**) - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples basic exponentiation 2 ** 3 // 8 3 ** 2 // 9 3 ** 2.5 // 15.588457268119896 10 ** -1 // 0.1 nan ** 2 // nan associativity 2 ** 3 ** 2 // 512 2 ** (3 ** 2) // 512 (2 ** 3) ** 2 // 64 usage with unary operators to invert the sign of the result of an exponentiation expression: -(2 ** 2) // -4 to force the base of an exponentiation expression to be a negative number: (-2) ** 2 // 4 ...
Exponentiation assignment (**=) - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... syntax operator: x **= y meaning: x = x ** y
examples using exponentiation assignment // assuming the following variable // bar = 5 bar **= 2 // 25 bar **= 'foo' // nan specifications specification ecmascript (ecma-262)the definition of 'assignment operators' in that specification.
Greater than (>) - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples string to string comparison console.log("a" > "b"); // false console.log("a" > "a"); // false console.log("a" > "3"); // true string to number comparison console.log("5" > 3); // true console.log("3" > 3); // false console.log("3" > 5); // false console.log("hello" > 5); // false console.log(5 > "hello"); // false console.log("5" > 3n); // true console.log("3" > 5n); // false number to number comparison console.log(5 > 3); // true console.log(3 > 3); // false console.log(3 > 5); // false ...
Greater than or equal (>=) - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples string to string comparison console.log("a" >= "b"); // false console.log("a" >= "a"); // true console.log("a" >= "3"); // true string to number comparison console.log("5" >= 3); // true console.log("3" >= 3); // true console.log("3" >= 5); // false console.log("hello" >= 5); // false console.log(5 >= "hello"); // false number to number comparison console.log(5 >= 3); // true console.log(3 >= 3); // true console.log(3 >= 5); // false number to bigint comparison console.log(5n >= 3); // true console.log(3 >= 3n); // tru...
Grouping operator ( ) - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using the grouping operator overriding multiplication and division first, then addition and subtraction to evaluate addition first.
Increment (++) - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples postfix increment let x = 3; y = x++; // y = 3 // x = 4 prefix increment let a = 2; b = ++a; // a = 3 // b = 3 specifications specification ecmascript (ecma-262)the definition of 'increment operator' in that specification.
Inequality (!=) - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... like the equality operator, the inequality operator will attempt to convert and compare operands of different types: 3 != "3"; // false to prevent this, and require that different types are considered to be different, use the strict inequality operator instead: 3 !== "3"; // true
examples comparison with no type conversion 1 != 2; // true "hello" != "hola"; // true 1 != 1; // false "hello" != "hello"; // false comparison with type conversion "1" != 1; // false 1 != "1"; // false 0 != false; // false 0 != null; // true 0 != undefined; // true 0 != !!null; // false, look at logical not oper...
Left shift (<<) - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using left shift 9 << 3; // 72 // 9 * (2 ** 3) = 9 * (8) = 72 specifications specification ecmascript (ecma-262)the definition of 'bitwise shift operators' in that specification.
Left shift assignment (<<=) - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... syntax operator: x <<= y meaning: x = x << y
examples using left shift assignment let a = 5; // 00000000000000000000000000000101 bar <<= 2; // 20 // 00000000000000000000000000010100 specifications specification ecmascript (ecma-262)the definition of 'assignment operators' in that specification.
Less than (<) - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples string to string comparison console.log("a" < "b"); // true console.log("a" < "a"); // false console.log("a" < "3"); // false string to number comparison console.log("5" < 3); // false console.log("3" < 3); // false console.log("3" < 5); // true console.log("hello" < 5); // false console.log(5 < "hello"); // false console.log("5" < 3...
Less than or equal (<=) - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples string to string comparison console.log("a" <= "b"); // true console.log("a" <= "a"); // true console.log("a" <= "3"); // false string to number comparison console.log("5" <= 3); // false console.log("3" <= 3); // true console.log("3" <= 5); // true console.log("hello" <= 5); // false console.log(5 <= "hello"); // false number to number comparison console.log(5 <= 3); // false console.log(3 <= 3); // true console.log(3 <= 5); // true number to bigint comparison console.log(5n <= 3); // false console.log(3 <= 3n); // tr...
Logical AND assignment (&&=) - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... logical and assignment short-circuits as well meaning that x &&= y is equivalent to: x && (x = y); and not equivalent to the following which would always perform an assignment: x = x && y;
examples using logical and assignment let x = 0; let y = 1; x &&= 0; // 0 x &&= 1; // 0 y &&= 1; // 1 y &&= 0; // 0 specifications specification logical assignment operatorsthe definition of 'assignment operators' in that specification.
Logical OR assignment (||=) - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
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.
Logical nullish assignment (??=) - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...y;
examples using logical nullish assignment function config(options) { options.duration ??= 100; options.speed ??= 25; return options; } config({ duration: 125 }); // { duration: 125, speed: 25 } config({}); // { duration: 100, speed: 25 } specifications specification logical assignment operatorsthe definition of 'assignment operators' in that specification.
Multiplication (*) - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... syntax operator: x * y
examples multiplication using numbers 2 * 2 // 4 -2 * 2 // -4 multiplication with infinity infinity * 0 // nan infinity * infinity // infinity multiplication with non-numbers 'foo' * 2 // nan specifications specification ecmascript (ecma-262)the definition of 'multiplication operator' in that specification.
Multiplication assignment (*=) - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... syntax operator: x *= y meaning: x = x * y
examples using multiplication assignment // assuming the following variable // bar = 5 bar *= 2 // 10 bar *= 'foo' // nan specifications specification ecmascript (ecma-262)the definition of 'assignment operators' in that specification.
Optional chaining (?.) - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...chaining operator when accessing properties with an expression using the bracket notation of the property accessor: let nestedprop = obj?.['prop' + 'name']; optional chaining not valid on the left-hand side of an assignment let object = {}; object?.property = 1; // uncaught syntaxerror: invalid left-hand side in assignment array item access with optional chaining let arrayitem = arr?.[42];
examples basic example this example looks for the value of the name property for the member bar in a map when there is no such member.
Property accessors - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples bracket notation vs.
Remainder (%) - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... syntax operator: var1 % var2
examples remainder with positive dividend 12 % 5 // 2 1 % -2 // 1 1 % 2 // 1 2 % 3 // 2 5.5 % 2 // 1.5 remainder with negative dividend -12 % 5 // -2 -1 % 2 // -1 -4 % 2 // -0 remainder with nan nan % 2 // nan specifications specification ecmascript (ecma-262)the definition of 'remainder operator' in that specification.
Remainder assignment (%=) - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... syntax operator: x %= y meaning: x = x % y
examples using remainder assignment // assuming the following variable // bar = 5 bar %= 2 // 1 bar %= 'foo' // nan bar %= 0 // nan specifications specification ecmascript (ecma-262)the definition of 'assignment operators' in that specification.
Right shift (>>) - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... -9 (base 10): 11111111111111111111111111110111 (base 2) -------------------------------- -9 >> 2 (base 10): 11111111111111111111111111111101 (base 2) = -3 (base 10)
examples using right shift 9 >> 2; // 2 -9 >> 2; // -3 specifications specification ecmascript (ecma-262)the definition of 'bitwise shift operators' in that specification.
Right shift assignment (>>=) - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... syntax operator: x >>= y meaning: x = x >> y
examples using right shift assignment let a = 5; // (00000000000000000000000000000101) a >>= 2; // 1 (00000000000000000000000000000001) let b = -5; // (-00000000000000000000000000000101) b >>= 2; // -2 (-00000000000000000000000000000010) specifications specification ecmascript (ecma-262)the definition of 'assignment operators' in that specification.
Spread syntax (...) - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples spread in function calls replace apply() it is common to use function.prototype.apply() in cases where you want to use the elements of an array as arguments to a function.
Strict equality (===) - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples comparing operands of the same type console.log("hello" === "hello"); // true console.log("hello" === "hola"); // false console.log(3 === 3); // true console.log(3 === 4); // false console.log(true === true); // true console.log(true === false); // false console.log(null === null); // true comparing operands of different types console...
Strict inequality (!==) - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... like the strict equality operator, the strict inequality operator will always consider operands of different types to be different: 3 !== "3"; // true
examples comparing operands of the same type console.log("hello" !== "hello"); // false console.log("hello" !== "hola"); // true console.log(3 !== 3); // false console.log(3 !== 4); // true console.log(true !== true); // false console.log(true !== false); // true console.log(null !== null); // false comparing operands of different types consol...
Subtraction (-) - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... syntax operator: x - y
examples subtraction with numbers 5 - 3 // 2 3 - 5 // -2 subtraction with non-numbers 'foo' - 3 // nan specifications specification ecmascript (ecma-262)the definition of 'subtraction operator' in that specification.
Subtraction assignment (-=) - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... syntax operator: x -= y meaning: x = x - y
examples using subtraction assignment // assuming the following variable // bar = 5 bar -= 2 // 3 bar -= 'foo' // nan specifications specification ecmascript (ecma-262)the definition of 'assignment operators' in that specification.
Unary negation (-) - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... syntax operator: -x
examples negating numbers const x = 3; const y = -x; // y = -3 // x = 3 negating non-numbers the unary negation operator can convert a non-number into a number.
Unary plus (+) - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples usage with numbers const x = 1; const y = -1; console.log(+x); // 1 console.log(+y); // -1 usage with non-numbers +true // 1 +false // 0 +null // 0 +function(val){ return val } // nan +1n // throws typeerror: cannot convert bigint value to number specifications specification ecmascript (ecma-262)the definition of 'unary plus operator' in that specification.
Unsigned right shift (>>>) - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... -9 (base 10): 11111111111111111111111111110111 (base 2) -------------------------------- -9 >>> 2 (base 10): 00111111111111111111111111111101 (base 2) = 1073741821 (base 10)
examples using unsigned right shift 9 >>> 2; // 2 -9 >>> 2; // 1073741821 specifications specification ecmascript (ecma-262)the definition of 'bitwise shift operators' in that specification.
Unsigned right shift assignment (>>>=) - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... syntax operator: x >>>= y meaning: x = x >>> y
examples using unsigned right shift assignment let a = 5; // (00000000000000000000000000000101) a >>>= 2; // 1 (00000000000000000000000000000001) let b = -5; // (-00000000000000000000000000000101) b >>>= 2; // 1073741822 (00111111111111111111111111111110) specifications specification ecmascript (ecma-262)the definition of 'assignment operators' in that specification.
class expression - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... 'use strict'; let foo = class {}; // constructor property is optional foo = class {}; // re-declaration is allowed typeof foo; // returns "function" typeof class {}; // returns "function" foo instanceof object; // true foo instanceof function; // true class foo {} // throws syntaxerror (class declarations do not allow re-declaration)
examples a simple class expression this is just a simple anonymous class expression which you can refer to using the variable foo.
delete operator - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples // creates the property adminname on the global scope.
function* expression - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using function* the following example defines an unnamed generator function and assigns it to x.
Function expression - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... var foo = function() {} foo.name // "foo" var foo2 = foo foo2.name // "foo" var bar = function baz() {} bar.name // "baz" console.log(foo === foo2); // true console.log(typeof baz); // undefined console.log(bar === baz); // false (errors because baz == undefined)
examples creating an unnamed function the following example defines an unnamed function and assigns it to x.
in operator - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples basic usage the following
examples show some uses of the in operator.
instanceof - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples demonstrating that string and date are of type object and exceptional cases the following code uses instanceof to demonstrate that string and date objects are also of type object (they are derived from object).
new operator - JavaScript
see the
examples below.
...
examples object type and object instance suppose you want to create an object type for cars.
new.target - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples new.target in function calls in normal function calls (as opposed to constructor function calls), new.target is undefined.
typeof - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples basic usage // numbers typeof 37 === 'number'; typeof 3.14 === 'number'; typeof(42) === 'number'; typeof math.ln2 === 'number'; typeof infinity === 'number'; typeof nan === 'number'; // despite being "not-a-number" typeof number('1') === 'number'; // number tries to parse things into numbers typeof number('shoe') === 'number'; // including values that cannot be type coerced to a number ...
void operator - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... 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.
yield* - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples delegating to another generator in following code, values yielded by g1() are returned from next() calls just like those which are yielded by g2().
yield - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using yield the following code is the declaration of an example generator function.
empty - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples empty loop body the empty statement is sometimes used with loop statements.
async function - JavaScript
if you'd like to contribute to the interactive demo project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples async functions and execution order function resolveafter2seconds() { console.log("starting slow promise") return new promise(resolve => { settimeout(function() { resolve("slow") console.log("slow promise is done") }, 2000) }) } function resolveafter1second() { console.log("starting fast promise") return new promise(resolve => { settimeout(function() { r...
block - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples block scoping rules with var or function declaration in non-strict mode variables declared with var or created by function declarations in non-strict mode do not have block scope.
class - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples a simple class declaration in the following example, we first define a class named polygon, then extend it to create a class named square.
const - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples basic const usage constants can be declared with uppercase or lowercase, but a common convention is to use all-uppercase letters.
continue - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using continue with while the following example shows a while loop that has a continue statement that executes when the value of i is 3.
do...while - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using do...while in the following example, the do...while loop iterates at least once and reiterates until i is no longer less than 5.
for...in - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using for...in the for...in loop below iterates over all of the object's enumerable, non-symbol properties and logs a string of the property names and their values.
for...of - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples iterating over an array const iterable = [10, 20, 30]; for (const value of iterable) { console.log(value); } // 10 // 20 // 30 you can use let instead of const too, if you reassign the variable inside the block.
for - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using for the following for statement starts by declaring the variable i and initializing it to 0.
function* - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples simple example function* idmaker() { var index = 0; while (true) yield index++; } var gen = idmaker(); console.log(gen.next().value); // 0 console.log(gen.next().value); // 1 console.log(gen.next().value); // 2 console.log(gen.next().value); // 3 // ...
function declaration - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...you can use the function before you declared it: hoisted(); // logs "foo" function hoisted() { console.log('foo'); } note that function expressions are not hoisted: nothoisted(); // typeerror: nothoisted is not a function var nothoisted = function() { console.log('bar'); };
examples using function the following code declares a function that returns the total amount of sales, when given the number of units sold of products a, b, and c.
if...else - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...for example: var b = new boolean(false); if (b) // this condition is truthy
examples using if...else if (cipher_char === from_char) { result = result + to_char; x++; } else { result = result + clear_char; } using else if note that there is no elseif syntax in javascript.
import - JavaScript
below are
examples to clarify the syntax.
... let module = await import('/modules/my-module.js');
examples standard import the code below shows how to import from a secondary module to assist in processing an ajax json request.
label - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using a labeled continue with for loops var i, j; loop1: for (i = 0; i < 3; i++) { //the first for statement is labeled "loop1" loop2: for (j = 0; j < 3; j++) { //the second for statement is labeled "loop2" if (i === 1 && j === 1) { continue loop1; } console.log('i = ' + i + ', j = ' + j); } } // output is: // "i = 0, j = 0" // "i = 0, j = 1" // ...
let - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples scoping rules variables declared by let have their scope in the block for which they are defined, as well as in any contained sub-blocks.
return - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... 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
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using switch in the following example, if expr evaluates to bananas, the program matches the value with case case 'bananas' and executes the associated statement.
throw - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples throw an object you can specify an object when you throw an exception.
try...catch - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
... openmyfile(); try { // tie up a resource writemyfile(thedata); } finally { closemyfile(); // always close the resource }
examples nested try-blocks first, let's see what happens with this: try { try { throw new error('oops'); } finally { console.log('finally'); } } catch (ex) { console.error('outer', ex.message); } // output: // "finally" // "outer" "oops" now, if we already caught the exception in the inner try-block by adding a catch-block try { try { throw new error('oops'); } catch (ex...
var - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...the value will be indeed assigned when the assignment statement is reached: function do_something() { console.log(bar); // undefined var bar = 111; console.log(bar); // 111 } // ...is implicitly understood as: function do_something() { var bar; console.log(bar); // undefined bar = 111; console.log(bar); // 111 }
examples declaring and initializing two variables var a = 0, b = 0; assigning two variables with single string value var a = 'a'; var b = a; // ...is equivalent to: var a, b = a = 'a'; be mindful of the order: var x = y, y = 'a'; console.log(x + y); // undefineda here, x and y are declared before any code is executed, but the assignments occur later.
while - JavaScript
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
...
examples using while the following while loop iterates as long as n is less than three.
JavaScript typed arrays - JavaScript
web apis using typed arrays these are some
examples of apis that make use of typed arrays; there are others, and more are being added all the time.
...
examples using views with buffers first of all, we will need to create a buffer, here with a fixed length of 16-bytes: let buffer = new arraybuffer(16); at this point, we have a chunk of memory whose bytes are all pre-initialized to 0.
<mmultiscripts> - MathML
see the
examples section for a correct usage.
...
examples using <mprescripts/> sample rendering: rendering in your browser: x d c b a <math> <mmultiscripts> <mi>x</mi> <!-- base expression --> <mi>d</mi> <!-- postsubscript --> <mi>c</mi> <!-- postsuperscript --> <mprescripts /> <mi>b</mi> <!-- presubscript --> <mi>a</mi> <!-- presuperscript --> </mmultiscript...
MathML
here you'll find links to documentation,
examples, and tools to help you work with this powerful technology.
... mathml
examples mathml samples and
examples to help you understand how it works.
Add to Home screen - Progressive web apps (PWAs)
if you have firefox for android available, use it to navigate to our demo at https://mdn.github.io/pwa-
examples/a2hs/.
...hey, at least it isn't cats.", "display": "fullscreen", "icons": [ { "src": "icon/fox-icon.png", "sizes": "192x192", "type": "image/png" } ], "name": "awesome fox pictures", "short_name": "foxes", "start_url": "/pwa-
examples/a2hs/index.html" } appropriate icon as shown in the above manifest listing, we are including a 192 x 192 px icon for use in our app.
spreadMethod - SVG: Scalable Vector Graphics
examples of spreadmethod with linear gradients svg <svg width="220" height="150" xmlns="http://www.w3.org/2000/svg"> <defs> <lineargradient id="padgradient" x1="33%" x2="67%"> <stop offset="0%" stop-color="fuchsia"/> <stop offset="100%" stop-color="orange"/> </lineargradient> <lineargradient id="reflectgradient" spreadmethod="reflect" x1...
...
examples of spreadmethod with radial gradients svg <svg width="340" height="120" xmlns="http://www.w3.org/2000/svg"> <defs> <radialgradient id="radialpadgradient" cx="75%" cy="25%" r="33%" fx="64%" fy="18%" fr="17%"> <stop offset="0%" stop-color="fuchsia"/> <stop offset="100%" stop-color="orange"/> </radialgradient> <radialgradient id="r...
SVG: Scalable Vector Graphics
other resources: xml, css, dom, canvas
examples google maps (route overlay) & docs (spreadsheet charting) svg bubble menus svg authoring guidelines an overview of the mozilla svg project frequently asked questions regarding svg and mozilla svg as an image svg animation with smil svg art gallery animation and interactions like html, svg has a document model (dom) and events, and is accessible from javascript.
... some real eye-candy svg at svg-wow.org firefox extension (grafox) to add a subset of smil animation support interactive photos manipulation html transformations using svg's foreignobject mapping, charting, games & 3d experiments while a little svg can go a long way to enhanced web content, here are some
examples of heavy svg usage.
Mixed content - Web security
active content
examples this section lists some types of http requests which are considered active content: <script> (src attribute) <link> (href attribute) (this includes css stylesheets) <iframe> (src attribute) xmlhttprequest requests fetch() requests all cases in css where a <url> value is used (@font-face, cursor, background-image, and so forth).
...some common
examples of mixed content include javascript files, stylesheets, images, videos, and other media.
Using custom elements - Web Components
to create one of these, you have to specify which element they extend (as implied in the
examples above), and they are used by writing out the basic element but specifying the name of the custom element in the is attribute (or property).
... working through some simple
examples at this point, let's go through some more simple
examples to show you how custom elements are created in more detail.
XPath snippets - XPath
this article provides some xpath code snippets—simple
examples of how to a few simple utility functions based on standard interfaces from the dom level 3 xpath specification that expose xpath functionality to javascript code.
...here are some
examples.
PI Parameters - XSLT: Extensible Stylesheet Language Transformations
examples set the parameter 'color' to the string 'red': <?xslt-param name="color" value="red"?> set the parameter 'columns' to the number 2: <?xslt-param name="columns" select="2"?> set the parameter 'books' to a nodeset containing all <book> elements in the null namespace: <?xslt-param name="books" select="//book"?> set the parameter 'show-toc' to boolean true: <?xslt-param name="show-toc" se...
...
examples set the parameter 'books' to a nodeset containing all <book> elements in the 'http://www.example.org/mynamespace' namespace: <?xslt-param-namespace prefix="my" namespace="http://www.example.org/mynamespace"?> <?xslt-param name="books" select="//my:book"?> supported versions supported as of firefox 2.0.0.1.
For Further Reading - XSLT: Extensible Stylesheet Language Transformations
this book is somewhat less comprehensive than michael kay's, but it covers the basics well, and offers some intriguing
examples.
...ken holman location: http://www.xml.com/pub/a/2000/08/holman/index.html tutorials/
examples zvon xsl programmers: http://www.zvon.org/o_html/group_xsl.html jeni's xslt pages index: http://www.jenitennison.com/xslt/ xmlpitstop.com stylesheet center: http://www.xmlpitstop.com/default.asp?datatype=ssc xsl tutorial index: http://www.nwalsh.com/docs/tutorials/xsl/ other cover pages extensible stylesheet language (xsl): http://www.o...
Understanding WebAssembly text format - WebAssembly
there are a lot more things that can be put inside function bodies, but we will start off simple for now, and you’ll see a lot more
examples as you go along.
... our .wat
examples look like so: shared0.wat: (module (import "js" "memory" (memory 1)) (import "js" "table" (table 1 funcref)) (elem (i32.const 0) $shared0func) (func $shared0func (result i32) i32.const 0 i32.load) ) shared1.wat: (module (import "js" "memory" (memory 1)) (import "js" "table" (table 1 funcref)) (type $void_to_i32 (func (result i32))) (func (export "doit") (result i32) i...
Using the WebAssembly JavaScript API - WebAssembly
some simple
examples let’s run through some
examples that explain how to use the webassembly javascript api, and how to use it to load a wasm module in a web page.
... note: you can find the sample code in our webassembly-
examples github repo.
Communicating With Other Scripts - Archive of obsolete content
so the content scripts in the above
examples need to be rewritten like this: // content-script.js document.defaultview.postmessage("message from content script", "http://my-domain.org/"); // content-script.js document.defaultview.addeventlistener('message', function(event) { console.log(event.data); // message from page script console.log(event.origin); }, false); using custom dom events as an alternative to using postmessage() y...
Interacting with page scripts - Archive of obsolete content
so the content scripts in the above
examples need to be rewritten like this: // talk.js document.defaultview.postmessage("message from content script", "http://my-domain.org/"); // listen.js document.defaultview.addeventlistener('message', function(event) { console.log(event.data); // message from page script console.log(event.origin); }, false); using custom dom events as an alternative to using postmessage() you can use custom ...
Modules - Archive of obsolete content
a commonjs module defines three global variables: require, which is a function that behaves like loadscript in our
examples, exports, which behaves like the exports object, and module, which is an object representing the module itself.
Testing the Add-on SDK - Archive of obsolete content
with gulp installed, and after installing the addon-sdk's npm dependencies, we can run the latter three test suites mentioned for cfx with jpm using the following commands: gulp test:
examples --filter <addon_example_folder_name> gulp test:addons --filter <addon_folder_name> gulp test:modules --filter <file_name>:<test_name> or run all of the tests with gulp test.
XUL Migration Guide - Archive of obsolete content
tils").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 modules.
selection - Archive of obsolete content
examples log the current contiguous selection as text: var selection = require("sdk/selection"); if (selection.text) console.log(selection.text); log the current discontiguous selections as html: var selection = require("sdk/selection"); if (!selection.iscontiguous) { for (var subselection in selection) { console.log(subselection.html); } } surround html selections with delimiters: var se...
core/promise - Archive of obsolete content
lets see the implementation of readasync that we used in several of the
examples above: const { defer } = require('sdk/core/promise'); function readasync(url) { var deferred = defer(); let xhr = new xmlhttprequest(); xhr.open("get", url, true); xhr.onload = function() { deferred.resolve(xhr.responsetext); }; xhr.onerror = function(event) { deferred.reject(event); }; xhr.send(); return deferred.promise; } so defer returns an object that contains a...
places/bookmarks - Archive of obsolete content
examples creating a new bookmark let { bookmark, save } = require("sdk/places/bookmarks"); // create a new bookmark instance, unsaved let bookmark = bookmark({ title: "mozilla", url: "http://mozilla.org" }); // attempt to save the bookmark instance to the bookmarks database // and store the emitter let emitter = save(bookmark); // listen for events emitter.on("data", function (saved, inputitem) { /...
system/child_process - Archive of obsolete content
child.stdin has no write() method (see example below for writing to child process stdin)
examples adaption of node's documentation for spawn(): var child_process = require("sdk/system/child_process"); var ls = child_process.spawn('/bin/ls', ['-lh', '/usr']); ls.stdout.on('data', function (data) { console.log('stdout: ' + data); }); ls.stderr.on('data', function (data) { console.log('stderr: ' + data); }); ls.on('close', function (code) { console.log('child process exited with code...
util/list - Archive of obsolete content
examples: var { list } = require("sdk/util/list"); var mylist = list.compose({ add: function add(item1, item2, /*item3...*/) { array.slice(arguments).foreach(this._add.bind(this)); }, remove: function remove(item1, item2, /*item3...*/) { array.slice(arguments).foreach(this._remove.bind(this)); } }); mylist('foo', 'bar', 'baz').length == 3; // true new mylist('new', 'keyword').lengt...
util/match-pattern - Archive of obsolete content
la.org/ https://foo.com/moz /http.*moz.*/ http://foo.mozilla.org/ http://mozilla.org http://hemozoon.org/ https://anydomain.com/foomozbar/ ftp://http/mozilla.org /[^:/]+:\/\/[^/]*mozilla\.org\/.*/ ftp://foo.mozilla.org/ http://www.mozilla.org/ https://developer.mozilla.org/any ftp://http/mozilla.org http://anydomain.com/mozilla.org/
examples var { matchpattern } = require("sdk/util/match-pattern"); var pattern = new matchpattern("http://example.com/*"); console.log(pattern.test("http://example.com/")); // true console.log(pattern.test("http://example.com/foo")); // true console.log(pattern.test("http://foo.com/")); // false!
Adding Events and Commands - Archive of obsolete content
additional information on custom events and how they can be used to effect communication between web content and xul can be found in the interaction between privileged and non-privileged pages code snippets, which describe and provide
examples of this sort of communication.
Setting up an extension development environment - Archive of obsolete content
and newer: /applications/firefox.app/contents/macos/firefox-bin -no-remote -p dev & on windows: start -> run "%programfiles%\mozilla firefox\firefox.exe" -no-remote -p dev on windows 64 bit: start -> run "%programfiles(x86)%\mozilla firefox\firefox.exe" -no-remote -p dev to start thunderbird or seamonkey instead of firefox, substitute thunderbird, or seamonkey for the firefox used in our
examples.
Adding preferences to an extension - Archive of obsolete content
« previousnext » override chrome://myaddon/content/options.xul chrome://myaddon/content/oldoptions.xul application={ec8030f7-c20a-464f-9b0e-13a3a9e97384} appversion<=6.*
examples github - gist :: _ff-addon-template-bootstrapprefsskeleton - this gist here is a fully working example of a fully funcitonal preferences skeleton, it uses the observer example from above.
Bookmark Keywords - Archive of obsolete content
thus we could type any of the following into the address bar and get back useful results: <tt>google geitost</tt> <tt>google mozilla keyword bookmark</tt> <tt>google bookmark site:developer.netscape.com</tt> <tt>google netscape xml support -site:netscape.com</tt> a few
examples in the course of writing this article, a number of potentially useful bookmarks were considered as possible
examples.
Dehydra - Archive of obsolete content
documentation installing dehydra download, installation and dependency info for dehydra using dehydra
examples for getting started writing analysis scripts.
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...
src - Archive of obsolete content
examples <iframe id="content-body" src="http://www.mozilla.org/"/> <browser src="http://www.mozilla.org" flex="1"/> <image src='firefoxlogo.png' width='135' height='130'/> see also prefpane.src treecell.src treecol.src script.src stringbundle.src checkbox.src ...
findbar - Archive of obsolete content
« xul reference home [
examples | attributes | properties | methods | related ] in gecko 1.9, the findbar widget moved into toolkit, so it's available to any xul application, as well as extensions.
MenuItems - Archive of obsolete content
if (gundobuffertype == "typing") menuitem.label = "undo typing"; else if (gundobuffertype == "paste") menuitem.label = "undo paste"; else menuitem.label = "undo"; see modifying a menu for
examples of how to add and remove items from a menu ...
Additional Navigation - Archive of obsolete content
ter the second triple will look like this: (?start = http://www.daml.org/2001/09/countries/iso#it, ?countrytitle = italy, ?photo = http://www.xulplanet.com/ndeakin/images/t/palace.jpg) (?start = http://www.daml.org/2001/09/countries/iso#it, ?countrytitle = italy, ?photo = http://www.xulplanet.com/ndeakin/images/t/obselisk.jpg) the third triple just grabs the title from the photo as previous
examples did, adding a value for the ?title variable for each photo.
The First Install Problem - Archive of obsolete content
examples: [hkey_local_machine\software\mozillaplugins\@mycompany.com/myapplication,version=5.01\mimetypes\application/x-myapp] there can be more than one such subkey, depending on how many mimetypes an application wishes to handle (or advertise that it handles).
Atomic RSS - Archive of obsolete content
references atomic rss element list
examples none available at this time community none available at this time tools none available at this time other resources tim bray's atom rss article rss, atom, rdf, xml ...
Content - Archive of obsolete content
references rss content module element list
examples none available at this time community none available at this time tools none available at this time other resources rss content module spec rss, rdf, xml ...
Slash - Archive of obsolete content
references rss slash module element list
examples none available at this time community none available at this time tools none available at this time other resources rss slash module slash slashdot rss, rdf, xml ...
Well-Formed Web - Archive of obsolete content
references rss well-formed web module element list
examples none available at this time community none available at this time tools none available at this time other resources well-formed web spec rss, rdf, xml ...
0.90 - Archive of obsolete content
examples rss 0.90 looked something like this: <?xml version="1.0"?> <rdf:rdf xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns="http://my.netscape.com/rdf/simple/0.9/" > <channel> <title>mozilla dot org</title> <link>http://www.mozilla.org</link> <description>the mozilla organization web site</description> </...
Vulnerabilities - Archive of obsolete content
examples of settings are an operating system offering access to control lists that set the privileges that users have for files, and an application offering a setting to enable or disable the encryption of sensitive data stored by the application.
-moz-binding - Archive of obsolete content
formal definition initial valuenoneapplies toall elements except generated content or pseudo-elementsinheritednocomputed valueas specifiedanimation typediscrete formal syntax <url> | none
examples .exampleone { -moz-binding: url(http://www.example.org/xbl/htmlbindings.xml#radiobutton); } specifications not part of any standard.
-ms-scroll-snap-points-x - Archive of obsolete content
formal syntax snapinterval( <length-percentage>, <length-percentage> ) | snaplist( <length-percentage># )where <length-percentage> = <length> | <percentage>
examples this example demonstrates both types of values for the -ms-scroll-snap-points-x property.
-ms-scroll-snap-points-y - Archive of obsolete content
formal syntax snapinterval( <length-percentage>, <length-percentage> ) | snaplist( <length-percentage># )where <length-percentage> = <length> | <percentage>
examples this example demonstrates both types of values for the -ms-scroll-snap-points-y property.
-ms-scrollbar-arrow-color - Archive of obsolete content
)where <alpha-value> = <number> | <percentage><hue> = <number> | <angle>
examples the following example shows how to use -ms-scrollbar-arrow-color and -ms-scrollbar-face-color to display a scroll bar with a blue scroll box and arrows, and a scroll bar with a green scroll box and arrows.
-ms-scrollbar-base-color - Archive of obsolete content
)where <alpha-value> = <number> | <percentage><hue> = <number> | <angle>
examples this example uses -ms-scrollbar-base-color and -ms-scrollbar-arrow-color to create two <div> objects with different scroll bar color schemes.
-ms-scrollbar-face-color - Archive of obsolete content
)where <alpha-value> = <number> | <percentage><hue> = <number> | <angle>
examples this example uses -ms-scrollbar-face-color and -ms-scrollbar-arrow-color to display a scroll bar with a blue scroll box and arrows, and a scroll bar with a green scroll box and arrows.
-ms-scrollbar-highlight-color - Archive of obsolete content
)where <alpha-value> = <number> | <percentage><hue> = <number> | <angle>
examples this example uses -ms-scrollbar-highlight-color, -ms-scrollbar-face-color, and -ms-scrollbar-arrow-color to create two <div> objects with different scroll bar color schemes.
-ms-scrollbar-track-color - Archive of obsolete content
)where <alpha-value> = <number> | <percentage><hue> = <number> | <angle>
examples this example uses -ms-scrollbar-track-color, -ms-scrollbar-face-color, and -ms-scrollbar-arrow-color to create two <div> elements with different scroll bar color schemes.
azimuth - Archive of obsolete content
examples h1 { azimuth: 30deg; } td.a { azimuth: far-right; } /* 60deg */ #12 { azimuth: behind far-right; } /* 120deg */ p.comment { azimuth: behind; } /* 180deg */ specifications specification status comment css level 2 (revision 1)the definition of 'azimuth' in that specification.
Iterator - Archive of obsolete content
examples iterating over properties of an object var a = { x: 10, y: 20, }; var iter = iterator(a); console.log(iter.next()); // ["x", 10] console.log(iter.next()); // ["y", 20] console.log(iter.next()); // throws stopiteration iterating over properties of an object with legacy destructuring for-in statement var a = { x: 10, y: 20, }; for (var [name, value] in iterator(a)) { console.log(nam...
Array.observe() - Archive of obsolete content
examples logging different change types var arr = ['a', 'b', 'c']; array.observe(arr, function(changes) { console.log(changes); }); arr[1] = 'b'; // [{type: 'update', object: <arr>, name: '1', oldvalue: 'b'}] arr[3] = 'd'; // [{type: 'splice', object: <arr>, index: 3, removed: [], addedcount: 1}] arr.splice(1, 2, 'beta', 'gamma', 'delta'); // [{type: 'splice', object: <arr>, index: 1, removed: ['b...
Array.unobserve() - Archive of obsolete content
examples unobserving an array var arr = [1, 2, 3]; var observer = function(changes) { console.log(changes); } array.observe(arr, observer); arr.push(4); // [{type: "splice", object: <arr>, index: 3, removed:[], addedcount: 1}] array.unobserve(arr, observer); arr.pop(); // the callback wasn't called using an anonymous function var persons = ['khalid', 'ahmed', 'mohammed']; array.observe(pers...
ArrayBuffer.transfer() - Archive of obsolete content
examples var buf1 = new arraybuffer(40); new int32array(buf1)[0] = 42; var buf2 = arraybuffer.transfer(buf1, 80); buf1.bytelength; // 0 but if you use the polyfill then the value is still 40 buf2.bytelength; // 80 new int32array(buf2)[0]; // 42 var buf3 = arraybuffer.transfer(buf2, 0); buf2.bytelength; // 0 but if you use the polyfill then the value is still 80 buf3.bytelength; // 0 polyfill you can...
Array comprehensions - Archive of obsolete content
examples simple array comprehensions [for (i of [1, 2, 3]) i * i ]; // [1, 4, 9] var abc = ['a', 'b', 'c']; [for (letters of abc) letters.tolowercase()]; // ["a", "b", "c"] array comprehensions with if statement var years = [1954, 1974, 1990, 2006, 2010, 2014]; [for (year of years) if (year > 2000) year]; // [2006, 2010, 2014] [for (year of years) if (year > 2000) if (year < 2010) year]; // [2006], t...
Expression closures - Archive of obsolete content
examples a shorthand for binding event listeners: document.addeventlistener('click', function() false, true); using this notation with some of the array functions from javascript 1.6: elems.some(function(elem) elem.type == 'text'); ...
Function.prototype.isGenerator() - Archive of obsolete content
examples function f() {} function* g() { yield 42; } console.log('f.isgenerator() = ' + f.isgenerator()); // f.isgenerator() = false console.log('g.isgenerator() = ' + g.isgenerator()); // g.isgenerator() = true specifications not part of any standard.
ActiveXObject - Archive of obsolete content
for example, here are a few
examples of values you may find there, depending on which programs are installed: excel.application excel.chart scripting.filesystemobject wscript.shell word.document important: activex objects may present security issues.
@set - Archive of obsolete content
examples of variable declarations look like this: @set @myvar1 = 12 @set @myvar2 = (@myvar1 * 20) @set @myvar3 = @_jscript_version the following operators are supported in parenthesized expressions: !
Object.prototype.__noSuchMethod__ - Archive of obsolete content
examples simple test of __nosuchmethod__ var o = { __nosuchmethod__: function(id, args) { console.log(id, '(' + args.join(', ') + ')'); } }; o.foo(1, 2, 3); o.bar(4, 5); o.baz(); // output // foo (1, 2, 3) // bar (4, 5) // baz () using __nosuchmethod__ to simulate multiple inheritance an example of code that implements a primitive form of multiple inherit...
Object.observe() - Archive of obsolete content
examples logging all six different types var obj = { foo: 0, bar: 1 }; object.observe(obj, function(changes) { console.log(changes); }); obj.baz = 2; // [{name: 'baz', object: <obj>, type: 'add'}] obj.foo = 'hello'; // [{name: 'foo', object: <obj>, type: 'update', oldvalue: 0}] delete obj.baz; // [{name: 'baz', object: <obj>, type: 'delete', oldvalue: 2}] object.defineproperty(obj, 'foo', {wr...
Object.unobserve() - Archive of obsolete content
examples unobserving an object var obj = { foo: 0, bar: 1 }; var observer = function(changes) { console.log(changes); } object.observe(obj, observer); obj.newproperty = 2; // [{name: 'newproperty', object: <obj>, type: 'add'}] object.unobserve(obj, observer); obj.foo = 1; // the callback wasn't called using an anonymous function var person = { name: 'ahmed', age: 25 }; object.observ...
Object.prototype.watch() - Archive of obsolete content
examples using watch and unwatch const o = { p: 1 }; o.watch('p', (id, oldval, newval) => { console.log('o.' + id + ' changed from ' + oldval + ' to ' + newval); return newval; }); o.p = 2; o.p = 3; delete o.p; o.p = 4; o.unwatch('p'); o.p = 5; this script displays the following: o.p changed from 1 to 2 o.p changed from 2 to 3 o.p changed from undefined to 4 using watch() to validate an obje...
arguments.caller - Archive of obsolete content
function whocalled() { if (whocalled.caller == null) console.log('i was called from the global scope.'); else console.log(whocalled.caller + ' called me!'); }
examples the following code was used to check the value of arguments.caller in a function, but doesn't work anymore.
JavaArray - Archive of obsolete content
examples example: instantiating a javaarray in javascript in this example, the javaarray bytearray is created by the java.lang.string.getbytes method, which returns an array.
JavaObject - Archive of obsolete content
examples example: instantiating a java object in javascript the following code creates the javaobject thestring, which is an instance of the class java.lang.string: var thestring = new packages.java.lang.string("hello, world"); because the string class is in the java package, you can also use the java synonym and omit the packages keyword when you instantiate the class: var thestring = new java.lang...
Packages - Archive of obsolete content
examples example: javascript function to create a java dialog box the following javascript function creates a java dialog box: function createwindow() { var theowner = new packages.java.awt.frame(); var thewindow = new packages.java.awt.dialog(theowner); thewindow.setsize(350, 200); thewindow.settitle("hello, world"); thewindow.setvisible(true); } in the previous example, the function ...
Old Proxy API - Archive of obsolete content
// in this example, the get trap rcvr argument is the c object while proxy is its prototype
examples very simple example a trap is called almost each time something happens to your proxy (that is used like an object).
ParallelArray - Archive of obsolete content
methods map reduce scan scatter filter flatten partition get
examples using map in parallel var p = new parallelarray([0, 1, 2, 3, 4]); var m = p.map(function (v) { return v + 1; }); ...
background-size - Archive of obsolete content
and anyway, it's more the -moz-border-image that seems to be the problem - that gets inherited even if i add in -moz-border-image: none, to <body> or <html>, and setting the height to 100% is more a matter of covering it up rather than stopping it happening (see further
examples a, b and c - b and c look ok, but adding margin or padding reveals that the image applies to both <body> and <html> even though explicitly set to none) user:robertc 2009-08-14 see also bug 509681 and bug 497995.
Implementation Status - Archive of obsolete content
ns partial 7.4.4 ui expressions partial scenarios exist where controls contained inside other controls inside a repeat won't be bound correctly 333638; 7.4.5 ui binding in other xml vocabularies unsupported not a compliance requirement for an xforms processor 7.4.6 binding
examples supported 7.5 xforms core function library supported 7.6.1 boolean-from-string() supported 7.6.2 is-card-number() unsupported 7.7.1 avg() supported 7.7.2 min() supported ...
XForms Alert Element - Archive of obsolete content
examples <xforms:model> <xforms:instance> <data xmlns=""> <x>10</x> </data> </xforms:instance> <xforms:bind id="x" nodeset="x" type="xsd:integer"/> </xforms:model> <style> @namespace xforms url("http://www.w3.org/2002/xforms"); xforms|input:invalid xforms|alert.inline { display: inline; font-style: italic; width: 40%; } } </style> <xforms:input bind="x"> <xforms:label>you can ty...
XForms Select Element - Archive of obsolete content
characteristics appearance attribute contains the value full there are no analogue widgets in xhtml or in xul visual grouping by choices element is supported if incremental attribute value is false then bound node is updated when item is blurred
examples <xf:model> <xf:instance> <data xmlns=""> <values>g</values> </data> </xf:instance> </xf:model> <xf:select ref="/data/values" appearance="full"> <xf:choices> <xf:label>green colors</xf:label> <xf:item> <xf:label>pale green</xf:label> <xf:value>pg</xf:value> </xf:item> <xf:item> <xf:label>green</xf:label> <xf:value>g</xf:value> </xf:...
XForms Select1 Element - Archive of obsolete content
characteristics appearance attribute contains the value full there are no analogue widgets in xhtml or in xul visual grouping by choices element is supported selection="open" attribute isn't supported if incremental attribute value is false then bound node is updated when item is blurred
examples <xf:model> <xf:instance> <data xmlns=""> <values>g</values> </data> </xf:instance> </xf:model> <xf:select1 ref="/data/values"> <xf:choices> <xf:label>green colors</xf:label> <xf:item> <xf:label>pale green</xf:label> <xf:value>pg</xf:value> </xf:item> <xf:item> <xf:label>green</xf:label> <xf:value>g</xf:value> </xf:item> </xf:choi...
Window: devicelight event - Archive of obsolete content
examples window.addeventlistener('devicelight', function(event) { console.log(event.value); }); specifications specification status comment ambient light sensorthe definition of 'ambient light events' in that specification.
Quality values - MDN Web Docs Glossary: Definitions of Web-related terms
examples the following syntax text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 indicates the order of priority: value priority text/html and application/xhtml+xml 1.0 application/xml 0.9 */* 0.8 if there is no priority defined for the first two values, the order in the list is irrelevant.
Site - MDN Web Docs Glossary: Definitions of Web-related terms
examples of the same site https://developer.mozilla.org/docs/ https://support.mozilla.org/ same site because the registrable domain of mozilla.org is the same http://example.com:8080 https://example.com same site because scheme and port are not relevant
examples of different site https://developer.mozilla.org/docs/ https://example.com not same site because the registrable ...
Static method - MDN Web Docs Glossary: Definitions of Web-related terms
examples in the notifications api, the notification.requestpermission() method is called on the actual notification constructor itself — it is a static method: let promise = notification.requestpermission(); the notification.close() method on the other hand, is an instance method — it is called on an specific notification object instance to close the system notification it represents: let mynotifi...
Truthy - MDN Web Docs Glossary: Definitions of Web-related terms
examples of truthy values in javascript (which will be coerced to true in boolean contexts, and thus execute the if block): if (true) if ({}) if ([]) if (42) if ("0") if ("false") if (new date()) if (-42) if (12n) if (3.14) if (-3.14) if (infinity) if (-infinity) specifications specification ecmascript (ecma-262)the definition of 'toboolean abstract operation' in that specification.
Origin - MDN Web Docs Glossary: Definitions of Web-related terms
examples of same origin http://example.com/app1/index.html http://example.com/app2/index.html same origin because same scheme (http) and host (example.com) http://example.com:80 http://example.com same origin because a server delivers http content through port 80 by default
examples of different origin http://example.com/app1 https://example.com/app2 different schemes http://example.com http://www.example.com http://myapp.exa...
Your first form - Learn web development
it's beyond the scope of this guide to go deeply into that subject, but if you want to know more, we have provided some
examples in our sending form data article later on.
Publishing your website - Learn web development
try playing with some of these
examples to find out which one works best for you: jsfiddle glitch js bin codepen publishing via github now let's examine how to easily publish your site via github pages.
Creating hyperlinks - Learn web development
let's look at some
examples, to see what kind of text can be used here: <p><a href="http://www.example.com/large-report.pdf"> download the sales report (pdf, 10mb) </a></p> <p><a href="http://www.example.com/video-stream/" target="_blank"> watch the video (stream opens in separate tab, hd quality) </a></p> <p><a href="http://www.example.com/car-game"> play the car game (requires flash) </a></p> use the download at...
Debugging HTML - Learn web development
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?
Getting started with HTML - Learn web development
every time the user updates the text area code textarea.onkeyup = function(){ // we only want to save the state when the user code is being shown, // not the solution, so that solution is not saved over the user code if(solution.value === 'show solution') { userentry = textarea.value; } else { solutionentry = textarea.value; } updatecode(); }; whitespace in html in the
examples above, you may have noticed that a lot of whitespace is included in the code.
Introduction to HTML - Learn web development
note: if you are working on a computer/tablet/other devices that doesn't let you create your own files, you can try out (most of) the code
examples in an online coding program such as jsbin or glitch.
Mozilla splash page - Learn web development
note: to properly test the srcset/sizes
examples, you'll need to upload your site to a server (using github pages is an easy and free solution), then from there you can test whether they are working properly using browser developer tools such as the firefox network monitor.
Multimedia and Embedding - Learn web development
note: if you are working on a computer/tablet/other device where you don't have the ability to create your own files, you could try out (most of) the code
examples in an online coding program such as jsbin or glitch.
HTML Tables - Learn web development
note: if you are working on a computer/tablet/other device where you don't have the ability to create your own files, you could try out (most of) the code
examples in an online coding program such as jsbin or glitch.
Asynchronous JavaScript - Learn web development
note: if you are working on a computer/tablet/other device where you don't have the ability to create your own files, you can try out (most of) the code
examples in an online coding program such as jsbin or glitch.
Making decisions in your code — conditionals - Learn web development
para.textcontent = 'it isn\'t raining, but the sky is grey and gloomy; it could turn any minute, so take a rain coat just in case.'; break; default: para.textcontent = ''; } } note: you can also find this example on github (see it running live on there also.) ternary operator there is one final bit of syntax we want to introduce you to before we get you to play with some
examples.
JavaScript building blocks - Learn web development
note: if you are working on a computer/tablet/other device where you don't have the ability to create your own files, you could try out (most of) the code
examples in an online coding program such as jsbin or glitch.
Manipulating documents - Learn web development
tnode(' — the premier source for web development knowledge.'); now we'll grab a reference to the paragraph the link is inside, and append the text node to it: const linkpara = document.queryselector('p'); linkpara.appendchild(text); that's most of what you need for adding nodes to the dom — you'll make a lot of use of these methods when building dynamic interfaces (we'll look at some
examples later).
Video and Audio APIs - Learn web development
if you downloaded our
examples repo, you'll find it in javascript/apis/video-audio/start/ at this point, if you load the html you should see a perfectly normal html5 video player, with the native controls rendered.
JavaScript First Steps - Learn web development
note: if you are working on a computer/tablet/other device where you don't have the ability to create your own files, you could try out (most of) the code
examples in an online coding program such as jsbin or glitch.
Introducing JavaScript objects - Learn web development
note: if you are working on a computer/tablet/other devices where you don't have the ability to create your own files, you could try out (most of) the code
examples in an online coding program such as jsbin or glitch.
The "why" of web performance - Learn web development
here's some real-world
examples of performance improvements: tokopedia reduced render time from 14s to 2s for 3g connections and saw a 19% increase in visitors, 35% increase in total sessions, 7% increase in new users, 17% increase in active users and 16% increase in sessions per user.
Properly configuring server MIME types - Learn web development
examples of mime types are: text/html for normal web pages text/plain for plain text text/css for cascading style sheets text/javascript for scripts application/octet-stream meaning "download this file" application/x-java-applet for java applets application/pdf for pdf documents technical background registered values for mime types are available in iana | mime media types.
Client-Server Overview - Learn web development
p.scl3.mozilla.com vary: cookie vary: accept-encoding content-type: text/html; charset=utf-8 date: wed, 07 sep 2016 00:38:13 gmt location: https://developer.mozilla.org/profiles/hamishwillee keep-alive: timeout=5, max=1000 connection: keep-alive x-frame-options: deny x-cache-info: not cacheable; request wasn't a get or head content-length: 0 note: the http responses and requests shown in these
examples were captured using the fiddler application, but you can get similar information using web sniffers (e.g.
Getting started with Svelte - Learn web development
<main> <h1>hello {name}!</h1> <p>visit the <a href="https://svelte.dev/tutorial">svelte tutorial</a> to learn how to build svelte apps.</p> </main> svelte also supports tags like {#if...}, {#each...}, and {#await...} — these
examples allow you to conditionally render a portion of the markup, iterate through a list of elements, and work with async values, respectively.
Handling common HTML and CSS problems - Learn web development
so for example: mozilla uses -moz- chrome/opera/safari use -webkit- microsoft uses -ms- here's some
examples: -webkit-transform: rotate(90deg); background-image: -moz-linear-gradient(left,green,yellow); background-image: -webkit-gradient(linear,left center,right center,from(green),to(yellow)); background-image: linear-gradient(to right,green,yellow); the first line shows a transform property with a -webkit- prefix — this was needed to make transforms work in chrome, etc.
Handling common JavaScript problems - Learn web development
for a light introduction; you should also study
examples like this one, which shows a typical pattern of saving a this scope to a separate variable, then using that variable in nested functions so you can be sure you are applying functionality to the correct this scope.
Git and GitHub - Learn web development
git handbook (from github) this git handbook goes into a little more depth, explaining what a vcs is, what a repository is, how the basic github model works, git commands and
examples, and more.
Client-side tooling overview - Learn web development
good
examples here include: babel: a javascript compiler that allows developers to write their code using cutting-edge javascript, which babel then takes and converts into old-fashioned javascript that more browsers can understand.
Learn web development
getting our code
examples the code
examples you'll encounter in the learning area are all available on github.
Accessibility Features in Firefox
here are some
examples of accessible extensions, although there are hundreds more to try (thank you to the gw micro knowledge base for some of this information): adblock plus removes ads (and other objects, like banners) from web pages greasemonkey lets you add bits of javascript ("user scripts") to any web page to change its behavior.
Mozilla accessibility architecture
examples of accessible role constants are role_button, role_checkbox and role_list, although they can have slightly different names and values in each api.
CSUN Firefox Materials
here are some
examples of accessible extensions, although there are hundreds more to try (thank you to the gw micro knowledge base for some of this information): adblock plus removes ads (and other objects, like banners) from web pages greasemonkey lets you add bits of javascript ("user scripts") to any web page to change its behavior.
Software accessibility: Where are we today?
some
examples of these assistive devices and software include: screen reading software, which speaks text displayed on the screen using hardware or software text-to-speech, and which allows a blind person to use the keyboard to simulate mouse actions alternate input devices, which allow people with physical disabilities to use alternatives to a keyboard and mouse voice recognition software, which allows...
Chrome registration
toolbars, menu bars, progress bars, and window title bars are all
examples of elements that are typically part of the chrome.
Command line options
in general, the syntax is as follows: application -option -option "argument" -option argument
examples the following
examples show the use of the "-profilemanager" command, which will open the profile manager prior to starting firefox or thunderbird: windows select run from windows start menu.
Creating JavaScript callbacks in components
here is an example of how to use the callback system: var wordhandler = { onword : function(word) { alert(word); } }; var stringparser = /* get a reference to the parser somehow */ stringparser.addobserver(wordhandler); stringparser.parse("pay no attention to the man behind the curtain"); you can find
examples of this pattern all over the mozilla codebase.
Debugging Table Reflow
debug_table_strategy editor's note: the following
examples are not shown correctly due to the wiki's technical constraint.
HTTP logging
so we have added a 'rotate:size_in_mb' option to moz_log (we use it in the
examples above).
Debugging
remote debugging core dumps and
examples of remote debugging.
How Mozilla's build system works
makefile
examples standard makefile header installing headers using exports compiling interfaces using xpidlsrcs installing a javascript component building a component dll building a static library building a dynamic library makefiles - best practices and suggestions makefile - targets makefile - variables, values makefile - *.mk files & user config building libraries there are three main types of ...
mach
here are some
examples: # use an explicit mozconfig file.
Cross Process Object Wrappers
this means that
examples like this will actually work, even in multiprocess firefox: gbrowser.selectedbrowser.contentdocument.body.innerhtml = "replaced by chrome code"; it's still important to keep in mind, though, that this is access through a cpow and not direct access to content.
Firefox UI considerations for web developers
examples consider again the example top sites box shown at the top of the page, repeated below: let's look at some
examples among the icons shown here (note that this discussion is based on the site designs as of early january, 2019).
HTMLIFrameElement.addNextPaintListener()
examples var browser = document.queryselector('iframe'); function onnextpaint() { console.log("paint has occured"); } browser.addnextpaintlistener(onnextpaint); specification not part of any specification.
HTMLIFrameElement.clearMatch()
examples the following function is taken from our browser api demo, and (amongst other things) clears the search results when the search bar is hidden, if an existing search is active.
HTMLIFrameElement.download()
examples var browser = document.queryselector('iframe'); var request = browser.download(foourl, { filename: 'foo.bin' }); request.onsuccess = function() { console.log("file downladed"); } request.onerror = function() { console.log("download error"); } specification not part of any specification.
HTMLIFrameElement.executeScript()
examples var request1 = browser.executescript( var a = 3; a + 3 , {url: 'http://example.com/index.html'}); request1.onsuccess = function() { console.log(request1.result); // 6 } var request2 = browser.executescript( new promise((resolve, reject) => { settimeout(function() { resolve(6); }, 1000}) ) , {origin: 'http://example.com'}); request2.onsuccess = function() { console.lo...
HTMLIFrameElement.findNext()
examples the following functions are taken from our browser api demo, and cycle through the available search results.
HTMLIFrameElement.getContentDimensions()
examples var browser = document.queryselector('iframe'); var request = browser.getcontentdimensions(); request.onsuccess = function() { console.log("page size:", request.result.width + "x" + request.result.height); } request.onerror = function() { console.log("download error"); } specification not part of any specification.
HTMLIFrameElement.getManifest()
examples var browser = document.queryselector('iframe'); browser.addeventlistener('mozbrowserloadend',function() { var request = browser.getmanifest().then(function(json) { console.log(json); }); }); specification not part of any specification.
HTMLIFrameElement.getScreenshot()
examples var browser = document.queryselector('iframe'); var request = browser.getscreenshot(100, 100); request.onsuccess = function() { var blob = request.result; var url = url.createobjecturl(blob); } specification not part of any specification.
HTMLIFrameElement.getStructuredData()
examples var browser = document.queryselector('iframe'); browser.addeventlistener('mozbrowserloadend',function() { var request = browser.getstructureddata(); request.onsuccess = function() { console.log(request.result); } }); running this code in a browser api app and then loading up a page that contains microdata (such as the website of british alt-country band salter cane) will result in a j...
HTMLIFrameElement.goBack()
examples back.addeventlistener('touchend',function() { browser.goback(); }); specification not part of any specification.
HTMLIFrameElement.goForward()
examples fwd.addeventlistener('touchend',function() { browser.goforward(); }); specification not part of any specification.
mozbrowseractivitydone
examples var browser = document.queryselector("iframe"); browser.addeventlistener("mozbrowseractivitydone", function(event) { if(event.details.success) { console.log('activity completed successfully'); } else { console.log('activity not completed successfully'); } }); related events mozbrowserclose mozbrowsercontextmenu mozbrowsererror mozbrowsericonchange mozbrowserloadend mozbro...
mozbrowserasyncscroll
examples var browser = document.queryselector("iframe"); browser.addeventlistener("mozbrowserasyncscroll", function( event ) { console.log("the scroll top position of the document is:" + event.details.top + "px"); }); related events mozbrowserclose mozbrowsercontextmenu mozbrowsererror mozbrowsericonchange mozbrowserloadend mozbrowserloadstart mozbrowserlocationchange mozbrowseropenwindow ...
mozbrowseraudioplaybackchange
examples var browser = document.queryselector("iframe"); browser.addeventlistener("mozbrowseraudioplaybackchange", function(event) { console.log(event.details); }); related events mozbrowserclose mozbrowsercontextmenu mozbrowsererror mozbrowsericonchange mozbrowserloadend mozbrowserloadstart mozbrowserlocationchange mozbrowseropenwindow mozbrowsersecuritychange mozbrowsertitlechange mozb...
mozbrowsercaretstatechanged
examples var browser = document.queryselector("iframe"); browser.addeventlistener("mozbrowsercaretstatechanged", function( event ) { // do stuff with event.details }); related events mozbrowserclose mozbrowsercontextmenu mozbrowsererror mozbrowsericonchange mozbrowserloadend mozbrowserloadstart mozbrowserlocationchange mozbrowseropenwindow mozbrowsersecuritychange mozbrowsertitlechange m...
HTMLIFrameElement.purgeHistory()
examples domrequest: var browser = document.queryselector('iframe'); var request = browser.purgehistory(); request.onsuccess = function() { console.log('history deleted!'); } request.onerror = function() { console.error(this.error.name); } promise: var browser = document.queryselector('iframe'); browser.purgehistory().then(function() { console.log('history deleted!'); }, function(error) { ...
HTMLIFrameElement.reload()
examples stopreload.addeventlistener('touchend',function() { if(stopreload.textcontent === 'x') { browser.stop(); } else { browser.reload(); } }); specification not part of any specification.
HTMLIframeElement.removeNextPaintListener()
examples var browser = document.queryselector('iframe'); function onnextpaint() { console.log("paint has occured"); } browser.addnextpaintlistener(onnextpaint); browser.removenextpaintlistener(onnextpaint); specification not part of any specification.
HTMLIFrameElement.sendMouseEvent()
examples var browser = document.queryselector('iframe'); browser.sendmouseevent("mousemove", x, y, 0, 0, 0); browser.sendmouseevent("mousedown", x, y, 0, 1, 0); browser.sendmouseevent("mouseup", x, y, 0, 1, 0); specification not part of any specification.
HTMLIFrameElement.sendTouchEvent()
examples var browser = document.queryselector('iframe'); browser.sendtouchevent("touchstart", [1], [x], [y], [2], [2], [20], [0.5], 1, 0); specification not part of any specification.
HTMLIFrameElement.setVisible()
examples var browser = document.queryselector('iframe'); browser.setvisible(true); specification not part of any specification.
HTMLIFrameElement.stop()
examples stopreload.addeventlistener('touchend',function() { if(stopreload.textcontent === 'x') { browser.stop(); } else { browser.reload(); } }); specification not part of any specification.
HTMLIFrameElement.zoom()
examples var browser = document.queryselector('iframe'); var zoomfactor = 1; zoomin.addeventlistener('touchend',function() { zoomfactor += 0.1; browser.zoom(zoomfactor); }); zoomout.addeventlistener('touchend',function() { zoomfactor -= 0.1; browser.zoom(zoomfactor); }); specification not part of any specification.
Chrome-only API reference
examples of chromeworker's using js-ctypes are availabe on github and are linked to from the see also section below.
::-moz-tree-image
associated elements <xul:treeitem> <xul:treecell> style properties margin list-style position
examples bookmark icons in the places window - mozillazine forum ...
::-moz-tree-row
associated elements treerow syntax treechildren::-moz-tree-row { style properties } style properties background border margin outline padding display -moz-appearance
examples treechildren::-moz-tree-row( foo bar ) { margin: 2%; } ...where...
overflow-clip-box-block
examples padding-box html <div class="things"> <input value="abcdefghijklmnopqrstuvwxyzÅÄÖ" class="scroll padding-box"> <div class="scroll padding-box"><span>abcdefghijklmnopqrstuvwxyzÅÄÖ</span></div> </div> css .scroll { overflow: auto; padding: 0 30px; width: 6em; border: 1px solid black; background: lime content-box; } .padding-box { overflow-clip-box-block: padding-box; } ...
overflow-clip-box-inline
examples padding-box html <div class="things"> <input value="abcdefghijklmnopqrstuvwxyzÅÄÖ" class="scroll padding-box"> <div class="scroll padding-box"><span>abcdefghijklmnopqrstuvwxyzÅÄÖ</span></div> </div> css .scroll { overflow: auto; padding: 0 30px; width: 6em; border: 1px solid black; background: lime content-box; } .padding-box { overflow-clip-box-inline: padding-box; }...
overflow-clip-box
formal syntax padding-box | content-box
examples padding-box html <div class="things"> <input value="abcdefghijklmnopqrstuvwxyzÅÄÖ" class="scroll padding-box"> <div class="scroll padding-box"><span>abcdefghijklmnopqrstuvwxyzÅÄÖ</span></div> </div> css .scroll { overflow: auto; padding: 0 30px; width: 6em; border: 1px solid black; background: lime content-box; } .padding-box { overflow-clip-box: padding-box; } js f...
Script security
privileged to unprivileged code the most obvious example of this kind of security relation is between system-privileged chrome code and untrusted web content, but there are other
examples in gecko.
How to implement a custom autocomplete search component
note: when copying the
examples below, change the uuid that uniquely identifies the component, otherwise you might have problems if your component gets installed along another component derived from those same
examples.
PBackground
examples indexeddb was rebuilt on top of pbackground last year.
Assert.jsm
undefined report( failed, actual, expected, message, operator ); parameters failed indicates if the assertion failed or not actual the result of evaluating the assertion expected expected result from the test author message short explanation of the expected result operator operation qualifier used by the assertion method (ex: '==')
examples custom reporter example components.utils.import("resource://testing-common/assert.jsm"); let assert = new assert(); assert.setreporter(function customreporter(err, message, stack) { if (err) { do_report_result(false, err.message, err.stack); } else { do_report_result(true, message, stack); } }); ...
AsyncShutdown.jsm
examples asyncshutdown.profilebeforechange.addblocker("module: just a promise", promise); // profilebeforechange will not complete until // promise is resolved or rejected asyncshutdown.profilebeforechange.addblocker("module: a callback", function condition() { // ...
CustomizableUI.jsm
examples createwidget - button type this is likely the code you need for your widget.
Dict.jsm
examples creating and populating a dictionary this example creates a new dictionary and adds some key/value pairs to it.
Downloads.jsm
examples downloading to a local file this example downloads an html file without showing progress, handling errors programmatically.
FileUtils.jsm
see also nsifileoutputstream code snippets and
examples ...
FxAccountsOAuthClient.jsm
parameters none
examples using the fxaccountsoauthclient chrome code let parameters = { oauth_uri: oauth_server_endpoint, client_id: oauth_client_id, content_uri: content_server_url, state: oauth_state } let client = new fxaccountsoauthclient({ parameters: parameters }); client.oncomplete = function (tokendata) { // tokendata consists of two properties: "tokendata.state" and "tokendata.code" }; client.lau...
FxAccountsProfileClient.jsm
examples using the fxaccountsprofileclient chrome code let client = new fxaccountsprofileclient({ serverurl: "https://profile.accounts.firefox.com/v1", token: "fxa_oauth_bearer_token", }); client.fetchprofile().then(profile => console.log(profile)); error handling the fxaccountsprofileclient.jsm normalizes request and client errors into fxaccountsprofileclienterror object.
JNI.jsm
aparamsarr.join('') : '') + ')' + aret; } function fullyqualifiednameofclass(aclass) { // aclass is a string with l and ; arround it return aclass.substr(1, aclass - 2); }
examples read java strings this example shows how to read java strings as javascript strings.
Promise
examples see the
examples page.
PromiseWorker.jsm
following information to the console: "fullfilled - promise_domyfunctrue - " "you sent to promiseworker argument of: `true`" bootstrap.js line 8 "rejected - promise_domyfuncfalse - " "you passed in a non-true value for shouldresolve argument and therefore this will reject the main thread promise" bootstrap.js line 25 other
examples github :: promiseworker with backward compatability - this example is of a firefox addon that copies and pastes in the contents of promiseworker.js and promiseworker.jsm so that it works all the way back till the firefox version in which the promise interface was frozen.
Task.jsm
examples general example cu.import("resource://gre/modules/task.jsm"); task.spawn(function* () { // this is our task.
Using JavaScript code modules
examples a template to download and edit is seen here on github - gists - _template-bootstrapjsm.xpi extending resource: urls prior to gecko 2.0, the most common way to load code modules was using resource: urls.
WebChannel.jsm
examples setting up a webchannel between chrome code and a webpage chrome code let channel = new webchannel(webchannelid, services.io.newuri("https://mozilla.org", null, null)); // receive messages channel.listen(function (webchannelid, message, sendercontext) { // send messages channel.send({ data: { greeting: true } }, sendercontext); }); webpage code receive messages from an existing we...
XPCOMUtils.jsm
examples definelazygetter var myservices = {}; cu.import('resource://gre/modules/xpcomutils.jsm'); //set it up xpcomutils.definelazygetter(myservices, 'as', function () { return cc['@mozilla.org/alerts-service;1'].getservice(ci.nsialertsservice) }); //when you need to use it myservices.as.showalertnotification('chrome://branding/content/icon64.png', 'this was lazyloaded', 'this is a notification from ...
Localization quick start guide
when we get to specific
examples, we'll take them from the firefox project, as it is the most widely localized project within mozilla.
Basics
these fonts are required to view other
examples beyond the basic constructions illustrated here.
MathML3Testsuite
characters blocks symbols variants entitynames numericrefs utf8 general clipboard genattribs math presentation css dynamicexpressions generallayout scriptsandlimits tablesandmatrices tokenelements topics accents bidi elementarymath
examples embellishedop largeop linebreak nesting stretchychars whitespace torturetests errorhandling original document information author(s): frédéric wang other contributors: last updated date: may 26, 2010 copyright information: portions of this content are © 2010 by individual mozilla.org contributors; content available under a creative commons license | details.
MathML In Action
) × ( ∏ k θ ( e k 2 π i - ( α k + 1 ) z ) θ ( - z ) θ ( e k 2 π i - z ) θ ( - ( α k + 1 ) z ) ) π ( n ) = ∑ m = 2 n ⌊ ( ∑ k = 1 m - 1 ⌊ ( m / k ) / ⌈ m / k ⌉ ⌋ ) - 1 ⌋ ‖ ϕ ‖ w s k ( Ω g ) ≝ ( ∑ | α | ≦ k ∂ α ϕ ∂ ξ α l s ( Ω g ) s ) 1 / s for more
examples, refer to links on the mathml project page, and if you are building your own mozilla binary, see the directory mozilla/layout/mathml/tests.
Gecko Profiler FAQ
(see many of the questions above for
examples of such limitations.) note that these tools should all be considered as complementary, it’s typical to capture a profile in gecko profiler and based on some investigations decide to delve into some part of it using a native profiler, etc.
Memory reporting
there are many such
examples in the code, such as nscategorymanager.
browser.urlbar.trimURLs
examples: https://www.example.org/ becomes https://www.example.org, http://www.example.org/foobar becomes www.example.org/foobar and http://ftp.example.org/foobar remains unchanged.
Preferences system
reference information about them is available below: preferences system documentation: introduction: getting started |
examples | troubleshooting reference: prefwindow | prefpane | preferences | preference | xul attributes use code for a typical preferences window may look like this: <prefwindow id="apppreferences" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <prefpane id="pane1" label="&pane1.title;"> <preferences> <preference id="pref1" name="pref.name" type="bool"/...
Preferences
examples code snippets preference-related code snippets.
Localization Use Cases
in all presented
examples, we try to show the existing code, explain the problem from the localizers' or developers' perspective, and suggest a solution.
Midas
examples this example shows the basic structure described in the notes section : <html> <head> <title>simple edit box</title> </head> <body> <iframe id="midasform" src="about:blank" onload="this.contentdocument.designmode='on';" ></iframe> </body> </html> methods document.execcommand executes the given command.
NSPR LOG MODULES
examples log everything from the toolkit::storage component that happens, prefixing each line with the timestamp when it was logged to the file /tmp/foo.log (which will be replaced each time the executable is run).
NSPR Types
here are some simple
examples of the use of these types: in dowhim.h: pr_extern( void ) dowhatimean( void ); static void pr_callback rootfunction(void *arg); in dowhim.c: pr_implement( void ) dowhatimean( void ) { return; }; prthread *thread = pr_createthread(..., rootfunction, ...); algebraic types nspr provides the following type definitions with unambiguous bit widths for algebraic operations: 8-, 16-, and...
JSS FAQ
org/mozilla/jss/tests/selftest.java org/mozilla/jss/tests/setupdbs.java org/mozilla/jss/tests/sigtest.java org/mozilla/jss/tests/symkeygen.java org/mozilla/jss/tests/testkeygen.java org/mozilla/jss/tests/sslclientauth.java org/mozilla/jss/tests/listcacerts.java org/mozilla/jss/tests/keystoretest.java org/mozilla/jss/tests/verifycert.java ssl
examples: org/mozilla/jss/tests/sslclientauth.java org/mozilla/jss/ssl/sslclient.java org/mozilla/jss/ssl/sslserver.java org/mozilla/jss/ssl/ssltest.java other test code that may prove useful: org/mozilla/jss/asn1/integer.java org/mozilla/jss/asn1/sequence.java org/mozilla/jss/asn1/set.java org/mozilla/jss/pkcs10/certificationrequest.java org/mozilla/j...
NSS Developer Tutorial
when a block of code consists of a single statement, nss doesn’t require curly braces, so both of these
examples are fine: if (condition) { action(); } or: if (condition) action(); although the use of curly braces is more common.
NSS Sample Code Sample1
we will add message protection (encryption and macing)
examples to this program in the future.
pkfnc.html
see also for
examples of password callback functions, see the samples in the samples directory.
NSS Tools certutil
o the database with one command: making a separate certificate request: creating a new binary certificate from a binary certificate request: adding a certificate to an existing database: listing all certificates or a named certificate: validating a certificate: modifying a certificate's trust attribute: displaying a list of the options and arguments used by the certificate database tool:
examples creating a new certificate database this example creates a new certificate database (cert8.db file) in the specified directory: certutil -n -d certdir you must generate the associated key3.db and secmod.db files by using the key database tool or other tools.
NSS Tools crlutil
ir] [-p dbprefix] [-l alg] [-a] [-b] -l [-n crl-name] [-d krydir] crlutil -d -n nickname [-d keydir] [-p dbprefix] crlutil -e [-d keydir] [-p dbprefix] crlutil -i -i crl [-t crltype] [-u url] [-d keydir] [-p dbprefix] [-b] creating or modifying a crl: listing all crls or a named crl: deleting crl from db: erasing crls from db: import crl from file:
examples creating a new crl listing crls in a database deleting crl from a database importing crl into a database modifiying crl in a database creating a new crl this example creates a new crl and importing it in to a database in the specified directory: crlutil -g -d certdir -n cert-nickname -c crl-script-file or crlutil -g -d certdir -n cert-nickname <<eof update=20050204153000z ...
NSS tools : modutil
usage and
examples creating database files before any operations can be performed, there must be a set of security databases available.
NSS tools : pk12util
ror o 21 - cert db conversion version 7 to version 5 error o 22 - cert and key dbs patch error o 23 - get default cert db error o 24 - find cert by nickname error o 25 - create export context error o 26 - pkcs12 add password itegrity error o 27 - cert and key safes creation error o 28 - pkcs12 add cert and key error o 29 - pkcs12 encode error
examples importing keys and certificates the most basic usage of pk12util for importing a certificate or key is the pkcs#12 input file (-i) and some way to specify the security database being accessed (either -d for a directory or -h for a token).
NSS tools : signtool
extended
examples the following example will do this and that listing available signing certificates you use the -l option to list the nicknames for all available certificates and check which ones are signing certificates.
NSS tools : signver
extended
examples verifying a signature the -v option verifies that the signature in a given signature file is valid when used to sign the given object (from the input file).
Rhino documentation
examples a set of
examples showing how to control the javascript engine and build javascript host objects.
Rhino JavaScript compiler
examples $ cat test.js java.lang.system.out.println("hi, mom!"); $ java org.mozilla.javascript.tools.jsc.main test.js $ ls *.class test.class $ java test hi, mom!
Rhino serialization
they're intended mainly as
examples of the use of serialization: $ java org.mozilla.javascript.tools.shell.main js> function f() { return 3; } js> serialize(f, "f.ser") js> quit() $ java org.mozilla.javascript.tools.shell.main js> f = deserialize("f.ser") function f() { return 3;} js> f() 3 js> here we see a simple case of a function being serialized to a file and then read into a new instance of rhino and called.
Shumway
the next step is to use the inspector included as one of shumway's
examples.
JSAPI Cookbook
/* jsapi */ bool found; assert(y.isobject()); js::rootedobject yobj(cx, &y.toobject()); if (!js_hasproperty(cx, yobj, "myprop", &found)) return false; if (found) { // then do something } defining a constant property this is the first of three
examples involving the built-in function object.defineproperty(), which gives javascript code fine-grained control over the behavior of individual properties of any object.
Starting WebLock
to keep things as simple as possible, we'll read the file into memory using standard ansi file i/o, but for
examples and information about how to usenecko, the gecko networking libraries, see http://www.mozilla.org/projects/netlib/.
Using XPCOM Components
component
examples you can find out more about how you can use the particular components described here in the xpcom api reference.
XPCOM hashtable guide
a few
examples: a hashtable that maps utf-8 origin names to a dom window - nsinterfacehashtable<nscstringhashkey, nsidomwindow> a hashtable that maps 32 bit integers to floats - nsdatahashtable<nsuint32hashkey, float> a hashtable that maps nsisupports pointers to reference counted cacheentrys - nsrefptrhashtable<nsisupportshashkey, cacheentry> a hashtable that maps jscontext pointers to a contextinfo stru...
Mozilla internal string guide
// call init(const nsacstring&) init(nsdependentcstring("start value")); // bad - length determined at runtime here are some
examples of proper usage of the literals (both standard and user-defined): // call init(const nsliteralstring&) - enforces that it's only called with literals init(u"start value"_ns); // call init(const nsastring&) init(u"start value"_ns); // call init(const nsacstring&) init("start value"_ns); in case a literal is defined via a macro, you can just convert it to nsliteralstring or nsliteralcstring us...
XPCOM Stream Guide
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.
Components.isSuccessCode
examples checking whether copying a stream's data succeeded the following example demonstrates copying data from a buffered nsiinputstream to an nsioutputstream, checking for whether the copy succeeded using components.issuccesscode().
Components.utils.reportError
examples usage in an exception handler: try { this.could.raise.an.exception; } catch(e) { components.utils.reporterror(e); // report the error and continue execution } sending debugging messages to the error console: components.utils.reporterror("init() called"); ...
JavaXPCOM
sample code there are several java test applications checked in to the tree that give
examples on how to embed gecko or init xpcom from within java.
IAccessibleImage
some
examples are: the accessible name and description() are not enough to fully describe the image, for example when the accessible description() is used to define the behavior of an actionable image and the image itself conveys semantically significant information.
mozIRegistry
i'll talk about them to provide
examples of how you should use the other boxes.
nsICategoryManager
examples print out a list of all categories this snippet shows how to print out a list of all categories in c++.
nsIComponentManager
void removebootstrappedmanifestlocation( in interface nsilocalfile alocation ); parameters
examples using addbootstrappedmanifestlocation in a bootstrapped extension for firefox 8 and 9: alocation the directory or xpi to stop reading the chrome.manifest from.
nsIConsoleService
examples retrieving the message array to retrieve the message array in gecko prior to version 19: function getconsolemessagearray() { var consoleservice = components.classes["@mozilla.org/consoleservice;1"] .getservice(components.interfaces.nsiconsoleservice); var array = {}; consoleservice.getmessagearray(array, {}); return array.value; } to retrieve the mess...
nsIContentFrameMessageManager
examples once you obtain the conten frame messge manager, you can send messages to listeners who registered with services.mm.addmessagelistener get content message manager from browser this could would run in a nsidomwindow scope.
nsIDOMEvent
examples of epoch time are the time of the system start or 0:0:0 utc 1st january 1970.
nsIDOMFileReader
examples os.file for the main thread - example - save canvas to disk see also file api specification working draft nsidomfile nsidomfilelist nsidomfileexception ...
nsIDOMParser
examples within the context of a window: var parser = new domparser(); var doc = parser.parsefromstring(astr, "application/xml"); outside of a window (e.g., a js xpcom component, a js module, or an xpcshell test): var parser = components.classes["@mozilla.org/xmlextras/domparser;1"] .createinstance(components.interfaces.nsidomparser); var doc = parser.parsefromstring(astr, "application/xml")...
nsIEnvironment
examples windows this example gets the path to the porgram files directory on windows.
ExtensionManager (Toolkit)
examples here is how to retrive all the extensions installed: var em = cc['@mozilla.org/extensions/manager;1'] .getservice(ci.nsiextensionmanager); const nsiupdateitem = ci.nsiupdateitem; var extension_type = nsiupdateitem.type_extension; items = em.getitemlist(extension_type, {}); items.foreach(function(item, index, array) { alert(item.name + " / " + item.id + " version: " + item.version); }); ...
nsIINIParser
examples getting a value for a key this example provides a function you can call to obtain the value for a specific key in a given ini file.
Using nsILoginManager
defining an nsilogininfo object is simple: var nslogininfo = new components.constructor( "@mozilla.org/login-manager/logininfo;1", components.interfaces.nsilogininfo, "init" ); var logininfo = new nslogininfo( hostname, formsubmiturl, httprealm, username, password, usernamefield, passwordfield );
examples creating a login for a web page var formlogininfo = new nslogininfo( 'http://www.example.com', 'http://login.example.com', null, 'joe', 'secret123', 'uname', 'pword' ); this login would correspond to a html form such as: <form action="http://login.example.com/foo/authenticate.cgi"> <div>please log in.</div> <label>username:</label> <input type="text" name="uname"> <label>password:</...
nsIMacDockSupport
to create an instance, use: var dock = components.classes["@mozilla.org/widget/macdocksupport;1"] .getservice(components.interfaces.nsimacdocksupport); see working with the mac os x dock for details and
examples.
nsIPassword
see using nsipasswordmanager for
examples of nsipassword in use.
nsIPasswordManager
netwerk/base/public/nsipasswordmanager.idlscriptable used to interface with the built-in password manager 66 introduced gecko 1.0 deprecated gecko 1.9 inherits from: nsisupports last changed in gecko 1.0 see using nsipasswordmanager for
examples.
nsIPlacesView
see displaying places information using views for
examples.
nsIPluginHost
lugininstance void setupplugininstance( in string amimetype, in nsiuri aurl, in nsiplugininstanceowner aowner ); parameters amimetype aurl aowner native code only!stopplugininstance void stopplugininstance( in nsiplugininstance ainstance ); parameters ainstance native code only!useragent void useragent( in nativechar resultingagentstring ); parameters
examples list all plug-ins and associated mime types and get handler info this example here logs to browser console all the installed plug-ins and the associated mime types.
Thunderbird Configuration Files
the path
examples above refers to the default profile that is automatically created when you start thunderbird for the first time.
Add Option to Context Menu
this can be reached by adding these lines to the chrome.manifest file: overlay chrome://messenger/content/mailwindowoverlay.xul chrome://myaddon/content/tboverlay-tb2.xul appversion<3.0 overlay chrome://messenger/content/mailwindowoverlay.xul chrome://myaddon/content/tboverlay-tb3.xul appversion=>3.0 than we need two overlay xul files with content from
examples above.
Thunderbird extensions
learn more about gloda: an overview of gloda how to create your first message query and read the gloda
examples gloda internals: gloda debugging, gloda indexing more thunderbird-specific links some links may be out of date, but they still provide valuable information on the codebase.
Zombie compartments
proactive checking of add-ons it's not uncommon for add-ons to cause zombie compartments, see bug 700547 for
examples.
Using COM from js-ctypes
atext = 'hello firefox!'; let aflags = spf_default; primative_hr = spvoice.speak(spvoiceptr, atext, aflags, 0); checkhresult(primative_hr, "cocreateinstance"); } catch (ex) { console.error('ex occured:', ex); } finally { if (spvoice) { spvoice.release(spvoiceptr); } couninitialize(); } } main(); lib.close(); other
examples shgetpropertystoreforwindow - this
examples shows that coinit is not needed, some winapi functions return the interface.
PointerType
examples creating a type "pointer to 32-bit integer" looks like this: var intptrtype = new ctypes.pointertype(ctypes.int32_t); properties property type description targettype ctype the type of object the pointer points to.
ctypes
examples example of structtype() on windows let's say we need tb_button, this type needs to be created.
js-ctypes
examples add to iphoto a firefox extension that uses js-ctypes to call carbon and core foundation framework routines on mac os x to implement an "add image to iphoto" feature in firefox.
Drawing and Event Handling - Plugins
here are two
examples of plug-ins that have transparent areas: a plug-in that is smaller than the area specified by the enclosing object or embed element a plug-in with nonrectangular boundaries the browser is responsible for rendering the background of a transparent windowless plug-in.
Plug-in Basics - Plugins
the following
examples demonstrate this use of nested object elements with markup more congenial to gecko included as children of the parent object element.
Preferences System
reference information about them is available below: preferences system documentation: introduction: getting started |
examples | troubleshooting reference: prefwindow | prefpane | preferences | preference | xul attributes use code for a typical preferences window may look like this: <prefwindow id="apppreferences" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <prefpane id="pane1" label="&pane1.title;"> <preferences> <preference id="pref1" name="pref.name" type="bool"/...
Application - Firefox Developer Tools
finding an example if you want to test this functionality and you don't have a handy pwa available, you can grab one of our simple
examples to use: add to homescreen demo: shows pictures of foxes (source code | live version) js13kpwa demo: show information on entries to the js13k annual competition (source code | live version) how to debug service workers inspect web app manifests ...
Use a source map - Firefox Developer Tools
the comment's syntax is like this: //# sourcemappingurl=http://example.com/path/to/your/sourcemap.map in the video above we load https://mdn.github.io/devtools-
examples/sourcemaps-in-console/index.html.
Debugger-API - Firefox Developer Tools
examples here are some things you can try out yourself that show off some of debugger’s features: setting a breakpoint in a page, running a handler function when it is hit that evaluates an expression in the page’s context.
Edit fonts - Firefox Developer Tools
here are a couple of
examples of fonts with different axes defined: in the following example, you can see that the font "cheee variable" includes settings for yeast and gravity.
Examine and edit HTML - Firefox Developer Tools
whitespace nodes are represented with a dot: and you get an explanatory tooltip when you hover over them: to see this in action, see the demo at https://mdn.github.io/devtools-
examples/whitespace-only-demo/index.html.
Animating CSS properties - Firefox Developer Tools
css property cost in the context of the rendering waterfall, some properties are more expensive than others: property type cost
examples properties that affect an element's geometry or position trigger a style recalculation, a layout and a repaint.
Web Console remoting - Firefox Developer Tools
examples: { "from": "conn0.netevent14", "type": "networkeventupdate", "updatetype": "requestheaders", "headers": 10, "headerssize": 425 }, { "from": "conn0.netevent14", "type": "networkeventupdate", "updatetype": "requestcookies", "cookies": 0 }, { "from": "conn0.netevent14", "type": "networkeventupdate", "updatetype": "requestpostdata", "datasize": 1024, "discardrequestbody":...
ANGLE_instanced_arrays.drawArraysInstancedANGLE() - Web APIs
examples var ext = gl.getextension('angle_instanced_arrays'); ext.drawarraysinstancedangle(gl.points, 0, 8, 4); specifications specification status comment angle_instanced_arraysthe definition of 'angle_instanced_arrays' in that specification.
ANGLE_instanced_arrays.drawElementsInstancedANGLE() - Web APIs
examples var ext = gl.getextension('angle_instanced_arrays'); ext.drawelementsinstancedangle(gl.points, 2, gl.unsigned_short, 0, 4); specifications specification status comment angle_instanced_arraysthe definition of 'angle_instanced_arrays' in that specification.
AnalyserNode.fftSize - Web APIs
for more complete applied
examples/information, check out our voice-change-o-matic demo (see app.js lines 128–205 for relevant code).
Animation() - Web APIs
examples in the follow the white rabbit example, the animation() constructor is used to create an animation for the rabbitdownkeyframes using the document's timeline: var rabbitdownanimation = new animation(rabbitdownkeyframes, document.timeline); specifications specification status comment web animationsthe definition of 'animation()' in that specification.
Animation.commitStyles() - Web APIs
examples const divelem = document.queryselector('div'); document.body.addeventlistener('mousemove', evt => { let anim = divelem.animate( { transform: `translate(${ evt.clientx}px, ${evt.clienty}px)` }, { duration: 500, fill: 'forwards' } ); anim.commitstyles(); }); specifications specification status comment web animationsthe definition of 'commitstyles()' in tha...
Animation.finished - Web APIs
examples the following code waits until all animations running on the element elem have finished, then deletes the element from the dom tree: promise.all( elem.getanimations().map( function(animation) { return animation.finished } ) ).then( function() { return elem.remove(); } ); specifications specification status comment web animationsthe definition ...
Animation.id - Web APIs
examples in the follow the white rabbit example, you can assign the rabbitdownanimation an id like so: rabbitdownanimation.effect.id = "rabbitgo"; specifications specification status comment web animationsthe definition of 'animation.id' in that specification.
Animation.onfinish - Web APIs
examples animation.onfinish is used several times in the alice in web animations api land growing/shrinking alice game.
Animation.onremove - Web APIs
examples in our simple replace indefinite animations demo, you can see the following code: const divelem = document.queryselector('div'); document.body.addeventlistener('mousemove', evt => { let anim = divelem.animate( { transform: `translate(${ evt.clientx}px, ${evt.clienty}px)` }, { duration: 500, fill: 'forwards' } ); anim.commitstyles(); //anim.persist() anim.onremove = functio...
Animation.persist() - Web APIs
examples in our simple replace indefinite animations demo, you can see the following code: const divelem = document.queryselector('div'); document.body.addeventlistener('mousemove', evt => { let anim = divelem.animate( { transform: `translate(${ evt.clientx}px, ${evt.clienty}px)` }, { duration: 500, fill: 'forwards' } ); anim.commitstyles(); //anim.persist() anim.onremove = function() { console.log('animation removed'); } console.log(anim.replacestate); }); here we have a <div> ...
Animation.playbackRate - Web APIs
examples in the growing/shrinking alice game example, clicking or tapping the bottle causes alice's growing animation (alicechange) to reverse, causing her to shrink: var shrinkalice = function() { alicechange.playbackrate = -1; alicechange.play(); } // on tap or click, alice will shrink.
Animation.replaceState - Web APIs
examples in our simple replace indefinite animations demo, you can see the following code: const divelem = document.queryselector('div'); document.body.addeventlistener('mousemove', evt => { let anim = divelem.animate( { transform: `translate(${ evt.clientx}px, ${evt.clienty}px)` }, { duration: 500, fill: 'forwards' } ); anim.commitstyles(); //anim.persist() anim.onremove = functio...
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.timeline - Web APIs
examples here we set the animation's timeline to be the same as the document's timeline (this is the default timeline for all animations, by the way): animation.timeline = document.timeline; specifications specification status comment web animationsthe definition of 'animation.timeline' in that specification.
Animation.updatePlaybackRate() - Web APIs
examples a speed selector component would benefit from smooth updating of updateplaybackrate(), as demonstrated below: speedselector.addeventlistener('input', evt => { cartoon.updateplaybackrate(parsefloat(evt.target.value)); cartoon.ready.then(() => { console.log(`playback rate set to ${cartoon.playbackrate}`); }); }); specifications specification status comment web...
AudioBuffer - Web APIs
you can find the full source code at our webaudio-
examples repository; a running live version is also available.
AudioBufferSourceNode.start() - Web APIs
examples the most simple example just starts the audio buffer playing from the beginning — you don't need to specify any parameters in this case: source.start(); the following more complex example will, 1 second from now, start playing 10 seconds worth of sound starting 3 seconds into the audio buffer.
AudioBufferSourceNode - Web APIs
examples in this example, we create a two-second buffer, fill it with white noise, and then play it using an audiobuffersourcenode.
AudioConfiguration - Web APIs
examples //create media configuration to be tested const mediaconfig = { type : 'file', // 'record', 'transmission', or 'media-source' audio : { contenttype : "audio/ogg", // valid content type channels : 2, // audio channels used by the track bitrate : 132700, // number of bits used to encode 1s of audio samplerate : 5200 // number of audio samples making up t...
AudioContext.createMediaStreamDestination() - Web APIs
examples in the following simple example, we create a mediastreamaudiodestinationnode, an oscillatornode and a mediarecorder (the example will therefore only work in firefox and chrome at this time.) the mediarecorder is set up to record information from the mediastreamdestinationnode.
AudioContext.getOutputTimestamp() - Web APIs
performancetime: a point in the time coordinate system of a performance interface; the time after the document containing the audio context was first rendered
examples in the following code we start to play an audio file after a play button is clicked, and start off a requestanimationframe loop running, which constantly outputs the contexttime and performancetime.
AudioContext - Web APIs
examples basic audio context declaration: var audioctx = new audiocontext(); cross browser variant: var audiocontext = window.audiocontext || window.webkitaudiocontext; var audioctx = new audiocontext(); var oscillatornode = audioctx.createoscillator(); var gainnode = audioctx.creategain(); var finish = audioctx.destination; // etc.
AudioDestinationNode.maxChannelCount - Web APIs
ample the following would set up a simple audio graph, featuring an audiodestinationnode with maxchannelcount of 2: var audioctx = new audiocontext(); var source = audioctx.createmediaelementsource(mymediaelement); source.connect(gainnode); audioctx.destination.maxchannelcount = 2; gainnode.connect(audioctx.destination); to see a more complete implementation, check out one of our mdn web audio
examples, such as voice-change-o-matic or violent theremin.
AudioDestinationNode - Web APIs
their speakers), so you can get it hooked up inside an audio graph using only a few lines of code: var audioctx = new audiocontext(); var source = audioctx.createmediaelementsource(mymediaelement); source.connect(gainnode); gainnode.connect(audioctx.destination); to see a more complete implementation, check out one of our mdn web audio
examples, such as voice-change-o-matic or violent theremin.
AudioNode.connect() - Web APIs
examples connecting to an audio input the most obvious use of the connect() method is to direct the audio output from one node into the audio input of another node for further processing.
AudioParam.cancelScheduledValues() - Web APIs
examples var gainnode = audioctx.creategain(); gainnode.gain.setvaluecurveattime(wavearray, audioctx.currenttime, 2); //'gain' is the audioparam gainnode.gain.cancelscheduledvalues(audioctx.currenttime); specifications specification status comment web audio apithe definition of 'cancelscheduledvalues' in that specification.
AudioParam.exponentialRampToValueAtTime() - Web APIs
examples in this example, we have a media source with two control buttons (see the audio-param repo for the source code, or view the example live.) when these buttons are pressed, exponentialramptovalueattime() is used to fade the gain value up to 1.0, and down to 0, respectively.
AudioParam.setTargetAtTime() - Web APIs
time since starttime value 0 * timeconstant 0% 0.5 * timeconstant 39.3% 1 * timeconstant 63.2% 2 * timeconstant 86.5% 3 * timeconstant 95.0% 4 * timeconstant 98.2% 5 * timeconstant 99.3% n * timeconstant 1-e-n1 - e^{-n}
examples in this example, we have a media source with two control buttons (see the webaudio-
examples repo for the source code, or view the example live.) when these buttons are pressed, settargetattime() is used to fade the gain value up to 1.0, and down to 0, respectively, with the effect starting after 1 second, and the length of time the effect lasts being controlled by the timeconstant.
AudioParam.setValueAtTime() - Web APIs
examples this simple example features a media element source with two control buttons (see our webaudio-
examples repo for the source code, or view the example live).
AudioParam.setValueCurveAtTime() - Web APIs
examples in this example, we have a media source with a single button (see the webaudio-
examples repo for the source code, or view the example live.) when this button is pressed, setvaluecurveattime() is used to change the gain value between the values contained in the wavearray array: // create audio context var audiocontext = window.audiocontext || window.webkitaudiocontext; var audioctx = new audioco...
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...
AudioTrackList: addtrack event - Web APIs
bubbles no cancelable no interface trackevent event handler property onaddtrack
examples using addeventlistener(): const videoelement = document.queryselector('video'); videoelement.audiotracks.addeventlistener('addtrack', (event) => { console.log(`audio track: ${event.track.label} added`); }); using the onaddtrack event handler property: const videoelement = document.queryselector('video'); videoelement.audiotracks.onaddtrack = (event) => { console.log(`audio track: ${event.track.label} added`); }; specifications specification status html living standardthe definition of 'addtrack' in that specification.
AudioTrackList: change event - Web APIs
bubbles no cancelable no interface event event handler property onchange
examples using addeventlistener(): const videoelement = document.queryselector('video'); videoelement.audiotracks.addeventlistener('change', (event) => { console.log(`'${event.type}' event fired`); }); // changing the value of `enabled` will trigger the `change` event const toggletrackbutton = document.queryselector('.toggle-track'); toggletrackbutton.addeventlistener('click', () => { const track = videoelement.audiotracks[0]; track.enabled = !track.enabled; }); using the onchange event handler property: const videoelement = document.
AudioTrackList: removetrack event - Web APIs
bubbles no cancelable no interface trackevent event handler property onremovetrack
examples using addeventlistener(): const videoelement = document.queryselector('video'); videoelement.audiotracks.addeventlistener('removetrack', (event) => { console.log(`audio track: ${event.track.label} removed`); }); using the onremovetrack event handler property: const videoelement = document.queryselector('video'); videoelement.audiotracks.onremovetrack = (event) => { console.log(`audio track: ${event.track.label} removed`); }; specifications specification status html living standardthe definition of 'removetrack' in that specification.
AudioWorkletNode.port - Web APIs
examples to demonstrate bidirectional communication capabilities, we'll create an audioworkletprocessor, which will output silence and respond to ping requests from its audioworkletnode.
AudioWorkletNodeOptions - Web APIs
examples // fill in example snippet specifications specification status comment web audio apithe definition of 'audioworkletnodeoptions' in that specification.
AudioWorkletProcessor.port - Web APIs
examples to demonstrate bidirectional communication capabilities, we'll create an audioworkletprocessor, which will output silence and respond to ping requests from its audioworkletnode.
AuthenticatorAssertionResponse.authenticatorData - Web APIs
examples var options = { challenge: new uint8array(26), // will be another value, provided by the relying party server timeout: 60000 }; navigator.credentials.get({ publickey: options }) .then(function (assertionpkcred) { var authenticatordata = assertionpkcred.response.authenticatordata; // maybe try to convert the authenticatordata to see what's inside // send response and client e...
AuthenticatorAssertionResponse.signature - Web APIs
examples var options = { challenge: new uint8array(26), // will be another value, provided by the relying party server timeout: 60000 }; navigator.credentials.get({ publickey: options }) .then(function (assertionpkcred) { var signature = assertionpkcred.response.signature; // send response and client extensions to the server so that it can // go on with the authentication }).catch(f...
AuthenticatorAssertionResponse.userHandle - Web APIs
username, e-mail, phone number, etc.)
examples var options = { challenge: new uint8array(26), // will be another value, provided by the relying party server timeout: 60000 }; navigator.credentials.get({ publickey: options }) .then(function (assertionpkcred) { var userhandle = assertionpkcred.response.userhandle; // send response and client extensions to the server so that it can // go on with the authentication }).catch...
AuthenticatorAssertionResponse - Web APIs
examples var options = { challenge: new uint8array([/* bytes sent from the server */]) }; navigator.credentials.get({ "publickey": options }) .then(function (credentialinfoassertion) { var assertionresponse = credentialinfoassertion.response; // do something specific with the response // send assertion response back to the server // to proceed with the control of the credential })...
AuthenticatorAttestationResponse.attestationObject - Web APIs
examples var publickey = { challenge: /* from the server */, rp: { name: "example corp", id : "login.example.com" }, user: { id: new uint8array(16), name: "jdoe@example.com", displayname: "john doe" }, pubkeycredparams: [ { type: "public-key", alg: -7 } ] }; navigator.credentials.create({ publickey }) .then(function (newcredentialinfo) { var a...
AuthenticatorAttestationResponse.getTransports() - Web APIs
examples var publickey = { challenge: /* from the server */, rp: { name: "example corp", id : "login.example.com" }, user: { id: new uint8array(16), name: "jdoe@example.com", displayname: "john doe" }, pubkeycredparams: [ { type: "public-key", alg: -7 } ] }; navigator.credentials.create({ publickey }) .then(function (newcredentialinfo) { var t...
AuthenticatorAttestationResponse - Web APIs
examples var publickey = { challenge: /* from the server */, rp: { name: "example corp", id : "login.example.com" }, user: { id: new uint8array(16), name: "jdoe@example.com", displayname: "john doe" }, pubkeycredparams: [ { type: "public-key", alg: -7 } ] }; navigator.credentials.create({ publickey }) .then(function (newcredentialinfo) { var r...
AuthenticatorResponse.clientDataJSON - Web APIs
examples function arraybuffertostr(buf) { return string.fromcharcode.apply(null, new uint8array(buf)); } // pk is a publickeycredential that is the result of a create() or get() promise var clientdatastr = arraybuffertostr(pk.clientdatajson); var clientdataobj = json.parse(clientdatastr); console.log(clientdataobj.type); // "webauthn.create" or "webauthn.get" console.log(clientdataobj.challeng...
AuthenticatorResponse - Web APIs
examples getting an authenticatorassertionresponse var options = { challenge: new uint8array([/* bytes sent from the server */]) }; navigator.credentials.get({ "publickey": options }) .then(function (credentialinfoassertion) { var assertionresponse = credentialinfoassertion.response; // send assertion response back to the server // to proceed with the control of the credential }).catc...
Background Tasks API - Web APIs
the getrandomintinclusive() method comes from the
examples for math.random(); we'll just link to it below but it needs to be included here for the example to work.
BaseAudioContext.createBuffer() - Web APIs
examples first, a couple of simple trivial
examples, to help explain how the parameters are used: var audioctx = new audiocontext(); var buffer = audioctx.createbuffer(2, 22050, 44100); if you use this call, you will get a stereo buffer (two channels), that, when played back on an audiocontext running at 44100hz (very common, most normal sound cards run at this rate), will last for 0.5 seconds: 22050 f...
BaseAudioContext - Web APIs
examples basic audio context declaration: const audiocontext = new audiocontext(); cross browser variant: const audiocontext = window.audiocontext || window.webkitaudiocontext; const audiocontext = new audiocontext(); const oscillatornode = audiocontext.createoscillator(); const gainnode = audiocontext.creategain(); const finish = audiocontext.destination; specifications specification ...
BasicCardRequest - Web APIs
those are: amex cartebancaire diners discover jcb mastercard mir unionpay visa
examples in the following example, the paymentrequest() constructor is used to create a new payment request, which takes three objects as parameters — one containing details of the payment methods that can be used for the payment, one containing details of the actual order (such as items bought and shipping options), and an optional object that describes what data is needed to fullfil the payment (e.g.
BasicCardResponse - Web APIs
examples in the following example, the paymentrequest() constructor is used to create a new payment request, which takes three objects as parameters — one containing details of the payment methods that can be used for the payment, one containing details of the actual order (such as items bought and shipping options), and an optional object containing further options.
BeforeUnloadEvent - Web APIs
oke-width="2px" /><text x="201" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">beforeunloadevent</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} bubbles no cancelable yes target objects defaultview interface event
examples window.addeventlistener("beforeunload", function( event ) { event.returnvalue = "\o/"; }); // is equivalent to window.addeventlistener("beforeunload", function( event ) { event.preventdefault(); }); webkit-derived browsers don't follow the spec for the dialog box.
Blob - Web APIs
examples creating a blob the blob() constructor can create blobs from other objects.
Bluetooth.getAvailability() - Web APIs
examples the following snippet prints out a message in the console specifying wheter or not bluetooth is supported: navigator.bluetooth.getavailability().then(available => { if (available) console.log("this device supports bluetooth!"); else console.log("doh!
Body - Web APIs
examples the example below uses a simple fetch call to grab an image and display it in an <img> tag.
BroadcastChannel: message event - Web APIs
bubbles no cancelable no interface messageevent event handler property onmessage
examples live example in this example there's a "sender" <iframe> that broadcasts the contents of a <textarea> when the user clicks a button.
BroadcastChannel: messageerror event - Web APIs
bubbles no cancelable no interface messageevent event handler property onmessageerror
examples this code uses addeventlistener to listen for messages and errors: const channel = new broadcastchannel('example-channel'); channel.addeventlistener('message', (event) => { received.textcontent = event.data; }); channel.addeventlistener('messageerror', (event) => { console.error(event); }); the same, but using the onmessage and onmessageerror event handler properties: const channel = new broadcastchannel('example-channel'); channel.onmessage = (event) => { received.textcontent = event.data; }; channel.onmessag...
BroadcastChannel.name - Web APIs
syntax var str = channel.name;
examples // connect to a channel var bc = new broadcastchannel('test_channel'); // more operations (like postmessage, …) // log the channel name to the console console.log(bc.name); // "test_channel" // when done, disconnect from the channel bc.close(); specifications specification status comment html living standardthe definition of 'broadcastchannel.name' in that specification.
ByteLengthQueuingStrategy - Web APIs
examples const queueingstrategy = new bytelengthqueuingstrategy({ highwatermark: 1 }); const readablestream = new readablestream({ start(controller) { ...
CSS.escape() - Web APIs
examples basic results css.escape(".foo#bar") // "\.foo\#bar" css.escape("()[]{}") // "\(\)\[\]\{\}" css.escape('--a') // "--a" css.escape(0) // "\30 ", the unicode code point of '0' is 30 css.escape('\0') // "\ufffd", the unicode replacement character in context uses to escape a string for use as part of a selector, the escape() method can be used: var element = document.queryselector('#' + css.escape(id) + ' > img'); the escape() method can also be used for escaping strings, although it escapes c...
CSS numeric factory functions - Web APIs
css.vmax(number); css.cm(number); css.mm(number); css.q(number); css.in(number); css.pt(number); css.pc(number); css.px(number); // <angle> css.deg(number); css.grad(number); css.rad(number); css.turn(number); // <time> css.s(number); css.ms(number); // <frequency> css.hz(number); css.khz(number); // <resolution> css.dpi(number); css.dpcm(number); css.dppx(number); // <flex> css.fr(number);
examples we use the css.vmax() numeric factory function to create a cssunitvalue: let height = css.vmax(50); console.log( height ); // cssunitvalue {value: 50, unit: "vmax"} console.log( height.value ) // 50 console.log( height.unit ) // vmax in this example, we set the margin on our element using the css.px() factory function: myelement.attributestylemap.set('margin', css.px(40)); let curre...
CSS.registerProperty() - Web APIs
examples the following will register a custom property, --my-color, using registerproperty(), as a color, give it a default value, and have it not inherit its value: window.css.registerproperty({ name: '--my-color', syntax: '<color>', inherits: false, initialvalue: '#c0ffee', }); in this example, the custom property --my-color has been registered using the syntax <color> .
CSS.supports() - Web APIs
examples result = css.supports("text-decoration-style", "blink"); result = css.supports("display: flex"); result = css.supports("(--foo: red)"); result = css.supports(`(transform-style: preserve) or (-moz-transform-style: preserve) or (-o-transform-style: preserve) or (-webkit-transform-style: preserve)`); // result is true or false specification specification statu...
CSSImageValue - Web APIs
examples we create an element <button>magic wand</button> we add some css, including a background image requesting a binary file: button { display: inline-block; min-height: 100px; min-width: 100px; background: no-repeat 5% center url(https://mdn.mozillademos.org/files/16793/magicwand.png) aqua; } we get the element's style map.
CSSKeywordValue.CSSKeywordValue() - Web APIs
examples the following example resets the css display property to its defaults, setting the inline style attribute to style="display: initial" if viewed in the developer tools inspector.
CSSKeywordValue - Web APIs
examples the following example resets the css display property to its defaults, setting the inline style attribute to style="display: initial" if viewed in the developer tools inspector.
CSSMathSum - Web APIs
examples we create an element with a width determined using a calc() function, then console.log() the operator and values, and dig into the values a bit.
CSSMathValue.operator - Web APIs
interface value cssmathsum "sum" cssmathproduct "product" cssmathmin "min" cssmathmax "max" cssmathclamp "clamp" cssmathnegate "negate" cssmathinvert "invert"
examples we create an element with a width determined using a calc() function, then console.log() the operator.
CSSMathValue - Web APIs
examples we create an element with a width determined using a calc() function, then console.log() the operator.
CSSNumericValue.add() - Web APIs
examples let mathsum = css.px("23").add(css.percent("4")).add(css.cm("3")).add(css.in("9")); // prints "calc(23px + 4% + 3cm + 9in)" console.log(mathsum.tostring()); specifications specification status comment css typed om level 1the definition of 'add' in that specification.
CSSNumericValue.div() - Web APIs
examples let mathproduct = css.px("24").div(css.percent("4")); // prints "calc(24px / 4%)" mathproduct.tostring(); specifications specification status comment css typed om level 1the definition of 'div' in that specification.
CSSNumericValue.mul() - Web APIs
examples let mathsum = css.px("23").mul(css.percent("4")).mul(css.cm("3")).mul(css.in("9")); // prints "calc(23px * 4% * 3cm * 9in)" console.log(mathsum.tostring()); specifications specification status comment css typed om level 1the definition of 'mul' in that specification.
CSSNumericValue.parse() - Web APIs
exceptions syntaxerror tbd
examples the following returns a cssunitvalue object with a unit property equal to "px" and a value property equal to 42.
CSSNumericValue.sub() - Web APIs
examples let mathsum = css.px("23").sum(css.percent("4")).sum(css.cm("3")).sum(css.in("9")); // prints "calc(23px - 4% - 3cm - 9in)" console.log(mathsum.tostring()); and/or include a list of links to useful code samples that live elsewhere: specifications specification status comment css typed om level 1the definition of 'sub' in that specification.
CSSNumericValue.sum() - Web APIs
examples let mathsum = css.px("23").sum(css.percent("4")).sum(css.cm("3")).sum(css.in("9")); // prints "calc(23px - 4% - 3cm - 9in)" console.log(mathsum.tostring()); and/or include a list of links to useful code samples that live elsewhere: specifications specification status comment css typed om level 1the definition of 'sub' in that specification.
CSSNumericValue.to() - Web APIs
examples // prints "0.608542cm" console.log(css.px("23").to("com").tostring()); specifications specification status comment css typed om level 1the definition of 'to' in that specification.
CSSNumericValue.toSum() - Web APIs
examples let v = css.px("23").add(css.percent("4")).add(css.cm("3")).add(css.in("9")); v.tostring() // => "calc(23px + 4% + 3cm + 9in)" v.tosum("px", "percent").tostring() // => "calc(1000.39px + 4%)" specifications specification status comment css typed om level 1the definition of 'tosum' in that specification.
CSSNumericValue.type - Web APIs
examples let mathsum = css.px("23").sub(css.percent("4")).sub(css.cm("3")).sub(css.in("9")); // returns an object with the structure: {length: 1, percenthint: "length"} let cssnumerictype = mathsum.type(); specifications specification status comment css typed om level 1the definition of 'type' in that specification.
CSSPositionValue - Web APIs
examples the following example positions a container <div> 5 pixels from the top and 10 pixels from the left of the page.
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); // ou...
CSSPseudoElement.type - Web APIs
syntax var typeofpseudoelement = csspseudoelement.type; value a cssomstring containing one of the following values: "::before" "::after" "::marker"
examples the example below demonstrates the relationship between csspseudoelement.type and element.pseudo(): const myelement = document.queryselector('q'); const myselector = '::after'; const csspseudoelement = myelement.pseudo(myselector); const typeofpseudoelement = csspseudoelement.type; console.log(myselector === typeofpseudoelement); // outputs true specifications specification status comment css pseudo-elements level 4the definition of 'type' in th...
CSSPseudoElement - Web APIs
examples basic example using element.pseudo using pseudo-elements, most modern browsers will automatically add quotation marks around text inside a <q> element.
CSSRule - Web APIs
the relationships between these constants and the interfaces are: type value rule-specific interface comments and
examples cssrule.style_rule 1 cssstylerule the most common kind of rule: selector { prop1: val1; prop2: val2; } cssrule.import_rule 3 cssimportrule an @import rule.
CSSStyleDeclaration.setProperty() - Web APIs
if priority can be omitted, javascript has a special simpler syntax for setting a css property on a style declaration object: style.csspropertyname = 'value';
examples in this example we have three buttons, which can be pressed to dynamically alter our box paragraph's border, background color, and text color to random values (see the live example at the end of this section).
CSSStyleSheet.cssRules - Web APIs
examples individual rules within the stylesheet can then be accessed by index: let rulelist = document.stylesheets[0].cssrules; for (let i=0; i < rulelist.length; i++) { processrule(rulelist[i]); } rules can also be accessed using for...of: let rulelist = document.stylesheets[0].cssrules; for (let rule of rulelist) { processrule(rule); } however, because cssrule is not a proper array, you can...
CSSUnitValue.unit - Web APIs
examples the following creates a csspositionvalue from individual cssunitvalue constructors, then queries the cssunitvalue.unit.
CSSUnitValue.value - Web APIs
examples the following creates a csspositionvalue from individual cssunitvalue constructors, then queries the cssunitvalue.value.
CSSUnitValue - Web APIs
examples the following shows a method of creating a csspositionvalue from individual cssunitvalue constructors.
CSSUnparsedValue.CSSUnparsedValue() - Web APIs
examples let value = new cssunparsedvalue( ['4deg'] ), values = new cssunparsedvalue( ['1em', '#445566', '-45px'] ); console.log( value ); // cssunparsedvalue {0: "4deg", length: 1} console.log( values ); // cssunparsedvalue {0: "1em", 1: "#445566", 2: "-45px", length: 3} specifications specification status comment css typed om level 1the definition of 'cssunparsedvalue' in that specification.
CSSUnparsedValue.length - Web APIs
examples in this example we employ the cssunparsedvalue.cssunparsedvalue() constructor, then query the length: let values = new cssunparsedvalue( ['1em', '#445566', '-45px'] ); console.log( values.length ) // 3 specifications specification status comment css typed om level 1the definition of 'length' in that specification.
CSS Properties and Values API - Web APIs
examples the following uses css.registerproperty in javascript to type a css custom properties, --my-color, as a color, give it a default value, and not allow it to inherit its value: window.css.registerproperty({ name: '--my-color', syntax: '<color>', inherits: false, initialvalue: '#c0ffee', }); the same registration can take place in css using the following @property: @property --my-color...
Using the CSS Typed Object Model - Web APIs
we grab our stylepropertymapreadonly with the following javascript: const allcomputedstyles = document.queryselector('button').computedstylemap(); the following
examples reference allcomputedstyles: cssunparsedvalue the cssunparsedvalue represents custom properties: // cssunparsedvalue let unit = allcomputedstyles.get('--unit'); console.log( unit ) // cssunparsedvalue {0: " 1.2rem", length: 1} console.log (unit[0] ) // " 1.2rem" when we invoke get(), a custom property of type cssunparsedvalue is returned.
Cache.add() - Web APIs
the response status is not in the 200 range (i.e., not a successful response.) this occurs if the request does not return successfully, but also if the request is a cross-origin no-cors request (in which case the reported status is always 0.)
examples this code block waits for an installevent to fire, then calls waituntil() to handle the install process for the app.
Cache.addAll() - Web APIs
the response status is not in the 200 range (i.e., not a successful response.) this occurs if the request does not return successfully, but also if the request is a cross-origin no-cors request (in which case the reported status is always 0.)
examples this code block waits for an installevent to fire, then runs waituntil() to handle the install process for the app.
Cache.delete() - Web APIs
examples caches.open('v1').then(function(cache) { cache.delete('/images/image.png').then(function(response) { someuiupdatefunction(); }); }) specifications specification status comment service workersthe definition of 'cache: delete' in that specification.
Channel Messaging API - Web APIs
examples we have published a channel messaging basic demo on github (run it live too), which shows a really simple single message transfer between a page and an embedded <iframe>.
ChildNode.after() - Web APIs
examples inserting an element var parent = document.createelement("div"); var child = document.createelement("p"); parent.appendchild(child); var span = document.createelement("span"); child.after(span); console.log(parent.outerhtml); // "<div><p></p><span></span></div>" inserting text var parent = document.createelement("div"); var child = document.createelement("p"); parent.appendchild(child); c...
ChildNode.before() - Web APIs
examples inserting an element var parent = document.createelement("div"); var child = document.createelement("p"); parent.appendchild(child); var span = document.createelement("span"); child.before(span); console.log(parent.outerhtml); // "<div><span></span><p></p></div>" inserting text var parent = document.createelement("div"); var child = document.createelement("p"); parent.appendchild(child); ...
ChildNode.replaceWith() - Web APIs
examples using replacewith() var parent = document.createelement("div"); var child = document.createelement("p"); parent.appendchild(child); var span = document.createelement("span"); child.replacewith(span); console.log(parent.outerhtml); // "<div><span></span></div>" childnode.replacewith() is unscopable the replacewith() method is not scoped into the with statement.
Client.postMessage() - Web APIs
examples sending a message from a service worker to a client: addeventlistener('fetch', event => { event.waituntil(async function() { // exit early if we don't have access to the client.
Clients.get() - Web APIs
examples self.clients.get(id).then(function(client) { self.clients.openwindow(client.url); }); specifications specification status comment service workersthe definition of 'get()' in that specification.
Clients.matchAll() - Web APIs
examples clients.matchall(options).then(function(clientlist) { for (var i = 0 ; i < clientlist.length ; i++) { if (clientlist[i].url === 'index.html') { clients.openwindow(clientlist[i]); // or do something else involving the matching client } } }); specifications specification status comment service workersthe definition of 'clients: matchall' in that sp...
Clients.openWindow() - Web APIs
examples // send notification to os if applicable if (self.notification.permission === 'granted') { const notificationobject = { body: 'click here to view your messages.', data: { url: self.location.origin + '/some/path' }, // data: { url: 'http://example.com' }, }; self.registration.shownotification('you\'ve got messages!', notificationobject); } // notification click event listener s...
Clients - Web APIs
examples the following example shows an existing chat window or creates a new one when the user clicks a notification.
ClipboardItem() - Web APIs
examples the below example requests a png image using the fetch api, and in turn, the responses' blob() method, to create a new clipboarditem and write it to the clipboard, using the clipboard api.
ClipboardItem - Web APIs
examples writing to clipboard here we're writing a new clipboarditem.clipboarditem() to the clipboard by requesting a png image using the fetch api, and in turn, the responses' blob() method, to create the new clipboarditem.
console.assert() - Web APIs
examples the following code example demonstrates the use of a javascript object following the assertion: const errormsg = 'the # is not even'; for (let number = 2; number <= 5; number += 1) { console.log('the # is ' + number); console.assert(number % 2 === 0, {number: number, errormsg: errormsg}); // or, using es2015 object property shorthand: // console.assert(number % 2 === 0, {number,...
console.count() - Web APIs
examples for example, given code like this: let user = ""; function greet() { console.count(); return "hi " + user; } user = "bob"; greet(); user = "alice"; greet(); greet(); console.count(); console output will look something like this: "default: 1" "default: 2" "default: 3" "default: 4" the label is displayed as default because no explicit label was supplied.
DOMMatrixReadOnly.translate() - Web APIs
examples this svg contains two squares, one red and one blue, each positioned at the document origin: <svg width="250" height="250" viewbox="0 0 50 50"> <rect width="25" height="25" fill="red" /> <rect id="transformed" width="25" height="25" fill="blue" /> </svg> the following javascript first creates an identity matrix, then uses the translate() method to create a new, translated matrix — which ...
DOMParser - Web APIs
the possible values are the following: mimetype doc.constructor text/html document text/xml xmldocument application/xml xmldocument application/xhtml+xml xmldocument image/svg+xml xmldocument
examples parsing xml once you have created a parser object, you can parse xml from a string using the parsefromstring() method: let parser = new domparser() let doc = parser.parsefromstring(stringcontainingxmlsource, "application/xml") error handling note that if the parsing process fails, the domparser does not throw an exception, but instead returns an error document: <parsererror xmlns="http://w...
DOMPoint.fromPoint() - Web APIs
examples creating a mutable point from a read-only point if you have a dompointreadonly object, you can easily create a mutable copy of that point: var mutablepoint = dompoint.frompoint(readonlypoint); creating a 2d point this sample creates a 2d point, specifying an inline object that includes the values to use for x and y.
DOMPoint.DOMPoint() - Web APIs
examples this example creates a dompoint representing the top-left corner of the current window, then creates a second point based on the first, which is then offset by 100 pixels both vertically and horizontally.
DOMPoint - Web APIs
examples in the webxr device api, dompointreadonly values are used to represent positions and orientations.
DOMRect.DOMRect() - Web APIs
examples to create a new domrect, you could run a line of code like so: mydomrect = new domrect(0,0,100,100); // running 'mydomrect' in the console would then return // domrect { x: 0, y: 0, width: 100, height: 100, top: 0, right: 100, bottom: 100, left: 0 } specifications specification status comment geometry interfaces module level 1the definition of 'domrect()' in that specification.
DOMRectReadOnly() - Web APIs
examples to create a new dompoint, you could run a line of code like so: const mydomrect = new domrectreadonly(0, 0, 100, 100) // running 'mydomrect' in the console would then return // domrect { x: 0, y: 0, width: 100, height: 100, top: 0, right: 100, bottom: 100, left: 0 } specifications specification status comment geometry interfaces module level 1the definition of 'domrectreadonly()' in that specification.
DOMTokenList.add() - Web APIs
return value undefined
examples in the following example we retrieve the list of classes set on a <span> element as a domtokenlist using element.classlist.
DOMTokenList.entries() - Web APIs
examples in the following example we retrieve the list of classes set on a <span> element as a domtokenlist using element.classlist.
DOMTokenList.item() - Web APIs
examples in the following example we retrieve the list of classes set on a <span> element as a domtokenlist using element.classlist.
DOMTokenList.keys() - Web APIs
examples in the following example we retrieve the list of classes set on a <span> element as a domtokenlist using element.classlist.
DOMTokenList.length - Web APIs
examples in the following example we retrieve the list of classes set on a <span> element as a domtokenlist using element.classlist, then write the length of the list to the <span>'s node.textcontent.
DOMTokenList.remove() - Web APIs
return value undefined
examples in the following example we retrieve the list of classes set on a <span> element as a domtokenlist using element.classlist.
DOMTokenList.replace() - Web APIs
examples in the following example we retrieve the list of classes set on a <span> element as a domtokenlist using element.classlist.
DOMTokenList.toggle() - Web APIs
examples in the following example we retrieve the list of classes set on a <span> element as a domtokenlist using element.classlist.
DOMTokenList.value - Web APIs
syntax tokenlist.value; value a domstring
examples in the following example we retrieve the list of classes set on a <span> element as a domtokenlist using element.classlist, then write the value of the list to the <span>'s node.textcontent.
DOMTokenList.values() - Web APIs
examples in the following example we retrieve the list of classes set on a <span> element as a domtokenlist using element.classlist.
DOMTokenList - Web APIs
examples in the following simple example, we retrieve the list of classes set on a <p> element as a domtokenlist using element.classlist, add a class using domtokenlist.add(), and then update the node.textcontent of the <p> to equal the domtokenlist.
DataTransfer.files - Web APIs
example there are two live
examples of this interface: firefox only: http://jsfiddle.net/9c2ef/ all browsers: https://jsbin.com/hiqasek/ specifications specification status comment html living standardthe definition of 'files' in that specification.
DataTransfer - Web APIs
examples every method and property listed in this document has its own reference page and each reference page either directly includes an example of the interface or has a link to an example.
DedicatedWorkerGlobalScope: message event - Web APIs
bubbles no cancelable no interface messageevent event handler property onmessage
examples this code creates a new worker and sends it a message using worker.postmessage(): const worker = new worker("static/scripts/worker.js"); worker.addeventlistener('message', (event) => { console.log(`received message from worker: ${event.data}`) }); the worker can listen for this message using addeventlistener(): // inside static/scripts/worker.js self.addeventlistener('message', (event) => { console.log(`received message from parent: ${event.data}`); }); al...
DedicatedWorkerGlobalScope: messageerror event - Web APIs
bubbles no cancelable no interface messageevent event handler property onmessageerror
examples listen for messageerror using addeventlistener(): // inside worker.js self.addeventlistener('messageerror', (event) => { self.postmessage('error receiving message'); console.error(event); }); the same, but using the onmessageerror event handler property: // inside worker.js self.onmessageerror = (event) => { self.postmessage('error receiving message'); console.error(event); }; specifications specification status html living standard living standard ...
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...
DeviceProximityEvent - Web APIs
examples window.addeventlistener('deviceproximity', function(event) { console.log("value: " + event.value, "max: " + event.max, "min: " + event.min); }); ...
Document: DOMContentLoaded event - Web APIs
examples basic usage document.addeventlistener('domcontentloaded', (event) => { console.log('dom fully loaded and parsed'); }); delaying domcontentloaded <script> document.addeventlistener('domcontentloaded', (event) => { console.log('dom fully loaded and parsed'); }); for( let i = 0; i < 1000000000; i++) {} // this synchronous script is going to delay parsing of the dom, // so the do...
Document: animationend event - Web APIs
examples this example listens for the animationend event: document.addeventlistener('animationend', () => { console.log('animation ended'); }); the same, but using the onanimationend event handler property: document.onanimationend = () => { console.log('animation ended'); }; see a live example of this event.
Document: animationiteration event - Web APIs
examples this code uses animationiteration to keep track of the number of iterations an animation has completed: let iterationcount = 0; document.addeventlistener('animationiteration', () => { iterationcount++; console.log(`animation iteration count: ${iterationcount}`); }); the same, but using the onanimationiteration event handler property: let iterationcount = 0; document.onanimationiteration...
Document: animationstart event - Web APIs
examples this listens for the animationstart event and logs a message when it is fired: document.addeventlistener('animationstart', () => { console.log('animation started'); }); the same, but using onanimationstart: document.onanimationstart = () => { console.log('animation started'); }; see a live example of this event.
Document.characterSet - Web APIs
syntax var string = document.characterset;
examples <button onclick="console.log(document.characterset);"> log character encoding </button> <!-- displays document's character encoding in the dev console, such as "iso-8859-1" or "utf-8" --> specifications specification status comment domthe definition of 'characterset' in that specification.
Document.cookie - Web APIs
examples example #1: simple usage document.cookie = "name=oeschger"; document.cookie = "favorite_food=tripe"; function alertcookie() { alert(document.cookie); } <button onclick="alertcookie()">show cookies</button> example #2: get a sample cookie named test2 document.cookie = "test1=hello"; document.cookie = "test2=world"; const cookievalue = document.cookie .split('; ') .find(row => row.s...
Document: copy event - Web APIs
examples document.addeventlistener('copy', (event) => { console.log('copy action initiated') }); specifications specification status clipboard api and events working draft ...
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.currentscript' in that specification.
Document: cut event - Web APIs
examples document.addeventlistener('cut', (event) => { console.log('cut action initiated') }); specifications specification status clipboard api and events working draft ...
Document.domain - Web APIs
ions securityerror an attempt has been made to set domain under one of the following conditions: the document is inside a sandboxed <iframe> the document has no browsing context the document's effective domain is null the given value is not equal to the document's effective domain (or it is not a registerable domain suffix of it) the document-domain feature-policy is enabled
examples getting the domain for the uri http://developer.mozilla.org/docs/web, this example sets currentdomain to the string "developer.mozilla.org".
Document: dragend event - Web APIs
bubbles yes cancelable no default action varies interface dragevent event handler property ondragend
examples see the drag event for example code or this jsfiddle demo.
Document: drop event - Web APIs
bubbles yes cancelable yes default action varies interface dragevent event handler property ondrop
examples see the drag event for example code or this jsfiddle demo.
Document.fonts - Web APIs
examples doing operation after all fonts are loaded document.fonts.ready.then(function() { // any operation that needs to be done only after all the fonts // have finished loading can go here.
Document.forms - Web APIs
examples getting form information <!doctype html> <html lang="en"> <head> <title>document.forms example</title> </head> <body> <form id="robby"> <input type="button" onclick="alert(document.forms[0].id);" value="robby's form" /> </form> <form id="dave"> <input type="button" onclick="alert(document.forms[1].id);" value="dave's form" /> </form> <form id="paul"> <input type="button" onclick="ale...
Document: fullscreenerror event - Web APIs
examples const requestor = document.queryselector('div'); document.addeventlistener('fullscreenerror', (event) => { console.error('an error occurred changing into fullscreen'); console.log(event); }); requestor.requestfullscreen(); specifications specification status fullscreen api living standard ...
Document.getElementsByClassName() - Web APIs
examples get all elements that have a class of 'test': document.getelementsbyclassname('test') get all elements that have both the 'red' and 'test' classes: document.getelementsbyclassname('red test') get all elements that have a class of 'test', inside of an element that has the id of 'main': document.getelementbyid('main').getelementsbyclassname('test') get the first element with a class of 'test...
Document: gotpointercapture event - Web APIs
bubbles no cancelable no interface pointerevent event handler property ongotpointercapture
examples this example gets a <p> element and listens for the gotpointercapture event.
Document.hidden - Web APIs
syntax var boolean = document.hidden
examples document.addeventlistener("visibilitychange", function() { console.log( document.hidden ); // modify behavior...
Document: keydown event - Web APIs
to ignore all keydown events that are part of composition, do something like this (229 is a special value set for a keycode relating to an event that has been processed by an ime): eventtarget.addeventlistener("keydown", event => { if (event.iscomposing || event.keycode === 229) { return; } // do something });
examples addeventlistener keydown example this example logs the keyboardevent.code value whenever you press down a key.
Document: keyup event - Web APIs
to ignore all keyup events that are part of composition, do something like this (229 is a special value set for a keycode relating to an event that has been processed by an ime): eventtarget.addeventlistener("keyup", event => { if (event.iscomposing || event.keycode === 229) { return; } // do something });
examples this example logs the keyboardevent.code value whenever you release a key.
Document.location - Web APIs
syntax locationobj = document.location document.location = 'http://www.mozilla.org' // equivalent to document.location.href = 'http://www.mozilla.org'
examples console.log(document.location); // prints a location object to the console specifications specification status comment html living standardthe definition of 'document.location' in that specification.
Document: lostpointercapture event - Web APIs
bubbles no cancelable no interface pointerevent event handler property onlostpointercapture
examples this example listens for the lostpointercapture event, and captures the pointer for an element on pointerdown.
Document.onbeforescriptexecute - Web APIs
example function starting(e) { logmessage("starting script with id: " + e.target.id); } document.addeventlistener("beforescriptexecute", starting, true); view live
examples specification html5 ...
Document.open() - Web APIs
examples the following simple code opens the document and replaces its content with a number of different html fragments, before closing it again.
Document.origin - Web APIs
syntax var origin = document.origin;
examples var origin = document.origin; // on this page, returns:'https://developer.mozilla.org' var origin = document.origin; // on "about:blank", returns:'null' var origin = document.origin; // on "data:text/html,<b>foo</b>", returns:'null' ...
Document: paste event - Web APIs
examples document.addeventlistener('paste', (event) => { console.log('paste action initiated') }); specifications specification status clipboard api and events working draft ...
Document: pointerdown event - Web APIs
bubbles yes cancelable yes interface pointerevent event handler property onpointerdown
examples using addeventlistener(): document.addeventlistener('pointerdown', (event) => { console.log('pointer down event'); }); using the onpointerdown event handler property: document.onpointerdown = (event) => { console.log('pointer down event'); }; specifications specification status pointer events obsolete ...
Document: pointerenter event - Web APIs
bubbles no cancelable no interface pointerevent event handler property onpointerenter
examples using addeventlistener(): document.addeventlistener('pointerenter', (event) => { console.log('pointer entered element'); }); using the onpointerenter event handler property: document.onpointerenter = (event) => { console.log('pointer entered element'); }; specifications specification status pointer events obsolete ...
Document: pointerleave event - Web APIs
bubbles no cancelable no interface pointerevent event handler property onpointerleave
examples using addeventlistener(): document.addeventlistener('pointerleave', (event) => { console.log('pointer left element'); }); using the onpointerleave event handler property: document.onpointerleave = (event) => { console.log('pointer left element'); }; specifications specification status pointer events obsolete ...
Document: pointerlockchange event - Web APIs
bubbles yes cancelable no interface event event handler property onpointerlockchange
examples using addeventlistener(): document.addeventlistener('pointerlockchange', (event) => { console.log('pointer lock changed'); }); using the onpointerlockchange event handler property: document.onpointerlockchange = (event) => { console.log('pointer lock changed'); }; specifications specification status pointer lock candidate recommendation ...
Document: pointerlockerror event - Web APIs
bubbles yes cancelable no interface event event handler property onpointerlockerror
examples using addeventlistener(): const para = document.queryselector('p'); document.addeventlistener('pointerlockerror', (event) => { console.log('error locking pointer'); }); using the onpointerlockerror event handler property: document.onpointerlockerror = (event) => { console.log('error locking pointer'); }; specifications specification status pointer lock candidate recommendation ...
Document: pointermove event - Web APIs
bubbles yes cancelable yes interface pointerevent event handler property onpointermove
examples using addeventlistener(): document.addeventlistener('pointermove', (event) => { console.log('pointer moved'); }); using the onpointermove event handler property: document.onpointermove = (event) => { console.log('pointer moved'); }; specifications specification status pointer events obsolete ...
Document: pointerout event - Web APIs
bubbles yes cancelable yes interface pointerevent event handler property onpointerout
examples using addeventlistener(): document.addeventlistener('pointerout', (event) => { console.log('pointer moved out'); }); using the onpointerout event handler property: document.onpointerout = (event) => { console.log('pointer moved out'); }; specifications specification status pointer events obsolete ...
Document: pointerover event - Web APIs
bubbles yes cancelable yes interface pointerevent event handler property onpointerover
examples using addeventlistener(): document.addeventlistener('pointerover', (event) => { console.log('pointer moved in'); }); using the onpointerover event handler property: document.onpointerover = (event) => { console.log('pointer moved in'); }; specifications specification status pointer events obsolete ...
Document: pointerup event - Web APIs
bubbles yes cancelable yes interface pointerevent event handler property onpointerup
examples using addeventlistener(): document.addeventlistener('pointerup', (event) => { console.log('pointer up'); }); using the onpointerup event handler property: document.onpointerup = (event) => { console.log('pointer up'); }; specifications specification status pointer events obsolete ...
Document.querySelector() - Web APIs
character) document.queryselector('#foo\bar'); // does not match anything console.log('#foo\\bar'); // "#foo\bar" console.log('#foo\\\\bar'); // "#foo\\bar" document.queryselector('#foo\\\\bar'); // match the first div document.queryselector('#foo:bar'); // does not match anything document.queryselector('#foo\\:bar'); // match the second div </script>
examples finding the first element matching a class in this example, the first element in the document with the class "myclass" is returned: var el = document.queryselector(".myclass"); a more complex selector selectors can also be really powerful, as demonstrated in the following example.
Document.querySelectorAll() - Web APIs
examples obtaining a list of matches to obtain a nodelist of all of the <p> elements in the document: var matches = document.queryselectorall("p"); this example returns a list of all <div> elements within the document with a class of either note or alert: var matches = document.queryselectorall("div.note, div.alert"); here, we get a list of <p> elements whose immediate parent element is a <div> wit...
Document.readyState - Web APIs
examples different states of readiness switch (document.readystate) { case "loading": // the document is still loading.
Document: readystatechange event - Web APIs
bubbles no cancelable no interface event event handler property onreadystatechange
examples live example html <div class="controls"> <button id="reload" type="button">reload</button> </div> <div class="event-log"> <label>event log:</label> <textarea readonly class="event-log-contents" rows="8" cols="30"></textarea> </div> css body { display: grid; grid-template-areas: "control log"; } .controls { grid-area: control; display: flex; align-items: center; justify-content: center; } .event-log { grid-area: log; } .event-log-contents { resize: none; } label, button { display: block; } #reload { height: 2rem; } js ...
Document: selectionchange event - Web APIs
bubbles no cancelable no interface event event handler property onselectionchange
examples // addeventlistener version document.addeventlistener('selectionchange', () => { console.log(document.getselection()); }); // onselectionchange version document.onselectionchange = () => { console.log(document.getselection()); }; specifications specification status comment selection apithe definition of 'selectionchange' in that specification.
Document: selectstart event - Web APIs
bubbles yes cancelable yes interface event event handler property onselectstart
examples // addeventlistener version document.addeventlistener('selectstart', () => { console.log('selection started'); }); // onselectstart version document.onselectstart = () => { console.log('selection changed.'); }; specifications specification status comment selection apithe definition of 'selectstart' in that specification.
Document: touchcancel event - Web APIs
bubbles yes cancelable no interface touchevent event handler property ontouchcancel
examples code samples for those events are available on the dedicated page: touch events.
Document: touchend event - Web APIs
bubbles yes cancelable yes interface touchevent event handler property ontouchend
examples code samples for those events are available on the dedicated page: touch events.
Document: touchmove event - Web APIs
bubbles yes cancelable yes interface touchevent event handler property ontouchmove
examples code samples for those events are available on the dedicated page: touch events.
Document: touchstart event - Web APIs
bubbles yes cancelable yes interface touchevent event handler property ontouchstart
examples code samples for those events are available on the dedicated page: touch events.
Document: transitioncancel event - Web APIs
examples this code adds a listener to the transitioncancel event: document.addeventlistener('transitioncancel', () => { console.log('transition canceled'); }); the same, but using the ontransitioncancel property instead of addeventlistener(): document.ontransitioncancel = () => { console.log('transition canceled'); }; see a live example of this event.
Document: transitionend event - Web APIs
examples this code adds a listener to the transitionend event: document.addeventlistener('transitionend', () => { console.log('transition ended'); }); the same, but using the ontransitionend property instead of addeventlistener(): document.ontransitionend = () => { console.log('transition ended'); }; see a live example of this event.
Document: transitionrun event - Web APIs
examples this code adds a listener to the transitionrun event: document.addeventlistener('transitionrun', () => { console.log('transition is running but hasn't necessarily started transitioning yet'); }); the same, but using the ontransitionrun property instead of addeventlistener(): document.ontransitionrun = () => { console.log('transition started running'); }; see a live example of this event.
Document: transitionstart event - Web APIs
examples this code adds a listener to the transitionstart event: document.addeventlistener('transitionstart', () => { console.log('started transitioning'); }); the same, but using the ontransitionstart property instead of addeventlistener(): document.ontransitionrun = () => { console.log('started transitioning'); }; see a live example of this event.
Document.visibilityState - Web APIs
syntax var string = document.visibilitystate
examples document.addeventlistener("visibilitychange", function() { console.log( document.visibilitystate ); // modify behavior...
Document: wheel event - Web APIs
examples scaling an element via the wheel this example shows how to scale an element using the mouse (or other pointing device) wheel.
DocumentFragment.querySelector() - Web APIs
examples basic example in this basic example, the first element in the documentfragment with the class "myclass" is returned: var el = documentfragment.queryselector(".myclass"); css syntax and the method's argument the string argument pass to queryselector must follow the css syntax.
DocumentFragment.querySelectorAll() - Web APIs
examples this example returns a list of all div elements within the documentfragment with a class of either "note" or "alert": var matches = documentfrag.queryselectorall("div.note, div.alert"); specifications specification status comment selectors api level 1the definition of 'documentfragment.queryselectorall' in that specification.
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...
DocumentOrShadowRoot.styleSheets - Web APIs
examples function getstylesheet(unique_title) { for (var i=0; i<document.stylesheets.length; i++) { var sheet = document.stylesheets[i]; if (sheet.title == unique_title) { return sheet; } } } notes the returned list is ordered as follows: stylesheets retrieved from <link> headers are placed first, sorted in header order.
DocumentTimeline - Web APIs
examples we could share a single documenttimeline among multiple animations, thus allowing us to manipulate just that group of animations via their shared timeline.
Locating DOM elements using selectors - Web APIs
you may find
examples and details by reading the documentation for the element.queryselector() and element.queryselectorall() methods, as well as in the article code snippets for queryselector.
EXT_blend_minmax - Web APIs
examples var ext = gl.getextension('ext_blend_minmax'); gl.blendequation(ext.min_ext); gl.blendequation(ext.max_ext); gl.blendequationseparate(ext.min_ext, ext.max_ext); specifications specification status comment ext_blend_minmaxthe definition of 'ext_blend_minmax' in that specification.
EXT_color_buffer_half_float - Web APIs
examples var ext = gl.getextension('ext_color_buffer_half_float'); gl.renderbufferstorage(gl.renderbuffer, ext.rbga16f_ext, 256, 256); specifications specification status comment ext_color_buffer_half_floatthe definition of 'ext_color_buffer_half_float' in that specification.
EXT_disjoint_timer_query.createQueryEXT() - Web APIs
examples var ext = gl.getextension('ext_disjoint_timer_query'); var query = ext.createqueryext(); specifications specification status comment ext_disjoint_timer_querythe definition of 'ext_disjoint_timer_query' in that specification.
EXT_disjoint_timer_query.getQueryEXT() - Web APIs
examples var ext = gl.getextension('ext_disjoint_timer_query'); var startquery = ext.createqueryext(); ext.querycounterext(startquery, ext.timestamp_ext); var currentquery = ext.getqueryext(ext.timestamp_ext, ext.current_query_ext); specifications specification status comment ext_disjoint_timer_querythe definition of 'ext_disjoint_timer_query...
EXT_disjoint_timer_query - Web APIs
examples var ext = gl.getextension('ext_disjoint_timer_query'); specifications specification status comment ext_disjoint_timer_querythe definition of 'ext_disjoint_timer_query' in that specification.
EXT_float_blend - Web APIs
examples const gl = canvas.getcontext('webgl2'); // enable necessary extensions gl.getextension('ext_color_buffer_float'); gl.getextension('ext_float_blend'); const tex = gl.createtexture(); gl.bindtexture(gl.texture_2d, tex); // use floating point format gl.teximage2d(gl.texture_2d, 0, gl.rgba32f, 1, 1, 0, gl.rgba, gl.float, null); const fb = gl.createframebuffer(); gl.bindframebuffer(gl.framebuffer...
EXT_frag_depth - Web APIs
examples enable the extension: gl.getextension('ext_frag_depth'); now the output variable gl_fragdepthext is available to set a depth value of a fragment from within the fragment shader: <script type="x-shader/x-fragment"> void main() { gl_fragcolor = vec4(1.0, 0.0, 1.0, 1.0); gl_fragdepthext = 0.5; } </script> specifications specification status comment ext_frag_depththe...
EXT_sRGB - Web APIs
examples var ext = gl.getextension('ext_srgb'); var texture = gl.createtexture(); gl.bindtexture(gl.texture_2d, texture); gl.teximage2d(gl.texture_2d, 0, ext.srgb_ext, 512, 512, 0, ext.srgb_ext, gl.unsigned_byte, image); specifications specification status comment ext_srgbthe definition of 'ext_srgb' in that specification.
EXT_shader_texture_lod - Web APIs
2d sampler, vec4 coord, float lod) vec4 texturecubelodext(samplercube sampler, vec3 coord, float lod) vec4 texture2dgradext(sampler2d sampler, vec2 p, vec2 dpdx, vec2 dpdy) vec4 texture2dprojgradext(sampler2d sampler, vec3 p, vec2 dpdx, vec2 dpdy) vec4 texture2dprojgradext(sampler2d sampler, vec4 p, vec2 dpdx, vec2 dpdy) vec4 texturecubegradext(samplercube sampler, vec3 p, vec3 dpdx, vec3 dpdy)
examples enabling the extensions: gl.getextension('ext_shader_texture_lod'); shader code that avoids artifacts when wrapping texture coordinates: <script type="x-shader/x-fragment"> #extension gl_ext_shader_texture_lod : enable #extension gl_oes_standard_derivatives : enable uniform sampler2d mytexture; varying vec2 texcoord; void main(){ gl_fragcolor = texture2dgradext(mytexture, mod(texcoord, v...
EXT_texture_compression_bptc - Web APIs
examples var ext = gl.getextension('ext_texture_compression_bptc'); var texture = gl.createtexture(); gl.bindtexture(gl.texture_2d, texture); gl.compressedteximage2d(gl.texture_2d, 0, ext.compressed_rgba_bptc_unorm_ext, 128, 128, 0, texturedata); specifications specification status ext_texture_compression_bptc community approved ...
EXT_texture_compression_rgtc - Web APIs
examples var ext = gl.getextension('ext_texture_compression_rgtc'); var texture = gl.createtexture(); gl.bindtexture(gl.texture_2d, texture); gl.compressedteximage2d(gl.texture_2d, 0, ext.compressed_red_rgtc1_ext, 128, 128, 0, texturedata); specifications specification status ext_texture_compression_rgtc community approved ...
EXT_texture_filter_anisotropic - Web APIs
examples var texture = gl.createtexture(); gl.bindtexture(gl.texture_2d, texture); var ext = ( gl.getextension('ext_texture_filter_anisotropic') || gl.getextension('moz_ext_texture_filter_anisotropic') || gl.getextension('webkit_ext_texture_filter_anisotropic') ); if (ext){ var max = gl.getparameter(ext.max_texture_max_anisotropy_ext); gl.texparameterf(gl.texture_2d, ext.texture_max_anisotropy_...
EcKeyGenParams - Web APIs
this may be any of the following names for nist-approved curves: p-256 p-384 p-521
examples see the
examples for subtlecrypto.generatekey().
EcKeyImportParams - Web APIs
this may be any of the following names for nist-approved curves: p-256 p-384 p-521
examples see the
examples for subtlecrypto.importkey().
EffectTiming.delay - Web APIs
examples in the pool of tears example, each tear is passed a random delay via its timing object: // randomizer function var getrandommsrange = function(min, max) { return math.random() * (max - min) + min; } // loop through each tear tears.foreach(function(el) { // animate each tear el.animate( tearsfalling, { delay: getrandommsrange(-1000, 1000), // randomized for each tear ...
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 }); specificat...
EffectTiming.duration - Web APIs
examples in the pool of tears example, each tear is passed a random duration via its timing object: // randomizer function var getrandommsrange = function(min, max) { return math.random() * (max - min) + min; } // loop through each tear tears.foreach(function(el) { // animate each tear el.animate( tearsfalling, { delay: getrandommsrange(-1000, 1000), // randomized for each tear ...
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...
EffectTiming.iterations - Web APIs
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'...
Element: DOMActivate event - Web APIs
bubbles yes cancelable yes interface mouseevent
examples <svg xmlns="http://www.w3.org/2000/svg" version="1.2" baseprofile="tiny" xmlns:ev="http://www.w3.org/2001/xml-events" width="6cm" height="5cm" viewbox="0 0 600 500"> <desc>example: invoke an ecmascript function from a domactivate event</desc> <!-- ecmascript to change the radius --> <script type="application/ecmascript"><![cdata[ function change(evt) { var circle = evt.target; var currentradius = circle.getfloattrait("r"); if (currentradius == 100) circle.setfloattrait("r", currentradius * 2); ...
Element: MSManipulationStateChanged event - Web APIs
examples // listen for panning state change events outerscroller.addeventlistener("msmanipulationstatechanged", function(e) { // check to see if they lifted while pulled to the top if (e.currentstate == ms_manipulation_state_inertia && outerscroller.scrolltop === 0) { refreshitemsasync(); } }); specifications not part of any specification.
Element.animate() - Web APIs
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.
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.
Element: blur event - Web APIs
bubbles no cancelable no interface focusevent event handler property onblur sync / async sync composed yes
examples simple example html <form id="form"> <input type="text" placeholder="text input"> <input type="password" placeholder="password"> </form> javascript const password = document.queryselector('input[type="password"]'); password.addeventlistener('focus', (event) => { event.target.style.background = 'pink'; }); password.addeventlistener('blur', (event) => { event.target.style.background = ''; }); result event de...
Element.classList - Web APIs
examples const div = document.createelement('div'); div.classname = 'foo'; // our starting state: <div class="foo"></div> console.log(div.outerhtml); // use the classlist api to remove and add classes div.classlist.remove("foo"); div.classlist.add("anotherclass"); // <div class="anotherclass"></div> console.log(div.outerhtml); // if visible is set remove it, otherwise add it div.classlist.toggle("vis...
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="examp...
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="example"...
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="ex...
Element: contextmenu event - Web APIs
bubbles yes cancelable yes interface mouseevent event handler property oncontextmenu
examples in this example, the default action of the contextmenu event is canceled using preventdefault() when the contextmenu event is fired at the first paragraph.
Element: copy event - Web APIs
examples live example html <div class="source" contenteditable="true">try copying text from this box...</div> <div class="target" contenteditable="true">...and pasting it into this one</div> css div.source, div.target { border: 1px solid gray; margin: .5rem; padding: .5rem; height: 1rem; background-color: #e9eef1; } js const source = document.queryselector('div.source'); sou...
Element: cut event - Web APIs
examples live example html <div class="source" contenteditable="true">try cutting text from this box...</div> <div class="target" contenteditable="true">...and pasting it into this one</div> css div.source, div.target { border: 1px solid gray; margin: .5rem; padding: .5rem; height: 1rem; background-color: #e9eef1; } js const source = document.queryselector('div.source'); sou...
Element: dblclick event - Web APIs
bubbles yes cancelable yes interface mouseevent event handler property ondblclick
examples this example toggles the size of a card when you double click on it.
Element: error event - Web APIs
examples live example html <div class="controls"> <button id="img-error" type="button">generate image error</button> <img class="bad-img" /> </div> <div class="event-log"> <label>event log:</label> <textarea readonly class="event-log-contents" rows="8" cols="30"></textarea> </div> css body { display: grid; grid-template-areas: "control log"; } .controls { grid-area: control; displ...
Element: focus event - Web APIs
bubbles no cancelable no interface focusevent event handler property onfocus sync / async sync composed yes
examples simple example html <form id="form"> <input type="text" placeholder="text input"> <input type="password" placeholder="password"> </form> javascript const password = document.queryselector('input[type="password"]'); password.addeventlistener('focus', (event) => { event.target.style.background = 'pink'; }); password.addeventlistener('blur', (event) => { event.target.style.background = ''; }); result eve...
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 specificatio...
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...
Element: fullscreenerror event - Web APIs
examples const requestor = document.queryselector('div'); requestor.addeventlistener('fullscreenerror', (event) => { console.error('an error occurred changing into fullscreen'); console.log(event); }); requestor.requestfullscreen(); specifications specification status fullscreen api living standard ...
Element.getAnimations() - Web APIs
examples the following code snippet will wait for all animations on elem and its descendants to finish before removing the element from the document.
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.getBoundingClientRect() - Web APIs
t : document.body).scrolltop
examples this simple example retrieves the domrect object representing the bounding client rect of a simple <div> element, and prints out its properties below it.
Element.getElementsByClassName() - Web APIs
examples matching a single class to look for elements that include among their classes a single specified class, we just provide that class name when calling getelementsbyclassname(): element.getelementsbyclassname('test'); this example finds all elements that have a class of test, which are also a descendant of the element that has the id of main: document.getelementbyid('main').getelementsbyclassna...
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.hasPointerCapture() - Web APIs
examples <html> <script> function downhandler(ev) { const el = document.getelementbyid("target"); // element 'target' will receive/capture further events el.setpointercapture(ev.pointerid); /* ...
Element: keydown event - Web APIs
to ignore all keydown events that are part of composition, do something like this (229 is a special value set for a keycode relating to an event that has been processed by an ime): eventtarget.addeventlistener("keydown", event => { if (event.iscomposing || event.keycode === 229) { return; } // do something });
examples addeventlistener keydown example this example logs the keyboardevent.code value whenever you press down a key inside the <input> element.
Element: keyup event - Web APIs
to ignore all keyup events that are part of composition, do something like this (229 is a special value set for a keycode relating to an event that has been processed by an ime): eventtarget.addeventlistener("keyup", event => { if (event.iscomposing || event.keycode === 229) { return; } // do something });
examples addeventlistener keyup example this example logs the keyboardevent.code value whenever you release a key inside the <input> element.
Element: mousedown event - Web APIs
bubbles yes cancelable yes interface mouseevent event handler property onmousedown
examples the following example uses the mousedown, mousemove, and mouseup events to allow the user to draw on an html5 canvas.
Element: mousemove event - Web APIs
bubbles yes cancelable yes interface mouseevent event handler property onmousemove
examples the following example uses the mousedown, mousemove, and mouseup events to allow the user to draw on an html5 canvas.
Element: mouseout event - Web APIs
bubbles yes cancelable yes interface mouseevent event handler property onmouseout
examples the following
examples show the use of the mouseout event.
Element: mouseover event - Web APIs
bubbles yes cancelable yes interface mouseevent event handler property onmouseover
examples the following example illustrates the difference between mouseover and mouseenter events.
Element: mouseup event - Web APIs
bubbles yes cancelable yes interface mouseevent event handler property onmouseup
examples the following example uses the mousedown, mousemove, and mouseup events to allow the user to draw on an html5 canvas.
Element.outerHTML - Web APIs
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"> ...
Element: overflow event - Web APIs
bubbles yes cancelable yes interface uievent event handler property unknown
examples <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("wra...
Element.part - Web APIs
syntax let elementpartlist = element.part
examples the following excerpt is from our shadow-part example.
Element: paste event - Web APIs
examples live example html <div class="source" contenteditable="true">try copying text from this box...</div> <div class="target" contenteditable="true">...and pasting it into this one</div> css div.source, div.target { border: 1px solid gray; margin: .5rem; padding: .5rem; height: 1rem; background-color: #e9eef1; } js const target = document.queryselector('div.target'); tar...
Element.querySelectorAll() - Web APIs
examples dataset selector & attribute selectors <section class="box" id="sect1"> <div class="funnel-chart-percent1">10.900%</div> <div class="funnel-chart-percent2">3700.00%</div> <div class="funnel-chart-percent3">0.00%</div> </section> // dataset selectors const refs = [...document.queryselectorall(`[data-name*="funnel-chart-percent"]`)]; // attribute selectors // const refs = [...document.qu...
Element.scroll() - Web APIs
examples // put the 1000th vertical pixel at the top of the element element.scroll(0, 1000); using options: element.scroll({ top: 100, left: 100, behavior: 'smooth' }); specification specification status comment css object model (cssom) view modulethe definition of 'element.scroll()' in that specification.
Element.scrollBy() - Web APIs
examples // scroll an element element.scrollby(300, 300); using options: element.scrollby({ top: 100, left: 100, behavior: 'smooth' }); specification specification status comment css object model (cssom) view modulethe definition of 'element.scrollby()' in that specification.
Element.scrollTo() - Web APIs
examples element.scrollto(0, 1000); using options: element.scrollto({ top: 100, left: 100, behavior: 'smooth' }); specifications specification status comment css object model (cssom) view modulethe definition of 'element.scrollto()' in that specification.
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...
Element.setCapture() - Web APIs
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.shadowRoot - Web APIs
examples the following snippets are taken from our life-cycle-callbacks example (see it live also), which creates an element that displays a square of a size and color specified in the element's attributes.
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.slot - Web APIs
examples in our simple-template example (see it live), we create a trivial custom element example called <my-paragraph> in which a shadow root is attached and then populated using the contents of a template that contains a slot named my-text.
Element: touchcancel event - Web APIs
bubbles yes cancelable no interface touchevent event handler property ontouchcancel
examples code samples for those events are available on the dedicated page: touch events.
Element: touchend event - Web APIs
bubbles yes cancelable yes interface touchevent event handler property ontouchend
examples code samples for those events are available on the dedicated page: touch events.
Element: touchmove event - Web APIs
bubbles yes cancelable yes interface touchevent event handler property ontouchmove
examples code samples for those events are available on the dedicated page: touch events.
Element: touchstart event - Web APIs
bubbles yes cancelable yes interface touchevent event handler property ontouchstart
examples code samples for those events are available on the dedicated page: touch events.
Element: underflow event - Web APIs
bubbles yes cancelable yes interface uievent event handler property unknown
examples <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.gete...
Element: wheel event - Web APIs
examples scaling an element via the wheel this example shows how to scale an element using the mouse (or other pointing device) wheel.
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 eleme...
Comparison of Event Targets - Web APIs
examples <!doctype html> <html> <head> <meta charset="utf-8"> <meta http-equiv="x-ua-compatible" content="ie=edge"> <title>comparison of event targets</title> <style> table { border-collapse: collapse; height: 150px; width: 100%; } td { border: 1px solid #ccc; font-weight: bold; padding: 5px; ...
Event.currentTarget - Web APIs
syntax var currenteventtarget = event.currenttarget; value eventtarget
examples event.currenttarget is interesting to use when attaching the same event handler to several elements.
Event.preventDefault() - Web APIs
syntax event.preventdefault();
examples blocking default click handling toggling a checkbox is the default action of clicking on a checkbox.
Event.stopPropagation() - Web APIs
examples see example 5: event propagation in the
examples chapter for a more detailed example of this method and event propagation in the dom.
EventSource() - Web APIs
examples var evtsource = new eventsource('sse.php'); var eventlist = document.queryselector('ul'); evtsource.onmessage = function(e) { var newelement = document.createelement("li"); newelement.textcontent = "message: " + e.data; eventlist.appendchild(newelement); } note: you can find a full example on github — see simple sse demo using php.
EventSource.close() - Web APIs
examples var button = document.queryselector('button'); var evtsource = new eventsource('sse.php'); button.onclick = function() { console.log('connection closed'); evtsource.close(); } note: you can find a full example on github — see simple sse demo using php.
EventSource: error event - Web APIs
bubbles no cancelable no interface event or errorevent event handler property eventsource.onerror
examples var evtsource = new eventsource('sse.php'); // addeventlistener version evtsource.addeventlistener('error', (e) => { console.log("an error occurred while attempting to connect."); }); // onerror version evtsource.onerror = (e) => { console.log("an error occurred while attempting to connect."); }; specifications specification status html living standardthe definition of 'error event' in that specification.
EventSource: message event - Web APIs
bubbles no cancelable no interface messageevent event handler property eventsource.onmessage
examples in this basic example, an eventsource is created to receive events from the server; a page with the name sse.php is responsible for generating the events.
EventSource.onerror - Web APIs
syntax eventsource.onerror = function
examples evtsource.onerror = function() { console.log("eventsource failed."); }; note: you can find a full example on github — see simple sse demo using php.
EventSource.onmessage - Web APIs
syntax eventsource.onmessage = function
examples evtsource.onmessage = function(e) { var newelement = document.createelement("li"); newelement.textcontent = "message: " + e.data; eventlist.appendchild(newelement); } note: you can find a full example on github — see simple sse demo using php.
EventSource.onopen - Web APIs
syntax eventsource.onopen = function
examples evtsource.onopen = function() { console.log("connection to server opened."); }; note: you can find a full example on github — see simple sse demo using php.
EventSource: open event - Web APIs
bubbles no cancelable no interface event event handler property eventsource.onopen
examples var evtsource = new eventsource('sse.php'); // addeventlistener version evtsource.addeventlistener('open', (e) => { console.log("the connection has been established."); }); // onopen version evtsource.onopen = (e) => { console.log("the connection has been established."); }; specifications specification status html living standardthe definition of 'open event' in that specification.
EventSource.readyState - Web APIs
possible values are: 0 — connecting 1 — open 2 — closed
examples var evtsource = new eventsource('sse.php'); console.log(evtsource.readystate); note: you can find a full example on github — see simple sse demo using php.
EventSource.url - Web APIs
examples var evtsource = new eventsource('sse.php'); console.log(evtsource.url); note: you can find a full example on github — see simple sse demo using php.
EventSource.withCredentials - Web APIs
examples var evtsource = new eventsource('sse.php'); console.log(evtsource.withcredentials); note: you can find a full example on github — see simple sse demo using php.
EventSource - Web APIs
examples in this basic example, an eventsource is created to receive unnamed events from the server; a page with the name sse.php is responsible for generating the events.
EventTarget() - Web APIs
examples class myeventtarget extends eventtarget { constructor(mysecret) { super(); this._secret = mysecret; } get secret() { return this._secret; } }; let myeventtarget = new myeventtarget(5); let value = myeventtarget.secret; // == 5 myeventtarget.addeventlistener("foo", function(e) { this._secret = e.detail; }); let event = new customevent("foo", { detail: 7 }); myeventtarget.dispatchevent(event); let newvalue = myeventtarget.secret; // == 7 specifications specification status comment domthe definition of 'eventtarget() constructor' in that specification.
ExtendableEvent - Web APIs
examples this code snippet is from the service worker prefetch sample (see prefetch example live.) the code calls extendableevent.waituntil() in serviceworkerglobalscope.oninstall, delaying treating the serviceworkerregistration.installing worker as installed until the passed promise resolves successfully.
ExtendableMessageEvent() - Web APIs
examples var init = { data : 'hello message', source : messageportreference, ports : messageportlistreference } var myeme = new extendablemessageevent('message', init); specifications specification status comment service workersthe definition of 'extendablemessageevent()' in that specification.
ExtendableMessageEvent.data - Web APIs
examples when the following code is used inside a service worker to respond to a push messages by sending the data received via pushmessagedata to the main context via a channel message, the event object of onmessage will be a extendablemessageevent.
ExtendableMessageEvent.lastEventId - Web APIs
examples when the following code is used inside a service worker to respond to a push messages by sending the data received via pushmessagedata to the main context via a channel message, the event object of onmessage will be a extendablemessageevent.
ExtendableMessageEvent.origin - Web APIs
examples when the following code is used inside a service worker to respond to a push messages by sending the data received via pushmessagedata to the main context via a channel message, the event object of onmessage will be a extendablemessageevent.
ExtendableMessageEvent.ports - Web APIs
examples when the following code is used inside a service worker to respond to a push messages by sending the data received via pushmessagedata to the main context via a channel message, the event object of onmessage will be a extendablemessageevent.
ExtendableMessageEvent.source - Web APIs
examples when the following code is used inside a service worker to respond to a push messages by sending the data received via pushmessagedata to the main context via a channel message, the event object of onmessage will be a extendablemessageevent.
ExtendableMessageEvent - Web APIs
examples in the below example a page gets a handle to the serviceworker object via serviceworkerregistration.active, and then calls its postmessage() function.
FederatedCredential - Web APIs
examples var cred = new federatedcredential({ id: id, name: name, provider: 'https://account.google.com', iconurl: iconurl }); // store it navigator.credentials.store(cred) .then(function() { // do something else.
File - Web APIs
see using files from web applications for more information and
examples.
FileException - Web APIs
examples of invalid modifications include moving a directory into its own child or moving a file into its parent directory without changing its name.
FileReader: abort event - Web APIs
bubbles no cancelable no interface progressevent event handler property filereader.onabort
examples live example html <div class="example"> <div class="file-select"> <label for="avatar">choose a profile picture:</label> <input type="file" id="avatar" name="avatar" accept="image/png, image/jpeg"> </div> <img src="" class="preview" height="200" alt="image preview..."> <div class="event-log"> <label>event log:</label> <textarea readonly class="event-log-contents"></textarea> </div> </div> css img.preview { margin: 1rem 0; } .event-log-c...
FileReader: error event - Web APIs
bubbles no cancelable no interface progressevent event handler property filereader.onerror
examples const fileinput = document.queryselector('input[type="file"]'); const reader = new filereader(); function handleselected(e) { const selectedfile = fileinput.files[0]; if (selectedfile) { reader.addeventlistener('error', () => { console.error(`error occurred reading file: ${selectedfile.name}`); }); reader.addeventlistener('load', () => { console.error(`file: ${selectedfile.name} read successfully`); }); reader.readasdataurl(selectedfile); } ...
FileReader: load event - Web APIs
bubbles no cancelable no interface progressevent event handler property filereader.onload
examples live example html <div class="example"> <div class="file-select"> <label for="avatar">choose a profile picture:</label> <input type="file" id="avatar" name="avatar" accept="image/png, image/jpeg"> </div> <img src="" class="preview" height="200" alt="image preview..."> <div class="event-log"> <label>event log:</label> <textarea readonly class="event-log-contents"></textarea> </div> </div> css img.preview { margin: 1rem 0; } .event-log-contents { width: 18rem; height: 5rem; border: ...
FileReader: loadend event - Web APIs
bubbles no cancelable no interface progressevent event handler property filereader.onloadend
examples live example html <div class="example"> <div class="file-select"> <label for="avatar">choose a profile picture:</label> <input type="file" id="avatar" name="avatar" accept="image/png, image/jpeg"> </div> <img src="" class="preview" height="200" alt="image preview..."> <div class="event-log"> <label>event log:</label> <textarea readonly class="event-log-contents"></textarea> </div> </div> css img.preview { margin: 1rem 0; } .event-log-contents { width: 18rem; heigh...
FileReader: loadstart event - Web APIs
bubbles no cancelable no interface progressevent event handler property filereader.onloadstart
examples live example html <div class="example"> <div class="file-select"> <label for="avatar">choose a profile picture:</label> <input type="file" id="avatar" name="avatar" accept="image/png, image/jpeg"> </div> <img src="" class="preview" height="200" alt="image preview..."> <div class="event-log"> <label>event log:</label> <textarea readonly class="event-log-contents"></textarea> </div> </div> css img.preview { margin: 1rem 0; } .event-log-contents { width: 18rem; height: 5rem; ...
FileReader: progress event - Web APIs
bubbles no cancelable no interface progressevent event handler property filereader.onprogress
examples live example html <div class="example"> <div class="file-select"> <label for="avatar">choose a profile picture:</label> <input type="file" id="avatar" name="avatar" accept="image/png, image/jpeg"> </div> <img src="" class="preview" height="200" alt="image preview..."> <div class="event-log"> <label>event log:</label> <textarea readonly class="event-log-contents"></textarea> </div> </div> css img.preview { margin: 1rem 0; } .event-log-contents { width: 18rem; height: 5rem;...
FontFaceSet.check() - Web APIs
examples document.fonts.check("12px courier"); // returns true if the font courier is available at 12px document.fonts.check("12px myfont", "ß"); // returns true if the font 'myfont' has a ß character.
FontFaceSet.load() - Web APIs
examples // returns a promise that will be fulfilled or rejected according the success to load myfont // the code in 'then' can assume the availability of that font.
FormDataEvent() - Web APIs
examples let fd = new formdata(); fd.append('test', 'test'); let fdev = new formdataevent('formdata', { formdata: fd }); for (let value of fdev.formdata.values()) { console.log(value); } specifications specification status comment html living standardthe definition of 'formdataevent' in that specification.
FormDataEvent.formData - Web APIs
examples // grab reference to form const formelem = document.queryselector('form'); // submit handler formelem.addeventlistener('submit', (e) => { // on form submission, prevent default e.preventdefault(); // construct a formdata object, which fires the formdata event new formdata(formelem); }); // formdata handler to retrieve data formelem.addeventlistener('formdata', (e) => { console.log('formdata fired'); // get the form data from the event object let data = e.formdata; for (var value of data.values()) { console.log(value); } // s...
FormDataEvent - Web APIs
examples // grab reference to form const formelem = document.queryselector('form'); // submit handler formelem.addeventlistener('submit', (e) => { // on form submission, prevent default e.preventdefault(); // construct a formdata object, which fires the formdata event new formdata(formelem); }); // formdata handler to retrieve data formelem.addeventlistener('formdata', (e) => { console.lo...
Fullscreen API - Web APIs
view live
examples watching for the enter key when the page is loaded, this code is run to set up an event listener to watch for the enter key.
Gamepad.hand - Web APIs
examples tbc specifications specification status comment gamepad extensionsthe definition of 'hand' in that specification.
Geolocation.getCurrentPosition() - Web APIs
enablehighaccuracy: false | true
examples var options = { enablehighaccuracy: true, timeout: 5000, maximumage: 0 }; function success(pos) { var crd = pos.coords; console.log('your current position is:'); console.log(`latitude : ${crd.latitude}`); console.log(`longitude: ${crd.longitude}`); console.log(`more or less ${crd.accuracy} meters.`); } function error(err) { console.warn(`error(${err.code}): ${err.message}`);...
Geolocation.watchPosition() - Web APIs
examples var id, target, options; function success(pos) { var crd = pos.coords; if (target.latitude === crd.latitude && target.longitude === crd.longitude) { console.log('congratulations, you reached the target'); navigator.geolocation.clearwatch(id); } } function error(err) { console.warn('error(' + err.code + '): ' + err.message); } target = { latitude : 0, longitude: 0 }; opti...
Using the Geolocation API - Web APIs
you could use it like so: function errorcallback(error) { alert(`error(${error.code}): ${error.message}`); };
examples in the following example the geolocation api is used to retrieve the user's latitude and longitude.
Geolocation API - Web APIs
examples in the following example the geolocation api is used to retrieve the user's latitude and longitude.
GlobalEventHandlers.onformdata - Web APIs
examples // grab reference to form const formelem = document.queryselector('form'); // submit handler formelem.addeventlistener('submit', (e) => { // on form submission, prevent default e.preventdefault(); // construct a formdata object, which fires the formdata event new formdata(formelem); }); // formdata handler to retrieve data formelem.onformdata = (e) => { console.log('formdata fire...
GlobalEventHandlers.onload - Web APIs
examples window.onload = function() { init(); dosomethingelse(); }; <!doctype html> <html> <head> <title>onload test</title> // es5 <script> function load() { console.log("load event detected!"); } window.onload = load; </script> // es2015 <script> const load = () => { console.log("load event detected!"); } window.onload = load; </script> </head> <body> <p>the load eve...
GlobalEventHandlers.onloadend - Web APIs
examples html content <img src="myimage.jpg"> javascript content // 'loadstart' fires first, then 'load', then 'loadend' image.addeventlistener('load', function(e) { console.log('image loaded'); }); image.addeventlistener('loadstart', function(e) { console.log('image load started'); }); image.addeventlistener('loadend', function(e) { console.log('image load finished'); }); ...
GlobalEventHandlers.onloadstart - Web APIs
examples html content <img src="myimage.jpg"> javascript content // 'loadstart' fires first, then 'load', then 'loadend' image.addeventlistener('load', function(e) { console.log('image loaded'); }); image.addeventlistener('loadstart', function(e) { console.log('image load started'); }); image.addeventlistener('loadend', function(e) { console.log('image load finished'); }); specifications specification status comment html li...
GlobalEventHandlers.onresize - Web APIs
examples window size logger <p>resize the browser window to fire the <code>resize</code> event.</p> <p>window height: <span id="height"></span></p> <p>window width: <span id="width"></span></p> const heightoutput = document.queryselector('#height'); const widthoutput = document.queryselector('#width'); function resize() { heightoutput.textcontent = window.innerheight; widthoutput.textcontent = window.innerwidth; } window.onresize = resize; specification...
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.
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.
msAudioCategory - Web APIs
examples include the following local media playback scenarios: local playlist streaming radio streaming playlist music videos streaming audio/radio, youtube, netflix, etc.
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.
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.mozOpaque - Web APIs
syntax var opaque = canvas.mozopaque; canvas.mozopaque = true;
examples given this <canvas> element: <canvas id="canvas" width="300" height="300" moz-opaque></canvas> you can get or set the mozopaque property.
HTMLCanvasElement.toBlob() - Web APIs
exceptions securityerror the canvas's bitmap is not origin clean; at least some of its contents come from secure
examples getting a file representing the canvas once you have drawn content into a canvas, you can convert it into a file of any supported image format.
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...
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: cancel event - Web APIs
bubbles no cancelable yes interface event event handler oncancel
examples live example html <dialog class="example-dialog"> <button class="close" type="reset">close</button> </dialog> <button class="open-dialog">open dialog</button> <div class="result"></div> css button, div { margin: .5rem; } js const result = document.queryselector('.result'); const dialog = document.queryselector('.example-dialog'); dialog.addeventlistener('cancel', (event) => { ...
HTMLDialogElement: close event - Web APIs
bubbles no cancelable no interface event event handler property onclose
examples live example html <dialog class="example-dialog"> <button class="close" type="reset">close</button> </dialog> <button class="open-dialog">open dialog</button> <div class="result"></div> css button, div { margin: .5rem; } js const result = document.queryselector('.result'); const dialog = document.queryselector('.example-dialog'); dialog.addeventlistener('close', (event) => { result.textcontent = 'dialog was closed'; }); const opendialog = document.queryselector('.open-dialog'); opendialog.addeventlistener('click', () => { if (typeof ...
HTMLDialogElement.open - Web APIs
examples the following example shows a simple button that, when clicked, opens a <dialog> containing a form via the showmodal() method.
HTMLDialogElement - Web APIs
examples the following example shows a simple button that, when clicked, opens a <dialog> containing a form via the htmldialogelement.showmodal() function.
HTMLElement: animationcancel event - Web APIs
bubbles yes cancelable no interface animationevent event handler property onanimationcancel
examples this code gets an element that's currently being animated and adds a listener to the animationcancel event.
HTMLElement: animationend event - Web APIs
bubbles yes cancelable no interface animationevent event handler property onanimationend
examples this example gets an element that's being animated and listens for the animationend event: const animated = document.queryselector('.animated'); animated.addeventlistener('animationend', () => { console.log('animation ended'); }); the same, but using the onanimationend event handler property: const animated = document.queryselector('.animated'); animated.onanimationend = () => { console.log...
HTMLElement: animationiteration event - Web APIs
bubbles yes cancelable no interface animationevent event handler property onanimationiteration
examples this code uses animationiteration to keep track of the number of iterations an animation has completed: const animated = document.queryselector('.animated'); let iterationcount = 0; animated.addeventlistener('animationiteration', () => { iterationcount++; console.log(`animation iteration count: ${iterationcount}`); }); the same, but using the onanimationiteration event handler property: ...
HTMLElement: animationstart event - Web APIs
bubbles yes cancelable no interface animationevent event handler property onanimationstart
examples this listens for the animationstart event and logs a message when it is fired: const animated = document.queryselector('.animated'); animated.addeventlistener('animationstart', () => { console.log('animation started'); }); the same, but using onanimationstart: const animated = document.queryselector('.animated'); animated.onanimationstart = () => { console.log('animation started'); }; ...
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.
HTMLElement: change event - Web APIs
examples <select> element html <label>choose an ice cream flavor: <select class="ice-cream" name="ice-cream"> <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 re...
HTMLElement: lostpointercapture event - Web APIs
bubbles yes cancelable no interface pointerevent event handler property onlostpointercapture
examples this example listens for the lostpointercapture event for an element, and captures the pointer for the element on pointerdown.
HTMLElement: pointerdown event - Web APIs
bubbles yes cancelable yes interface pointerevent event handler property onpointerdown
examples using addeventlistener(): const para = document.queryselector('p'); para.addeventlistener('pointerdown', (event) => { console.log('pointer down event'); }); using the onpointerdown event handler property: const para = document.queryselector('p'); para.onpointerdown = (event) => { console.log('pointer down event'); }; specifications specification status pointer eve...
HTMLElement: pointerenter event - Web APIs
bubbles no cancelable no interface pointerevent event handler property onpointerenter
examples using addeventlistener(): const para = document.queryselector('p'); para.addeventlistener('pointerenter', (event) => { console.log('pointer entered element'); }); using the onpointerenter event handler property: const para = document.queryselector('p'); para.onpointerenter = (event) => { console.log('pointer entered element'); }; specifications specification status pointer events ...
HTMLElement: pointerleave event - Web APIs
bubbles no cancelable no interface pointerevent event handler property onpointerleave
examples using addeventlistener(): const para = document.queryselector('p'); para.addeventlistener('pointerleave', (event) => { console.log('pointer left element'); }); using the onpointerleave event handler property: const para = document.queryselector('p'); para.onpointerleave = (event) => { console.log('pointer left element'); }; specifications specification status pointer events obsolete ...
HTMLElement: pointermove event - Web APIs
examples to add a handler for pointermove events using addeventlistener(): const para = document.queryselector('p'); para.addeventlistener('pointermove', (event) => { console.log('pointer moved'); }); you can also use the onpointermove event handler property: const para = document.queryselector('p'); para.onpointermove = (event) => { console.log('pointer moved'); }; specifications spe...
HTMLElement: pointerout event - Web APIs
bubbles yes cancelable yes interface pointerevent event handler property onpointerout
examples using addeventlistener(): const para = document.queryselector('p'); para.addeventlistener('pointerout', (event) => { console.log('pointer moved out'); }); using the onpointerout event handler property: const para = document.queryselector('p'); para.onpointerout = (event) => { console.log('pointer moved out'); }; specifications specification status pointer events ...
HTMLElement: pointerover event - Web APIs
bubbles yes cancelable yes interface pointerevent event handler property onpointerover
examples using addeventlistener(): const para = document.queryselector('p'); para.addeventlistener('pointerover', (event) => { console.log('pointer moved in'); }); using the onpointerover event handler property: const para = document.queryselector('p'); para.onpointerover = (event) => { console.log('pointer moved in'); }; specifications specification status pointer events obsolete ...
HTMLElement: pointerup event - Web APIs
bubbles yes cancelable yes interface pointerevent event handler property onpointerup
examples using addeventlistener(): const para = document.queryselector('p'); para.addeventlistener('pointerup', (event) => { console.log('pointer up'); }); using the onpointerup event handler property: const para = document.queryselector('p'); para.onpointerup = (event) => { console.log('pointer up'); }; specifications specification status pointer events obsolete ...
HTMLElement: transitioncancel event - Web APIs
bubbles yes cancelable no interface transitionevent event handler property globaleventhandlers.ontransitioncancel
examples this code gets an element that has a transition defined and adds a listener to the transitioncancel event: const transition = document.queryselector('.transition'); transition.addeventlistener('transitioncancel', () => { console.log('transition canceled'); }); the same, but using the ontransitioncancel property instead of addeventlistener(): const transition = document.queryselector('.transition'); transition.ontransitioncancel = () => { console.log('transition cance...
HTMLElement: transitionend event - Web APIs
examples this code gets an element that has a transition defined and adds a listener to the transitionend event: const transition = document.queryselector('.transition'); transition.addeventlistener('transitionend', () => { console.log('transition ended'); }); the same, but using the ontransitionend: const transition = document.queryselector('.transition'); transition.ontransitionend = () => { c...
HTMLElement: transitionrun event - Web APIs
bubbles yes cancelable no interface transitionevent event handler property ontransitionrun
examples this code adds a listener to the transitionrun event: el.addeventlistener('transitionrun', () => { console.log('transition is running but hasn\'t necessarily started transitioning yet'); }); the same, but using the ontransitionrun property instead of addeventlistener(): el.ontransitionrun = () => { console.log('transition started running, and will start transitioning when the transition delay has expired'); }; live example in the following example, we have a simple <div> element, styled with a transition tha...
HTMLElement: transitionstart event - Web APIs
bubbles yes cancelable no interface transitionevent event handler property ontransitionstart
examples this code adds a listener to the transitionstart event: element.addeventlistener('transitionstart', () => { console.log('started transitioning'); }); the same, but using the ontransitionstart property instead of addeventlistener(): element.ontransitionrun = () => { console.log('started transitioning'); }; live example in the following example, we have a simple <div> element, styled with a transition that includes a delay: <div class="transition">hover over me</div> <div class="message"></div> .trans...
HTMLFontElement.color - Web APIs
the format of the string must follow one of the following html microsyntaxes: microsyntax description
examples valid name 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...
HTMLFontElement.face - Web APIs
the format of the string 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 a...
HTMLFontElement.size - Web APIs
the format of the string must follow one of the following html microsyntaxes: microsyntax description
examples valid size number string 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 ...
HTMLFormElement: formdata event - Web APIs
general info bubbles no cancelable no interface formdataevent event handler property globaleventhandlers.onformdata
examples // grab reference to form const formelem = document.queryselector('form'); // submit handler formelem.addeventlistener('submit', (e) => { // on form submission, prevent default e.preventdefault(); // construct a formdata object, which fires the formdata event new formdata(formelem); }); // formdata handler to retrieve data formelem.addeventlistener('formdata', (e) => { console.log('formdata fired'); ...
HTMLFormElement: reset event - Web APIs
bubbles yes (although specified as a simple event that doesn't bubble) cancelable yes interface event event handler property globaleventhandlers.onreset
examples this example uses eventtarget.addeventlistener() to listen for form resets, and logs the current event.timestamp whenever that occurs.
HTMLFormElement: submit event - Web APIs
examples this example uses eventtarget.addeventlistener() to listen for form submit, and logs the current event.timestamp whenever that occurs, then prevents the default action of submitting the form.
HTMLFormElement - Web APIs
examples creating a new form element, modifying its attributes, then submitting it: const f = document.createelement("form"); // create a form document.body.appendchild(f); // add it to the document body f.action = "/cgi-bin/some.cgi"; // add action and method attributes f.method = "post"; f.submit(); // call the form's submit() method extract inform...
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.host - Web APIs
syntax string = object.host; object.host = string;
examples var anchor = document.createelement("a"); anchor.href = "https://developer.mozilla.org/htmlhyperlinkelementutils.host" anchor.host == "developer.mozilla.org" anchor.href = "https://developer.mozilla.org:443/htmlhyperlinkelementutils.host" anchor.host == "developer.mozilla.org" // the port number is not included because 443 is the scheme's default port anchor.href = "https://developer.mozilla.org:4097/htmlhyperlinkelementutils.host" anchor.host == "developer.mozilla.org:4097" specifications specification status comment html liv...
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
syntax string = object.origin;
examples // on this page, returns the origin var result = window.location.origin; // returns:'https://developer.mozilla.org' specifications specification status comment html living standardthe definition of 'htmlhyperlinkelementutils.origin' in that specification.
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 liv...
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.
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.
srcdoc - Web APIs
examples var iframe = document.createelement("iframe"); iframe.srcdoc = `<!doctype html><p>hello world!</p>`; document.body.appendchild(iframe); specifications specification status comment html living standardthe definition of 'htmliframeelement: srcdoc' in that specification.
Image() - Web APIs
examples var myimage = new image(100, 200); myimage.src = 'picture.jpg'; document.body.appendchild(myimage); this would be the equivalent of defining the following html tag inside the <body>: <img width="100" height="200" src="picture.jpg"> specifications specification status comment html living standardthe definition of 'image()' in that specification.
HTMLImageElement.complete - Web APIs
examples consider a photo library app that provides the ability to open images into a lightbox mode for improved viewing as well as editing of the image.
HTMLImageElement.decoding - Web APIs
examples var img = new image(); img.decoding = 'sync'; img.src = 'img/logo.png'; specifications specification status comment html living standardthe definition of 'decoding' in that specification.
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.src - Web APIs
examples specifying a single image html <img src="https://udn.realityripple.com/samples/d6/7ab36d79bb.jpg" width="160" alt="slices of grapefruit, looking yummy."> result using src with an image set when using a set of images with the srcset property, the src serves as either a fallback for older browsers, or as the 1x size of the image.
HTMLInputElement: invalid event - Web APIs
examples if a form is submitted with an invalid value, the submittable elements are checked and, if an error is found, the invalid event will fire on the invalid element.
HTMLInputElement: search event - Web APIs
examples // addeventlistener version const input = document.queryselector('input[type="search"]'); input.addeventlistener('search', () => { console.log("the term searched for was " + input.value); }) // onsearch version const input = document.queryselector('input[type="search"]'); input.onsearch = () => { console.log("the term searched for was " + input.value); }) specifications this event is not ...
HTMLMarqueeElement - Web APIs
examples <marquee>this text will scroll from right to left</marquee> <marquee direction="up">this text will scroll from bottom to top</marquee> <marquee direction="down" width="250" height="200" behavior="alternate" style="border:solid"> <marquee behavior="alternate"> this text will bounce </marquee> </marquee> specifications specification status comment html living ...
HTMLMediaElement: abort event - Web APIs
bubbles no cancelable no interface event event handler property onabort
examples const video = document.queryselector('video'); const videosrc = 'https://path/to/video.webm'; video.addeventlistener('abort', () => { console.log(`abort loading: ${videosrc}`); }); const source = document.createelement('source'); source.setattribute('src', videosrc); source.setattribute('type', 'video/webm'); video.appendchild(source); specifications specification status html living standard living standard html5 recommendation ...
HTMLMediaElement: canplay event - Web APIs
bubbles no cancelable no interface event target element default action none event handler property globaleventhandlers.oncanplay specification html5 media
examples these
examples add an event listener for the htmlmediaelement's canplay event, then post a message when that event handler has reacted to the event firing.
HTMLMediaElement: canplaythrough event - Web APIs
bubbles no cancelable no interface event target element default action none event handler property globaleventhandlers.oncanplaythrough specification html5 media
examples these
examples add an event listener for the htmlmediaelement's canplaythrough event, then post a message when that event handler has reacted to the event firing.
HTMLMediaElement.duration - Web APIs
examples var obj = document.createelement('video'); console.log(obj.duration); // nan specifications specification status comment html living standardthe definition of 'htmlmediaelement.duration' in that specification.
HTMLMediaElement: durationchange event - Web APIs
bubbles no cancelable no interface event target element default action none event handler property globaleventhandlers.ondurationchange specification html5 media
examples these
examples add an event listener for the htmlmediaelement's durationchange event, then post a message when that event handler has reacted to the event firing.
HTMLMediaElement: emptied event - Web APIs
bubbles no cancelable no interface event target element default action none event handler property globaleventhandlers.onemptied specification html5 media
examples these
examples add an event listener for the htmlmediaelement's emptied event, then post a message when that event handler has reacted to the event firing.
HTMLMediaElement: ended event - Web APIs
bubbles no cancelable no interface event target element default action none event handler property globaleventhandlers.onended specification html5 media this event is also defined in media capture and streams and web audio api
examples these
examples add an event listener for the htmlmediaelement's ended event, then post a message when that event handler has reacted to the event firing.
HTMLMediaElement: error event - Web APIs
bubbles no cancelable no interface event event handler property onerror
examples const video = document.queryselector('video'); const videosrc = 'https://path/to/video.webm'; video.addeventlistener('error', () => { console.error(`error loading: ${videosrc}`); }); video.setattribute('src', videosrc); specifications specification status html living standard living standard html5 recommendation ...
HTMLMediaElement: pause event - Web APIs
general info bubbles no cancelable no interface event target element default action none event handler property globaleventhandlers.onpause specification html5 media
examples these
examples add an event listener for the htmlmediaelement's pause event, then post a message when that event handler has reacted to the event firing.
HTMLMediaElement: play event - Web APIs
bubbles no cancelable no interface event target element default action none event handler property globaleventhandlers.onplay specification html5 media
examples these
examples add an event listener for the htmlmediaelement's play event, then post a message when that event handler has reacted to the event firing.
HTMLMediaElement: playing event - Web APIs
bubbles no cancelable no interface event target element default action none event handler property globaleventhandlers.onplaying specification html5 media
examples these
examples add an event listener for the htmlmediaelement's playing event, then post a message when that event handler has reacted to the event firing.
HTMLMediaElement: ratechange event - Web APIs
bubbles no cancelable no interface event target element default action none event handler property globaleventhandlers.onratechange specification html5 media
examples these
examples add an event listener for the htmlmediaelement's ratechange event, then post a message when that event handler has reacted to the event firing.
HTMLMediaElement.seekable - Web APIs
examples var video = document.queryselector("video"); var timerangesobject = video.seekable; var timeranges = []; //go through the object and output an array for (let count = 0; count < timerangesobject.length; count ++) { timeranges.push([timerangesobject.start(count), timerangesobject.end(count)]); } specifications specification status comment html living standardthe definition of 'htmlmediaelement' in that specification.
HTMLMediaElement: seeked event - Web APIs
bubbles no cancelable no interface event target element default action none event handler property globaleventhandlers.onseeked specification html5 media
examples these
examples add an event listener for the htmlmediaelement's seeked event, then post a message when that event handler has reacted to the event firing.
HTMLMediaElement: seeking event - Web APIs
bubbles no cancelable no interface event target element default action none event handler property globaleventhandlers.onseeking specification html5 media
examples these
examples add an event listener for the htmlmediaelement's seeking event, then post a message when that event handler has reacted to the event firing.
HTMLMediaElement.setSinkId() - Web APIs
exceptions exception explanation domexception no permission to use the requested device
examples const devices = await navigator.mediadevices.enumeratedevices(); const audiodevices = devices.filter(device => device.kind === 'audiooutput'); const audio = document.createelement('audio'); await audio.setsinkid(audiodevices[0].deviceid); console.log('audio is being played on ' + audio.sinkid); specifications specification status comment audio output devices apithe def...
HTMLMediaElement: stalled event - Web APIs
bubbles no cancelable no interface event target element default action none event handler property globaleventhandlers.onstalled specification html5 media
examples these
examples add an event listener for the htmlmediaelement's stalled event, then post a message when that event handler has reacted to the event firing.
HTMLMediaElement: suspend event - Web APIs
bubbles no cancelable no interface event target element default action none event handler property globaleventhandlers.onsuspend specification html5 media
examples these
examples add an event listener for the htmlmediaelement's suspend event, then post a message when that event handler has reacted to the event firing.
HTMLMediaElement.textTracks - Web APIs
examples we start with a <video> that has several <track> children <video controls poster="/images/sample.gif"> <source src="sample.mp4" type="video/mp4"> <source src="sample.ogv" type="video/ogv"> <track kind="captions" src="samplecaptions.vtt" srclang="en"> <track kind="descriptions" src="sampledescriptions.vtt" srclang="en"> <track kind="chapters" src="samplechapters.vtt" srclang="en"> <...
HTMLMediaElement: timeupdate event - Web APIs
bubbles no cancelable no interface event target element default action none event handler property globaleventhandlers.ontimeupdate specification html5 media
examples these
examples add an event listener for the htmlmediaelement's timeupdate event, then post a message when that event handler has reacted to the event firing.
HTMLMediaElement: volumechange event - Web APIs
bubbles no cancelable no interface event target element default action none event handler property globaleventhandlers.onvolumechange specification html5 media
examples these
examples add an event listener for the htmlmediaelement's volumechange event, then post a message when that event handler has reacted to the event firing.
HTMLMediaElement: waiting event - Web APIs
bubbles no cancelable no interface event target element default action none event handler property globaleventhandlers.onwaiting specification html5 media
examples these
examples add an event listener for the htmlmediaelement's waiting event, then post a message when that event handler has reacted to the event firing.
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</optio...
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
examples <div id="user" data-id="1234567890" data-user="johndoe" data-date-of-birth>john doe</div> const el = document.queryselector('#user'); // el.id === 'user' // el.dataset.id === '1234567890' // el.dataset.user === 'johndoe' // el.dataset.dateofbirth === '' // set the data attribute el.dataset.dateofbirth = '1960-10-03'; // result: el.dataset.dateofbirth === 1960-10-03 delete el.dataset.dateofbi...
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.g...
HTMLOrForeignElement.nonce - Web APIs
examples retrieving a nonce value in the past, not all browsers supported the nonce idl attribute, so a workaround is to try to use getattribute as a fallback: let nonce = script['nonce'] || script.getattribute('nonce'); however, recent browsers version hide nonce values that are accessed this way (an empty string will be returned).
HTMLScriptElement.referrerPolicy - Web APIs
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.
HTMLScriptElement - Web APIs
examples dynamically importing scripts let's create a function that imports new scripts within a document creating a <script> node immediately before the <script> that hosts the following code (through document.currentscript).
HTMLSelectElement.add() - Web APIs
examples creating elements from scratch var sel = document.createelement("select"); var opt1 = document.createelement("option"); var opt2 = document.createelement("option"); opt1.value = "1"; opt1.text = "option: value 1"; opt2.value = "2"; opt2.text = "option: value 2"; sel.add(opt1, null); sel.add(opt2, null); /* produces the following, conceptually: <select> <option value="1">option: val...
HTMLSelectElement.item() - Web APIs
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...
HTMLSlotElement.assignedElements() - Web APIs
examples let slots = this.shadowroot.queryselector('slot'); let elements = slots.assignedelements({flatten: true}); specifications specification status comment html living standardthe definition of 'assignedelements()' in that specification.
HTMLSlotElement: slotchange event - Web APIs
examples element.setattribute('slot', slotname); // element.assignedslot = $slot element.removeattribute('slot'); // element.assignedslot = null the following snippet is taken from our slotchange example (see it live also).
HTMLTextAreaElement - Web APIs
examples autogrowing textarea example make a textarea autogrow while typing: javascript function autogrow (ofield) { if (ofield.scrollheight > ofield.clientheight) { ofield.style.height = ofield.scrollheight + "px"; } } css textarea.noscrollbars { overflow: hidden; width: 300px; height: 100px; } html <form> <fieldset> <legend>your comments</legend> <p><textarea class="noscr...
HTMLTimeElement.dateTime - Web APIs
the format of the string must follow one of the following html microsyntaxes: microsyntax description
examples valid month string yyyy-mm 2011-11, 2013-05 valid date string yyyy-mm-dd 1887-12-01 valid yearless date string mm-dd 11-12 valid time string hh:mm hh:mm:ss hh:mm:ss.mmm 23:59 12:15:47 12:15:52.998 valid local date and time string yyyy-mm-dd hh:mm yyyy-mm-dd hh:mm:ss yyyy-mm-dd hh:mm:ss.mmm yyyy-mm-ddthh:mm yyyy-mm-ddthh:mm:ss yyyy-mm-ddthh:mm:ss.mmm 2013-12-25 11:12 1972-07-25 13:43:07 ...
HTMLTrackElement: cuechange event - Web APIs
bubbles no cancelable no interface event event handler oncuechange
examples on the texttrack you can set up a listener for the cuechange event on a texttrack using the addeventlistener() method: track.addeventlistener('cuechange', function () { let cues = track.activecues; // array of current cues }); or you can just set the oncuechange event handler property: track.oncuechange = function () { let cues = track.activecues; // array of current cues } on the track element the underlying texttrack, indicated by the track property, receives a...
The HTML DOM API - Web APIs
eventsource
examples in this example, an <input> element's input event is monitored in order to update the state of a form's "submit" button based on whether or not a given field currently has a value.
HTML Drag and Drop API - Web APIs
examples and demos copying and moving elements with the datatransfer interface copying and moving elements with the datatransferlistitem interface dragging and dropping files (firefox only): http://jsfiddle.net/9c2ef/ dragging and dropping files (all browsers): https://jsbin.com/hiqasek/ a parking project using the drag and drop api: https://park.glitch.me/ (you can edit here) specifications...
HashChangeEvent - Web APIs
examples syntax options for a hash change you can listen for the hashchange event using any of the following options: window.onhashchange = funcref; or <body onhashchange="funcref();"> or window.addeventlistener("hashchange", funcref, false); basic example function locationhashchanged() { if (location.hash === '#somecoolfeature') { somecoolfeature(); } } window.addeventlistener('hashc...
History.back() - Web APIs
syntax history.back()
examples the following short example causes a button on the page to navigate back one entry in the session history.
History.forward() - Web APIs
syntax history.forward()
examples the following
examples create a button that moves forward one step in the session history.
History.go() - Web APIs
examples to move back one page (the equivalent of calling back()): history.go(-1) to move forward a page, just like calling forward(): history.go(1) to move forward two pages: history.go(2); to move backwards by two pages: history.go(-2); and, finally either of the following statements will reload the current page: history.go(); history.go(0); specifications specification status ...
History.replaceState() - Web APIs
examples suppose https://www.mozilla.org/foo.html executes the following javascript: const stateobj = { foo: 'bar' }; history.pushstate(stateobj, '', 'bar.html'); the explanation of these two lines above can be found in the example of pushstate() method section of the working with the history api article.
History.state - Web APIs
examples the code below logs the value of history.state before using the pushstate() method to push a value to the history.
IDBCursor.request - Web APIs
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.
IDBCursor - Web APIs
examples in this simple fragment we create a transaction, retrieve an object store, then use a cursor to iterate through all the records in the object store.
IDBDatabase: abort event - Web APIs
bubbles yes cancelable no interface event event handler property onabort
examples this example opens a database (creating the database if it does not exist), then opens a transaction, adds a listener to the abort event, then aborts the transaction to trigger the event.
IDBDatabase: close event - Web APIs
bubbles no cancelable no interface event event handler property onerror
examples this example opens a database and listens for the close event: // open the database const dbopenrequest = window.indexeddb.open('todolist', 4); dbopenrequest.onupgradeneeded = (event) => { const db = event.target.result; // create an objectstore for this database const objectstore = db.createobjectstore('todolist', { keypath: 'tasktitle' }); // define what data items the objectstore ...
IDBDatabase: error event - Web APIs
bubbles yes cancelable no interface event event handler property onerror
examples this example opens a database and tries to add a record, listening for the error event for the add() operation (this will occur if, for example, a record with the given tasktitle already exists): // open the database const dbopenrequest = window.indexeddb.open('todolist', 4); dbopenrequest.onupgradeneeded = (event) => { const db = event.target.result; // create an objectstore for this database const objectstore = db.createobjectstore('todolist', { keypath: 'tasktitle' }); // define what data items the objectstore will contain ...
IDBDatabase: versionchange event - Web APIs
bubbles no cancelable no interface event event handler property onversionchange
examples this example opens a database and, on success, adds a listener to versionchange: // open the database const dbopenrequest = window.indexeddb.open('nonexistent', 4); dbopenrequest.onupgradeneeded = event => { const db = event.target.result; // create an objectstore for this database const objectstore = db.createobjectstore('todolist', { keypath: 'tasktitle' }); // define what data items the objectstore will contain objectstore.createindex('hours', 'hours', { unique: false }); objectstore.cre...
IDBKeyRange.bound() - Web APIs
note: for a more complete example allowing you to experiment with key range, have a look at the idbkeyrange directory in the indexeddb-
examples repo (view the example live too.) function displaydata() { var keyrangevalue = idbkeyrange.bound("a", "f"); var transaction = db.transaction(['fthings'], 'readonly'); var objectstore = transaction.objectstore('fthings'); objectstore.opencursor(keyrangevalue).onsuccess = function(event) { var cursor = event.target.result; if(cursor) { var listitem = document.createele...
IDBLocaleAwareKeyRange - Web APIs
examples function displaydata() { var keyrangevalue = idblocaleawarekeyrange.bound("a", "f"); var transaction = db.transaction(['fthings'], 'readonly'); var objectstore = transaction.objectstore('fthings'); var myindex = objectstore.index('lname'); myindex.opencursor(keyrangevalue).onsuccess = function(event) { var cursor = event.target.result; if(cursor) { var tablerow = docume...
IDBOpenDBRequest: blocked event - Web APIs
bubbles no cancelable no interface idbversionchangeevent event handler property onblocked
examples using addeventlistener(): // open the database const dbopenrequest = window.indexeddb.open('todolist', 4); dbopenrequest.onupgradeneeded = (event) => { const db = event.target.result; db.onerror = () => { console.log('error creating database'); }; // create an objectstore for this database var objectstore = db.createobjectstore('todolist', { keypath: 'tasktitle' }); // define what data items the objectstore will contain objectstore.createindex('hours', 'hours', { unique: false }); objectst...
IDBOpenDBRequest: upgradeneeded event - Web APIs
bubbles no cancelable no interface event event handler onupgradeneeded
examples this example opens a database and handles the upgradeneeded event by making any necessary updates to the object store.
IDBRequest: error event - Web APIs
bubbles yes cancelable no interface event event handler property onerror
examples this example opens a database and tries to add a record, listening for the error event for the add() operation (this will occur if, for example, a record with the given tasktitle already exists): // open the database const dbopenrequest = window.indexeddb.open('todolist', 4); dbopenrequest.addeventlistener('upgradeneeded', event => { const db = event.target.result; db.onerror = () => { console.log('error creating database'); }; // create an objectstore for this database var objectstore = db.createobjectstore('todolist', { keypath: 'tasktitle' }); // define what data item...
IDBRequest: success event - Web APIs
bubbles no cancelable no interface event event handler property onsuccess
examples this example tries to open a database and listens for the success event using addeventlistener(): // open the database const openrequest = window.indexeddb.open('todolist', 4); openrequest.onupgradeneeded = (event) => { const db = event.target.result; db.onerror = () => { console.log('error creating database'); }; // create an objectstore for this database var objectstore = db.createobjectstore('todolist', { keypath: 'tasktitle' }); // define what data items the objectstore will contain objectstore.createindex('hours', 'hours', { unique: false }); objectstore.createindex('minutes...
IDBTransaction: abort event - Web APIs
examples this example opens a database (creating the database if it does not exist), then opens a transaction, adds a listener to the abort event, then aborts the transaction to trigger the event.
IDBTransaction.commit() - Web APIs
examples // open a read/write db transaction, ready for adding the data var transaction = db.transaction(["mydb"], "readwrite"); // report on the success of opening the transaction transaction.oncomplete = function(event) { note.innerhtml += '<li>transaction completed: database modification finished.</li>'; }; transaction.onerror = function(event) { note.innerhtml += '<li>transaction not opened due...
IDBTransaction: complete event - Web APIs
bubbles no cancelable no interface event event handler property oncomplete
examples using addeventlistener(): // open the database const dbopenrequest = window.indexeddb.open('todolist', 4); dbopenrequest.onupgradeneeded = event => { const db = event.target.result; db.onerror = () => { console.log('error creating database'); }; // create an objectstore for this database var objectstore = db.createobjectstore('todolist', { keypath: 'tasktitle' }); // define what data items the objectstore will contain objectstore.createindex('hours', 'hours', { unique: false }); objectstore.createindex('minutes', 'minutes', { unique: false }); objectstore.c...
IDBTransaction: error event - Web APIs
bubbles yes cancelable no interface event event handler property onerror
examples this example opens a database and tries to add a record, listening for the error event for the add() operation (this will occur if, for example, a record with the given tasktitle already exists): // open the database const dbopenrequest = window.indexeddb.open('todolist', 4); dbopenrequest.onupgradeneeded = (event) => { const db = event.target.result; // create an objectstore for this database const objectstore = db.createobjectstore('todolist', { keypath: 'tasktitle' }); // define what data items the objectstore will conta...
IDBTransaction - Web APIs
you should code defensively in case the object is not available anymore: var myidbtransaction = window.idbtransaction || window.webkitidbtransaction || { read_write: "readwrite" };
examples in the following code snippet, we open a read/write transaction on our database and add some data to an object store.
IIRFilterNode() - Web APIs
examples let feedforward = [0.00020298, 0.0004059599, 0.00020298]; let feedbackward = [1.0126964558, -1.9991880801, 0.9873035442]; const audiocontext = window.audiocontext || window.webkitaudiocontext; const audioctx = new audiocontext(); const iirfilter = new iirfilternode(audioctx, { feedforward: feedforward, feedback: feedbackward }); specifications specification status comment ...
IIRFilterNode.getFrequencyResponse() - Web APIs
examples in the following example we are using an iir filter on a media stream (for a complete full demo, see our stream-source-buffer demo live, or read its source.) as part of this demo, we get the frequency responses for this iir filter, for five sample frequencies.
ImageBitmap.close() - Web APIs
syntax void imagebitmap.close()
examples var offscreen = new offscreencanvas(256, 256); var gl = offscreen.getcontext('webgl'); // ...
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
examples creating a blank imagedata object this example creates an imagedata object that is 200 pixels wide and 100 pixels tall, containing a total of 20,000 pixels.
InputEvent.data - Web APIs
examples in the following simple example we've set up an event listener on the input event so that when any change is made to the contents of the <input> element (either by typing or pasting), the text that was added is retrieved via the inputevent.data property and reported in the paragraph below the input.
InputEvent.dataTransfer - Web APIs
examples in the following simple example we've set up an event listener on the input event so that when any content is pasted into the contenteditable <p> element, its html source is retrieved via the inputevent.datatransfer.getdata() method and reported in the paragraph below the input.
InstallEvent - Web APIs
examples this code snippet is from the service worker prefetch sample (see prefetch running live.) the code calls extendableevent.waituntil() in serviceworkerglobalscope.oninstall and delays treating the serviceworkerregistration.installing worker as installed until the passed promise resolves successfully.
IntersectionObserver - Web APIs
examples var intersectionobserver = new intersectionobserver(function(entries) { // if intersectionratio is 0, the target is out of view // and we do not need to do anything.
InterventionReportBody - Web APIs
examples let options = { types: ['intervention'], buffered: true } let observer = new reportingobserver(function(reports, observer) { let firstreport = reports[0]; console.log(firstreport.type); // intervention console.log(firstreport.body.id); console.log(firstreport.body.message); console.log(firstreport.body.sourcefile); console.log(firstreport.body.linenumber); console.log(firstrep...
KeyboardEvent.altKey - Web APIs
syntax var altkeypressed = instanceofkeyboardevent.altkey return value boolean
examples <html> <head> <title>altkey example</title> <script type="text/javascript"> function showchar(e){ alert( "key keydown: " + string.fromcharcode(e.charcode) + "\n" + "charcode: " + e.charcode + "\n" + "alt key keydown: " + e.altkey + "\n" ); } </script> </head> <body onkeydown="showchar(event);"> <p> press any character key, with or without holding down the alt key.<br /> you can also use the shift key together with the alt key.
KeyboardEvent.code - Web APIs
examples exercising keyboardevent html <p>press keys on the keyboard to see what the keyboardevent's key and code 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='" + e...
KeyboardLayoutMap - Web APIs
examples the following example demonstrates how to get the location- or layout-specific string associated with the key that corresponds to the 'w' key on an english qwerty keyboard.
KeyframeEffect.KeyframeEffect() - Web APIs
examples in the follow the white rabbit example, the keyframeeffect constructor is used to create a set of keyframes that dictate how the white rabbit should animate down the hole: var rabbitdownkeyframes = new keyframeeffect( whiterabbit, // element to animate [ { transform: 'translatey(0%)' }, // keyframe { transform: 'translatey(100%)' } // keyframe ], { duration: 3000,...
KeyframeEffect.getKeyframes() - Web APIs
examples in the red queen race example, we can inspect alice and the redqueen's animation to see its individual keyframes like so: // return the array of keyframes redqueen_alice.effect.getkeyframes(); specifications specification status comment web animationsthe definition of 'keyframeeffect.getkeyframes()' in that specification.
KeyframeEffect.setKeyframes() - Web APIs
examples // passing an array of keyframe objects existingkeyframeeffect.setkeyframes( [ { color: 'blue' }, { color: 'green', left: '10px' } ] ); // passing an object with arrays for values existingkeyframeeffect.setkeyframes( { color: ['blue', 'green'], left: [ '0', '10px'] } ); // passing a single-member object existingkeyframeeffect.setkeyframes( { color: 'blue' } ); spec...
KeyframeEffect.target - Web APIs
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!</...
KeyframeEffect - Web APIs
examples in the follow the white rabbit example, the keyframeeffect constructor is used to create a set of keyframes that dictate how the white rabbit should animate down the hole: var rabbitdownkeyframes = new keyframeeffect( whiterabbit, // element to animate [ { transform: 'translatey(0%)' }, // keyframe { transform: 'translatey(100%)' } // keyframe ], { duration: 3000,...
LargestContentfulPaint - Web APIs
examples the following example shows how to create a performanceobserver that listens for largest-contentful-paint entries and logs the lcp value to the console.
LayoutShift - Web APIs
examples the following example shows how to capture layout shifts and log them to the console.
Location: hash - Web APIs
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: host - Web APIs
syntax string = object.host; object.host = string;
examples var anchor = document.createelement("a"); anchor.href = "https://developer.mozilla.org/location.host" anchor.host == "developer.mozilla.org" anchor.href = "https://developer.mozilla.org:443/location.host" anchor.host == "developer.mozilla.org" // the port number is not included because 443 is the scheme's default port anchor.href = "https://developer.mozilla.org:4097/location.host" anchor.host == "developer.mozilla.org:4097" specifications specification status comment html living standardthe definition of 'host' in that specif...
Location: hostname - Web APIs
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
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
syntax string = object.origin;
examples // on this page, returns the origin var result = window.location.origin; // returns:'https://developer.mozilla.org' specifications specification status comment html living standardthe definition of 'origin' in that specification.
Location: password - Web APIs
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
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
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
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: replace() - Web APIs
examples // navigate to the location.reload article by replacing this page window.location.replace('/docs/web/api/location.reload'); specifications specification status comment html living standardthe definition of 'location.replace()' in that specification.
Location: search - Web APIs
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 standardth...
Location: toString() - Web APIs
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
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' ...
Location - Web APIs
examples // create anchor element and use href property for the purpose of this example // a more correct alternative is to browse to the url and use document.location or window.location var url = document.createelement('a'); url.href = 'https://developer.mozilla.org:8080/search?q=url#search-results-close-container'; console.log(url.href); // https://developer.mozilla.org:8080/search?q=url#search-re...
Locks.mode - Web APIs
example the following
examples show how the mode property is passed in the call to lockmanager.request().
Locks.name - Web APIs
example the following
examples show how the name property passed in the call to lockmanager.request().
Lock - Web APIs
examples the following
examples show how the mode and name properties are passed in the call to lockmanager.request().
LockManager.request() - Web APIs
examples general example the following example shows the basic use of the request() method with an asynchronous function as the callback.
MIDIAccess - Web APIs
examples navigator.requestmidiaccess() .then(function(access) { // get lists of available midi controllers const inputs = access.inputs.values(); const outputs = access.outputs.values(); access.onstatechange = function(e) { // print information about the (dis)connected midi controller console.log(e.port.name, e.port.manufacturer, e.port.state); }; }); specif...
MIDIConnectionEvent - Web APIs
properties midiconnectionevent.port returns a reference to a midiport instance for a port that has been connected or disconnected."
examples specifications specification status comment web midi api working draft initial definition.
MIDIMessageEvent - Web APIs
examples // printing all messages to console navigator.requestmidiaccess().then(midiaccess => { array.from(midiaccess.inputs).foreach(input => { input[1].onmidimessage = console.log; }) }); specifications specification status comment web midi apithe definition of 'midimessageevent' in that specification.
MathMLElement - Web APIs
properties this interface has no properties, but inherits properties from: documentandelementeventhandlers, element, elementcssinlinestyle, globaleventhandlers, htmlorforeignelement methods this interface has no methods, but inherits methods from: documentandelementeventhandlers, element, elementcssinlinestyle, globaleventhandlers, htmlorforeignelement
examples mathml <math xmlns="http://www.w3.org/1998/math/mathml"> <msqrt> <mi>x</mi> </msqrt> </math> javascript document.queryselector('msqrt').constructor.name; // mathmlelement specifications specification status comment mathmlelement interface ...
MediaDecodingConfiguration - Web APIs
examples //create media configuration to be tested const mediaconfig = { type : 'file', // or 'media-source' video : { contenttype : "video/webm;codecs=vp8", // valid content type width : 800, // width of the video height : 600, // height of the video bitrate : 10000, // number of bits used to encode 1s of video framerate : 30 // number of frames m...
MediaElementAudioSourceNode.mediaElement - Web APIs
examples const audioctx = new window.audiocontext(); const audioelem = document.queryselector('audio'); let options = { mediaelement: audioelem } let source = new mediaelementaudiosourcenode(audioctx, options); console.log(source.mediaelement); specifications specification status comment web audio apithe definition of 'mediaelementaudiosourcenode.mediaelement' in that specif...
MediaEncodingConfiguration - Web APIs
examples //create media configuration to be tested const mediaconfig = { type : 'record', // or 'transmission' video : { contenttype : "video/webm;codecs=vp8", // valid content type width : 800, // width of the video height : 600, // height of the video bitrate : 10000, // number of bits used to encode 1s of video framerate : 30 // number of frames...
MediaKeyMessageEvent - Web APIs
examples // tbd specifications specification status comment encrypted media extensionsthe definition of 'mediakeymessageevent' in that specification.
MediaKeySession - Web APIs
examples // tbd specifications specification status comment encrypted media extensionsthe definition of 'mediakeysession' in that specification.
MediaKeys - Web APIs
examples //tbd specifications specification status comment encrypted media extensionsthe definition of 'mediakeys' in that specification.
MediaList.mediaText - Web APIs
examples the following would log to the console a textual representation of the medialist of the first stylesheet applied to the current document.
MediaList - Web APIs
examples the following would log to the console a textual representation of the medialist of the first stylesheet applied to the current document.
MediaQueryList.addListener() - Web APIs
examples var para = document.queryselector('p'); var mql = window.matchmedia('(max-width: 600px)'); function screentest(e) { if (e.matches) { /* the viewport is 600 pixels wide or less */ para.textcontent = 'this is a narrow screen — less than 600px wide.'; document.body.style.backgroundcolor = 'red'; } else { /* the viewport is more than than 600 pixels wide */ para.textconten...
MediaQueryList.matches - Web APIs
examples this example detects viewport orientation changes by creating a media query using the orientation media feature: function addmqlistener(mq, callback) { if (mq.addeventlistener) { mq.addeventlistener("change", callback); } else { mq.addlistener(callback); } } addmqlistener(window.matchmedia("(orientation:landscape)"), event => { if (event.matches) { /* now in landscape...
MediaQueryList.media - Web APIs
examples this example runs the media query (max-width: 600px) and displays the value of the resulting mediaquerylist's media property in a <span>.
MediaQueryList.removeListener() - Web APIs
examples var mql = window.matchmedia('(max-width: 600px)'); function screentest(e) { if (e.matches) { /* the viewport is 600 pixels wide or less */ para.textcontent = 'this is a narrow screen — less than 600px wide.'; document.body.style.backgroundcolor = 'red'; } else { /* the viewport is more than than 600 pixels wide */ para.textcontent = 'this is a wide screen — more than...
MediaQueryListEvent.MediaQueryListEvent() - Web APIs
examples var media = '(max-width: 600px)'; var matches = true; var mymediaquerylistevent = new mediaquerylistevent({media, matches}); specifications specification status comment css object model (cssom) view modulethe definition of 'mediaquerylistevent()' in that specification.
MediaQueryListEvent.matches - Web APIs
examples var mql = window.matchmedia('(max-width: 600px)'); function screentest(e) { if (e.matches) { /* the viewport is 600 pixels wide or less */ para.textcontent = 'this is a narrow screen — less than 600px wide.'; document.body.style.backgroundcolor = 'red'; } else { /* the viewport is more than than 600 pixels wide */ para.textcontent = 'this is a wide screen — more than 600px wide.'; document.body.style.backgroundcolor = 'blue'; } } ...
MediaQueryListEvent.media - Web APIs
examples var mql = window.matchmedia('(max-width: 600px)'); function screentest(e) { if (e.matches) { /* the viewport is 600 pixels wide or less */ para.textcontent = 'this is a narrow screen — less than 600px wide.'; document.body.style.backgroundcolor = 'red'; } else { /* the viewport is more than than 600 pixels wide */ para.textcontent = 'this is a wide screen — more than 600px wide.'; document.body.style.backgroundcolor = 'blue'; } console.log(e.media); } mql.addlistener(screentest); specifications specification s...
MediaQueryListEvent - Web APIs
examples var mql = window.matchmedia('(max-width: 600px)'); function screentest(e) { if (e.matches) { /* the viewport is 600 pixels wide or less */ para.textcontent = 'this is a narrow screen — less than 600px wide.'; document.body.style.backgroundcolor = 'red'; } else { /* the viewport is more than than 600 pixels wide */ para.textcontent = 'this is a wide screen — more than...
MediaRecorder: error event - Web APIs
examples using addeventlistener to listen for error events: async function record() { const stream = await navigator.mediadevices.getusermedia({audio: true}); const recorder = new mediarecorder(stream); recorder.addeventlistener('error', (event) => { console.error(`error recording stream: ${event.error.name}`) }); recorder.start(); } record(); the same, but using the onerro...
MediaSession.setActionHandler() - Web APIs
examples adding action handlers this example implements seek forward and backward actions for an audio player by setting up the seekforward and seekbackward action handlers.
MediaSession - Web APIs
examples the following example creates a new media session and assigns action handlers to it: if ('mediasession' in navigator){ navigator.mediasession.metadata = new mediametadata({ title: "podcast episode title", artist: "podcast host", album: "podcast name", artwork: [{src: "podcast.jpg"}] }); navigator.mediasession.setactionhandler('play', function() {}); navigator.mediasessio...
Media Session action types - Web APIs
examples adding action handlers this example implements seek forward and backward actions for an audio player by setting up the seekforward and seekbackward action handlers.
MediaSessionActionDetails - Web APIs
examples adding action handlers this example implements seek forward and backward actions for an audio player by setting up the seekforward and seekbackward action handlers.
MediaSource.removeSourceBuffer() - Web APIs
examples for (i = 0; i < 10; i++) { var sourcebuffer = mediasource.addsourcebuffer(mimecodec); } mediasource.removesourcebuffer(mediasource.sourcebuffers[0]); specifications specification status comment media source extensionsthe definition of 'removesourcebuffer()' in that specification.
MediaSource - Web APIs
examples the following simple example loads a video with xmlhttprequest, playing it as soon as it can.
MediaStream: addtrack event - Web APIs
bubbles no cancelable no interface mediastreamtrackevent event handler property onaddtrack
examples using addeventlistener(): let stream = new mediastream(); stream.addeventlistener('addtrack', (event) => { console.log(`new ${event.track.kind} track added`); }); using the onaddtrack event handler property: let stream = new mediastream(); stream.onaddtrack = (event) => { console.log(`new ${event.track.kind} track added`); }; specifications specification status media capture and streamsthe definition of 'addtrack' in that specification.
MediaStream: removetrack event - Web APIs
bubbles no cancelable no interface mediastreamtrackevent event handler property onremovetrack
examples using addeventlistener(): let stream = new mediastream(); stream.addeventlistener('removetrack', (event) => { console.log(`${event.track.kind} track removed`); }); using the onremovetrack event handler property: let stream = new mediastream(); stream.onremovetrack = (event) => { console.log(`${event.track.kind} track removed`); }; specifications specification status media capture and streamsthe definition of 'removetrack' in that specification.
MessagePort: message event - Web APIs
bubbles no cancelable no interface messageevent event handler property onmessage
examples suppose a script creates a messagechannel and sends one of the ports to a different browsing context, such as another <iframe>, using code like this: const channel = new messagechannel(); const myport = channel.port1; const targetframe = window.top.frames[1]; const targetorigin = 'https://example.org'; const messagecontrol = document.queryselector('#message'); const channelmessagebutton = document.queryselector('#channel-message'); channelmessagebutton.addeventlistener('click', () => { myport.postmessage(messagecontrol.value); }) targetframe.postmessage('...
MessagePort: messageerror event - Web APIs
bubbles no cancelable no interface messageevent event handler property onmessageerror
examples suppose a script creates a messagechannel and sends one of the ports to a different browsing context, such as another <iframe>, using code like this: const channel = new messagechannel(); const myport = channel.port1; const targetframe = window.top.frames[1]; const targetorigin = 'https://example.org'; const messagecontrol = document.queryselector('#message'); const channelmessagebutton = document.queryselector('#channel-message'); channelmessagebutton.addeventlistener('click', () => { myport.postmessage(messagecontrol.value); }) ...
MouseEvent.pageX - Web APIs
example more
examples you can also see an example that demonstrates how to access the mouse position information in every available coordinate system.
MouseEvent.pageY - Web APIs
examples var pagey = event.pagey; specifications specification status comment css object model (cssom) view modulethe definition of 'pagey' in that specification.
NavigationPreloadManager - Web APIs
examples feature detecting and enabling navigation preloading addeventlistener('activate', event => { event.waituntil(async function() { if (self.registration.navigationpreload) { // enable navigation preloads!
Navigation Timing API - Web APIs
examples calculate the total page load time to compute the total amount of time it took to load the page, you can use the following code: const perfdata = window.performance.timing; const pageloadtime = perfdata.loadeventend - perfdata.navigationstart; this subtracts the time at which navigation began (navigationstart) from the time at which the load event handler returns (loadeventend).
Navigator.clipboard - Web APIs
examples the following code uses navigator.clipboard to access the system clipboard in order to read the contents of the clipboard.
Navigator.getBattery() - Web APIs
let batteryischarging = false; navigator.getbattery().then(function(battery) { batteryischarging = battery.charging; battery.addeventlistener('chargingchange', function() { batteryischarging = battery.charging; }); }); for more
examples and details, see battery status api.
Navigator.mediaCapabilities - Web APIs
examples navigator.mediacapabilities.decodinginfo({ type : 'file', audio : { contenttype : "audio/mp3", channels : 2, bitrate : 132700, samplerate : 5200 } }).then(function(result) { console.log('this configuration is ' + (result.supported ?
Navigator.permissions - Web APIs
examples navigator.permissions.query({name:'geolocation'}).then(function(result) { if (result.state === 'granted') { showmap(); } else if (result.state === 'prompt') { showbuttontoenablemap(); } // don't do anything if the permission was denied.
Web-based protocol handlers - Web APIs
so, using the above
examples, the browser would perform a get on this url: http://www.google.co.uk/?uri=web+burger:cheeseburger server side code can extract the query string parameters and perform the desired action.
Navigator.serviceWorker - Web APIs
syntax var workercontainerinstance = navigator.serviceworker; value serviceworkercontainer
examples this code checks if the browser supports service workers.
Navigator.share() - Web APIs
examples in our web share test (see the source code) there is a button which, when clicked, invokes the web share api to share mdn's url.
Navigator.vibrate() - Web APIs
examples window.navigator.vibrate(200); // vibrate for 200ms window.navigator.vibrate([100,30,100,30,100,30,200,30,200,30,200,30,100,30,100,30,100]); // vibrate 'sos' in morse.
navigator.hardwareConcurrency - Web APIs
examples in this example, one worker is created for each logical processor reported by the browser and a record is created which includes a reference to the new worker as well as a boolean value indicating whether or not we're using that worker yet; these objects are, in turn, stored into an array for later use.
NavigatorLanguage.languages - Web APIs
syntax preferredlanguages = globalobj.navigator.languages
examples navigator.language //"en-us" navigator.languages //["en-us", "zh-cn", "ja-jp"] specifications specification status comment html living standardthe definition of 'navigatorlanguage: languages' in that specification.
Node.childNodes - Web APIs
syntax let nodelist = elementnodereference.childnodes;
examples simple usage // parg is an object reference to a <p> element // first check that the element has child nodes if (parg.haschildnodes()) { let children = parg.childnodes; for (let i = 0; i < children.length; i++) { // do something with each child as children[i] // note: list is live!
Node.getRootNode() - Web APIs
examples the first simple example returns a reference to the html/document node: rootnode = node.getrootnode(); this more complex example shows the difference between returning a normal root, and a root incuding the shadow root.
Node.isConnected - Web APIs
examples standard dom a standard dom example: let test = document.createelement('p'); console.log(test.isconnected); // returns false document.body.appendchild(test); console.log(test.isconnected); // returns true shadow dom a shadow dom example: // create a shadow root var shadow = this.attachshadow({mode: 'open'}); // create some css to apply to the shadow dom var style = document.createelement(...
Node.nodeType - Web APIs
examples different types of nodes document.nodetype === node.document_node; // true document.doctype.nodetype === node.document_type_node; // true document.createdocumentfragment().nodetype === node.document_fragment_node; // true var p = document.createelement("p"); p.textcontent = "once upon a time…"; p.nodetype === node.element_node; // true p.firstchild.nodetype === node.text_node; // true co...
Node.removeChild() - Web APIs
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("neste...
Node - Web APIs
examples remove all children nested within a node function removeallchildren(element) { while (element.firstchild) { element.removechild(element.firstchild) } } sample usage /* ...
Notification.body - Web APIs
examples function spawnnotification(thebody, theicon, thetitle) { var options = { body: thebody, icon: theicon } var n = new notification(thetitle, options); console.log(n.body); } specifications specification status comment notifications apithe definition of 'body' in that specification.
Notification.close() - Web APIs
examples in the following snippet, we have a simple function that when called creates an options object and then a new notification.
Notification.data - Web APIs
examples the following snippet fires a notification; a simple options object is created, then the notification is fired using the notification() constructor.
Notification.dir - Web APIs
examples the following snippet fires a notification; a simple options object is created, then the notification is fired using the notification() constructor.
Notification.icon - Web APIs
examples in our to-do list app (view the app running live), we use the notification() constructor to fire a notification, passing it arguments to specify the body, icon and title we want.
Notification.lang - Web APIs
examples the following snippet fires a notification; a simple options object is created, then the notification is fired using the notification() constructor.
Notification.onclick - Web APIs
examples in the following example, we use an onclick handler to open a webpage in a new tab (specified by the inclusion of the '_blank' parameter) once a notification is clicked: notification.onclick = function(event) { event.preventdefault(); // prevent the browser from focusing the notification's tab window.open('http://www.mozilla.org', '_blank'); } specifications specification stat...
Notification.permission - Web APIs
examples the following snippet could be used if you wanted to first check whether notifications are supported, then check if permission has been granted for the current origin to send notifications, then request permission if required, before then sending a notification.
Notification.renotify - Web APIs
examples the following snippet is intended to fire a notification that renotifies the user after it has been replaced; a simple options object is created, and then the notification is fired using the notification() constructor.
Notification.requestPermission() - Web APIs
possible values for this string are: granted denied default
examples assume this basic html: <button onclick="notifyme()">notify me!</button> it's possible to send a notification as follows — here we present a fairly verbose and complete set of code you could use if you wanted to first check whether notifications are supported, then check if permission has been granted for the current origin to send notifications, then request permission if required, before t...
Notification.silent - Web APIs
examples the following snippet is intended to fire a silent notification; a simple options object is created, and then the notification is fired using the notification() constructor.
Notification.timestamp - Web APIs
examples the following snippet fires a notification; a simple options object is created, then the notification is fired using the notification() constructor.
Notification.title - Web APIs
examples function spawnnotification(thebody,theicon,thetitle) { var options = { body: thebody, icon: theicon } var n = new notification(thetitle,options); console.log(n.title) } specifications specification status comment notifications apithe definition of 'title' in that specification.
Notification.vibrate - Web APIs
examples the following snippet is intended to create a notification that also triggers a device vibration; a simple options object is created, and then the notification is fired using the notification() constructor.
Notification - Web APIs
examples assume this basic html: <button onclick="notifyme()">notify me!</button> it's possible to send a notification as follows — here we present a fairly verbose and complete set of code you could use if you wanted to first check whether notifications are supported, then check if permission has been granted for the current origin to send notifications, then request permission if required, before t...
OES_element_index_uint - Web APIs
examples var ext = gl.getextension('oes_element_index_uint'); gl.drawelements(gl.points, 8, gl.unsigned_int, 0); specifications specification status comment oes_element_index_uintthe definition of 'oes_element_index_uint' in that specification.
OES_standard_derivatives - Web APIs
glsl built-in functions the following new functions can be used in glsl shader code, if this extension is enabled: gentype dfdx(gentype) gentype dfdy(gentype) gentype fwidth(gentype)
examples enabling the extensions: gl.getextension('oes_standard_derivatives'); gl.getextension('ext_shader_texture_lod'); shader code that avoids artifacts when wrapping texture coordinates: <script type="x-shader/x-fragment"> #extension gl_ext_shader_texture_lod : enable #extension gl_oes_standard_derivatives : enable uniform sampler2d mytexture; varying vec2 texcoord; void main(){ gl_fragcolor =...
OES_texture_float - Web APIs
examples var ext = gl.getextension('oes_texture_float'); var texture = gl.createtexture(); gl.bindtexture(gl.texture_2d, texture); gl.teximage2d(gl.texture_2d, 0, gl.rgba, gl.rgba, gl.float, image); specifications specification status comment oes_texture_floatthe definition of 'oes_texture_float' in that specification.
OES_texture_float_linear - Web APIs
examples gl.getextension('oes_texture_float'); gl.getextension('oes_texture_float_linear'); var texture = gl.createtexture(); gl.bindtexture(gl.texture_2d, texture); gl.texparameterf(gl.texture_2d, gl.texture_mag_filter, gl.linear); gl.teximage2d(gl.texture_2d, 0, gl.rgba, gl.rgba, gl.float, image); specifications specification status comment oes_texture_float_linearthe defin...
OES_texture_half_float - Web APIs
examples var ext = gl.getextension('oes_texture_half_float'); var texture = gl.createtexture(); gl.bindtexture(gl.texture_2d, texture); gl.teximage2d(gl.texture_2d, 0, gl.rgba, gl.rgba, ext.half_float_oes, image); specifications specification status comment oes_texture_half_floatthe definition of 'oes_texture_half_float' in that specification.
OES_texture_half_float_linear - Web APIs
examples var halffloat = gl.getextension('oes_texture_half_float'); gl.getextension('oes_texture_half_float_linear'); var texture = gl.createtexture(); gl.bindtexture(gl.texture_2d, texture); gl.texparameterf(gl.texture_2d, gl.texture_mag_filter, gl.linear); gl.teximage2d(gl.texture_2d, 0, gl.rgba, gl.rgba, halffloat.half_float_oes, image); specifications specification status comment ...
OES_vertex_array_object - Web APIs
examples var oes_vao_ext = gl.getextension('oes_vertex_array_object'); var vao = oes_vao_ext.createvertexarrayoes(); oes_vao_ext.bindvertexarrayoes(vao); // ...
OfflineAudioContext: complete event - Web APIs
bubbles no cancelable no default action none interface offlineaudiocompletionevent event handler property offlineaudiocontext.oncomplete
examples when processing is complete, you might want to use the oncomplete handler the prompt the user that the audio can now be played, and enable the play button: let offlineaudioctx = new offlineaudiocontext(); offlineaudioctx.addeventlistener('complete', () => { console.log('offline audio processing now complete'); showmodaldialog('song processed and ready to play'); playbtn.disabled = false; }) you can also set up the event handler using the offlineaudiocont...
OffscreenCanvas.getContext() - Web APIs
examples var offscreen = new offscreencanvas(256, 256); var gl = offscreen.getcontext("webgl"); gl; // webglrenderingcontext gl.canvas; // offscreencanvas specifications specification status comment html living standardthe definition of 'offscreencanvas.getcontext()' in that specification.
OffscreenCanvas.height - Web APIs
syntax var pxl = offscreen.height; offscreen.height = pxl;
examples creating a new offscreen canvas and returning or setting the height of the offscreen canvas: var offscreen = new offscreencanvas(256, 256); offscreen.height; // 256 offscreen.height = 512; specifications specification status comment html living standardthe definition of 'offscreencanvas.height' in that specification.
OffscreenCanvas.width - Web APIs
syntax var pxl = offscreen.width; offscreen.width = pxl;
examples creating a new offscreen canvas and returning or setting the width of the offscreen canvas: var offscreen = new offscreencanvas(256, 256); offscreen.width; // 256 offscreen.width = 512; specifications specification status comment html living standardthe definition of 'offscreencanvas.width' in that specification.
OffscreenCanvas - Web APIs
examples synchronous display of frames produced by an offscreencanvas one way to use the offscreencanvas api, is to use a renderingcontext that has been obtained from an offscreencanvas object to generate new frames.
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 - Web APIs
examples the following example shows basic usage of an audiocontext to create an oscillator node and to start playing a tone on it.
PaintWorklet - Web APIs
examples the following three
examples go together to show creating, loading, and using a paintworklet.
PannerNode - Web APIs
examples in the following example, you can see an example of how the createpanner() method, audiolistener and pannernode would be used to control audio spatialisation.
ParentNode.append() - Web APIs
examples appending an element let parent = document.createelement("div") let p = document.createelement("p") parent.append(p) console.log(parent.childnodes) // nodelist [ <p> ] appending text let parent = document.createelement("div") parent.append("some text") console.log(parent.textcontent) // "some text" appending an element and text let parent = document.createelement("div") let p = document.
ParentNode.prepend() - Web APIs
examples prepending an element var parent = document.createelement("div"); var p = document.createelement("p"); var span = document.createelement("span"); parent.append(p); parent.prepend(span); console.log(parent.childnodes); // nodelist [ <span>, <p> ] prepending text var parent = document.createelement("div"); parent.append("some text"); parent.prepend("headline: "); console.log(parent.textconte...
ParentNode.querySelectorAll() - Web APIs
examples to obtain a nodelist of all of the <p> elements in the document: var matches = document.queryselectorall("p"); this example returns a list of all <div> elements within the document with a class of either note or alert: var matches = document.queryselectorall("div.note, div.alert"); here, we get a list of <p> elements whose immediate parent element is a <div> with the class highlighted and w...
PasswordCredential - Web APIs
examples this example shows how to set up an htmlformelement to caputure data which we'll use to create a passwordcredential object.
PasswordCredential - Web APIs
examples var cred = new passwordcredential({ id: id, password: password, name: name, iconurl: iconurl }); navigator.credentials.store(cred) .then(function() { // do something else.
Path2D() - Web APIs
examples creating and copying paths this example creates and copies a path2d path.
PaymentCurrencyAmount.value - Web APIs
examples representing prices this example represents the price of $42.95 in us dollars: let itemprice = { currency: "usd", value: "42.95" }; this example specifies a price of £7.77: let shippingcost = { currency: "gbp", value: "7.77" } this example specifies a price of 1000¥: let price = { currency: "jpy", value: "1000" } verifying a properly formatted price you can ensure that t...
PaymentRequest.abort() - Web APIs
parameters none
examples the following example sets up a timeout to clear the payment request that might have been abandoned or neglected.
PaymentRequest.onmerchantvalidation - Web APIs
examples an example merchant validation handler for the paymentrequest object request looks like this: request.onmerchantvalidation = ev => { ev.complete(async () => { const merchantserverurl = window.location.origin + '/validation?url=' + encodeuricomponent(ev.validationurl); // get validation data, and complete validation; return await fetch(merchantserverurl).then(r => r.text())...
PaymentRequest.onpaymentmethodchange - Web APIs
examples an example payment method change handler is shown below; this example handles changes made to the payment method when using apple pay, specifically: request.onpaymentmethodchange = ev => { const { type: cardtype } = ev.methoddetails; const newstuff = {}; if (ev.methodname === "https://apple.com/apple-pay") { switch (cardtype) { case "store": // do apple pay specific hand...
PaymentResponse.onpayerdetailchange - Web APIs
examples in the example below, onpayerdetailchange is used to set up a listener for the payerdetailchange event in order to validate the information entered by the user, requesting that any mistakes be corrected // options for paymentrequest(), indicating that shipping address, // payer email address, name, and phone number all be collected.
PaymentResponse: payerdetailchange event - Web APIs
bubbles no cancelable no interface paymentrequestupdateevent event handler property onpayerdetailchange
examples in the example below, onpayerdetailchange is used to set up a listener for the payerdetailchange event in order to validate the information entered by the user, requesting that any mistakes be corrected // options for paymentrequest(), indicating that shipping address, // payer email address, name, and phone number all be collected.
PaymentResponse.retry() - Web APIs
epayment() { const payrequest = new paymentrequest(methoddata, details, options); try { let payresponse = await payrequest.show(); while (payresponse has errors) { /* let the user edit the payment information, wait until they submit */ await response.retry(); } await payresponse.complete("success"); } catch(err) { /* handle the exception */ } }
examples try { await paymentrequest.retry(errorfields); } catch (domexception err) { ...
PerformanceEventTiming - Web APIs
examples the following example shows how to use the api for all events: const observer = new performanceobserver(function(list) { const perfentries = list.getentries().foreach(entry => { // full duration const inputduration = entry.duration; // input delay (before processing event) const inputdelay = entry.processingstart - entry.starttime; // synchronous even...
PluginArray - Web APIs
examples the following example function returns the version of the shockwave flash plugin.
PointerEvent - Web APIs
example
examples of each property, event type, and global event handler are included in their respective reference pages.
ProgressEvent - Web APIs
examples the following example adds a progressevent to a new xmlhttprequest and uses it to display the status of the request.
PromiseRejectionEvent() - Web APIs
examples this example creates a new unhandledrejection event for the promise mypromise with the reason being the string "my house is on fire".
PromiseRejectionEvent.promise - Web APIs
examples this example listens for unhandled promises and, if the reason is an object with a code field containing the text "module not ready", it sets up an idle callback that will retry the task that failed to execute correctly.
PromiseRejectionEvent.reason - Web APIs
examples window.onunhandledrejection = function(e) { console.log(e.reason); } specifications specification status comment html living standardthe definition of 'promiserejectionevent.reason' in that specification.
PublicKeyCredential.getClientExtensionResults() - Web APIs
examples var publickey = { // here are the extensions (as "inputs") extensions: { "loc": true, // this extension has been defined to include location information in attestation "uvi": true // user verification index: how the user was verified }, challenge: new uint8array(16) /* from the server */, rp: { name: "example corp", id : "login.example.com" }, user: { id: new ...
PublicKeyCredential.id - Web APIs
examples var publickey = { challenge: new uint8array(26) /* this actually is given from the server */, rp: { name: "example corp", id : "login.example.com" }, user: { id: new uint8array(26), /* to be changed for each user */ name: "jdoe@example.com", displayname: "john doe", }, pubkeycredparams: [ { type: "public-key", alg: -7 } ] }; navigator.crede...
PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable() - Web APIs
examples publickeycredential.isuserverifyingplatformauthenticatoravailable() .then(function(available){ if(available){ // we can proceed with the creation of a publickeycredential // with this authenticator } else { // use another kind of authenticator or a classical login/password // workflow } }).catch(function(err){ // something went wrong console.error(...
PublicKeyCredential.rawId - Web APIs
examples var options = { challenge: new uint8array(26) /* from the server */, rp: { name: "example corp", id : "login.example.com" }, user: { id: new uint8array(26), /* to be changed for each user */ name: "jdoe@example.com", displayname: "john doe", }, pubkeycredparams: [ { type: "public-key", alg: -7 } ] }; navigator.credentials.create({ publicke...
PublicKeyCredential.response - Web APIs
examples var options = { challenge: new uint8array(16) /* from the server */, rp: { name: "example corp", id : "login.example.com" }, user: { id: new uint8array(16) /* from the server */, name: "jdoe@example.com", displayname: "john doe" }, pubkeycredparams: [ { type: "public-key", alg: -7 } ] }; navigator.credentials.create({ publickey: options })...
PublicKeyCredential - Web APIs
examples creating a new instance of publickeycredential here, we use navigator.credentials.create() to generate a new credential.
PublicKeyCredentialCreationOptions.attestation - Web APIs
examples var publickey = { attestation: "indirect", challenge: new uint8array(26) /* this actually is given from the server */, rp: { name: "example corp", id : "login.example.com" }, user: { id: new uint8array(26), /* to be changed for each user */ name: "jdoe@example.com", displayname: "john doe", }, pubkeycredparams: [ { type: "public-key", alg: -7 ...
PublicKeyCredentialCreationOptions.authenticatorSelection - Web APIs
examples var publickey = { authenticatorselection:{ authenticatorattachment: "cross-platform", requireresidentkey: true, userverification: "required" }, challenge: new uint8array(26) /* this actually is given from the server */, rp: { name: "example corp", id : "login.example.com" }, user: { id: new uint8array(26), /* to be changed for each user */ name: "jdoe@exa...
PublicKeyCredentialCreationOptions.challenge - Web APIs
examples var publickey = { challenge: new uint8array(26) /* this actually is given from the server */, rp: { name: "example corp", id : "login.example.com" }, user: { id: new uint8array(26), /* to be changed for each user */ name: "jdoe@example.com", displayname: "john doe", }, pubkeycredparams: [ { type: "public-key", alg: -7 } ] }; navigator.crede...
PublicKeyCredentialCreationOptions.excludeCredentials - Web APIs
examples var publickey = { excludecredentials: [ { type: "public-key", // the id for john.doe@example.com id : new uint8array(26) /* this actually is given by the server */ }, { type: "public-key", // the id for john-doe@example.com id : new uint8array(26) /* another id */ } ], challenge: new uint8array(26) /* this actually is given from the serv...
PublicKeyCredentialCreationOptions.extensions - Web APIs
examples var publickey = { extensions:{ uvi: true, loc: false, uvm: false, exts: true }, challenge: new uint8array(26) /* this actually is given from the server */, rp: { name: "example corp", id : "login.example.com" }, user: { id: new uint8array(26), /* to be changed for each user */ name: "jdoe@example.com", displayname: "john doe", }, pubkeycredpar...
PublicKeyCredentialCreationOptions.pubKeyCredParams - Web APIs
examples var publickey = { pubkeycredparams: [ // we would like an elliptic curve to be used if possible { type: "public-key", alg: -7 }, // if not, then we will fallback on an rsa algorithm { type: "public-key", alg: -37 } ], challenge: new uint8array(26) /* this actually is given from the server */, rp: { name: "example corp", id : "login...
PublicKeyCredentialCreationOptions.rp - Web APIs
examples var publickey = { challenge: /* from the server */, rp: { name: "example corp", id : "login.example.com", icon: "https://login.example.com/login.ico" }, user: { id: new uint8array(16), name: "jdoe@example.com", displayname: "john doe" }, pubkeycredparams: [ { type: "public-key", alg: -7 } ] }; navigator.credentials.create({ publickey })...
PublicKeyCredentialCreationOptions.user - Web APIs
examples var publickey = { challenge: new uint8array(26) /* this actually is given from the server */, rp: { name: "example corp", id : "login.example.com" }, user: { // to be changed for each user id: new uint8array.from(window.atob("laegmlkjnrlkgnamlafalfka="), c=>c.charcodeat(0)); name: "jdoe@example.com", displayname: "john doe", icon: "https://gravatar.com/avata...
PublicKeyCredentialCreationOptions - Web APIs
examples // some
examples of cose algorithms const cose_alg_ecdsa_w_sha256 = -7; const cose_alg_ecdsa_w_sha512 = -36; var createcredentialoptions = { // format of new credentials is publickey publickey: { // relying party rp: { name: "example corp", id: "login.example.com", icon: "https://login.example.com/login.ico" }, // crypt...
PublicKeyCredentialRequestOptions.allowCredentials - Web APIs
examples var options = { allowcredentials: [ { transports: ["usb"], type: "public-key", id: new uint8array(26) // actually provided by the server }, { transports: ["internal"], type: "public-key", id: new uint8array(26) // actually provided by the server } ], challenge: new uint8array([/* bytes sent from the server */]) }; navigator.credentials.g...
PublicKeyCredentialRequestOptions.challenge - Web APIs
examples var options = { challenge: new uint8array([/* bytes sent from the server */]) }; navigator.credentials.get({ "publickey": options }) .then(function (credentialinfoassertion) { // send assertion response back to the server // to proceed with the control of the credential }).catch(function (err) { console.error(err); }); specifications specification status co...
PublicKeyCredentialRequestOptions.extensions - Web APIs
examples var options = { extensions: { uvm: true, loc: false, txauthsimple: "could you please verify yourself?" }, challenge: new uint8array([/* bytes sent from the server */]) }; navigator.credentials.get({ "publickey": options }) .then(function (credentialinfoassertion) { // send assertion response back to the server // to proceed with the control of the credential }).cat...
PublicKeyCredentialRequestOptions.rpId - Web APIs
examples var options = { challenge: new uint8array([/* bytes sent from the server */]), rpid: "example.com" // will only work if the current domain // is something like foo.example.com }; navigator.credentials.get({ "publickey": options }) .then(function (credentialinfoassertion) { // send assertion response back to the server // to proceed with the control of the c...
PublicKeyCredentialRequestOptions.timeout - Web APIs
examples var options = { challenge: new uint8array([/* bytes sent from the server */]), timeout: 6000 // wait a minute for the fetching operation // and maybe fail if it takes longer }; navigator.credentials.get({ "publickey": options }) .then(function (credentialinfoassertion) { // send assertion response back to the server // to proceed with the control of the credent...
PublicKeyCredentialRequestOptions.userVerification - Web APIs
examples var options = { userverification: "preferred", challenge: new uint8array([/* bytes sent from the server */]), }; navigator.credentials.get({ "publickey": options }) .then(function (credentialinfoassertion) { // send assertion response back to the server // to proceed with the control of the credential }).catch(function (err) { console.error(err); }); specifications ...
PublicKeyCredentialRequestOptions - Web APIs
examples var options = { challenge: new uint8array([/* bytes sent from the server */]), rpid: "example.com", /* will only work if the current domain is something like foo.example.com */ userverification: "preferred", timeout: 60000, // wait for a minute allowcredentials: [ { transports: "usb", type: "public-key", id: new uint8array(26) // actua...
PushEvent.data - Web APIs
examples the following example takes data from a pushevent and displays it on all of the service workers' clients.
PushEvent - Web APIs
examples the following example takes data from a pushevent and displays it on all of the service worker's clients.
PushMessageData.arrayBuffer() - Web APIs
examples self.addeventlistener('push', function(event) { var buffer = event.data.arraybuffer(); // do something with your array buffer }); specifications specification status comment push apithe definition of 'arraybuffer()' in that specification.
PushMessageData.blob() - Web APIs
examples self.addeventlistener('push', function(event) { var blob = event.data.blob(); // do something with your blob }); specifications specification status comment push apithe definition of 'blob()' in that specification.
PushMessageData.json() - Web APIs
examples self.addeventlistener('push', function(event) { var mydata = event.data.json(); // do something with your data }); specifications specification status comment push apithe definition of 'json()' in that specification.
PushMessageData.text() - Web APIs
examples self.addeventlistener('push', function(event) { var textobj = event.data.text(); // do something with your text }); specifications specification status comment push apithe definition of 'text()' in that specification.
PushMessageData - Web APIs
examples self.addeventlistener('push', function(event) { var obj = event.data.json(); if(obj.action === 'subscribe' || obj.action === 'unsubscribe') { firenotification(obj, event); port.postmessage(obj); } else if(obj.action === 'init' || obj.action === 'chatmsg') { port.postmessage(obj); } }); specifications specification status comment push apithe definiti...
Push API - Web APIs
when a push service sets an expiration time.)
examples mozilla's serviceworker cookbook contains many useful push
examples.
RTCConfiguration.bundlePolicy - Web APIs
examples the following example creates a new rtcpeerconnection with a configuration setting the connection's bundlepolicy to max-compat to maximize compatibility while attempting to optimize network use.
RTCConfiguration.certificates - Web APIs
<<<--- add link to information about identity --->>>
examples specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcconfiguration.certificates' in that specification.
RTCDTMFSender: tonechange event - Web APIs
examples this example establishes a handler for the tonechange event which updates an element to display the currently playing tone in its content, or, if all tones have played, the string "<none>".
RTCDTMFToneChangeEvent - Web APIs
examples this snippet is derived loosely from the full, working example you'll find in when a tone finishes playing in using dtmf with webrtc.
RTCDataChannel: bufferedamountlow event - Web APIs
bubbles no cancelable no interface event event handler property onbufferedamountlow
examples this example sets up a handler for bufferedamountlow to request more data any time the data channel's buffer falls below the number of bytes specified by bufferedamountlowthreshold, which we have set to 65536.
RTCDataChannel: close event - Web APIs
bubbles no cancelable no interface event event handler property rtcdatachannel.onclose
examples this example sets up a handler for the close event for the rtcdatachannel named dc; its responsibility in this example is to update user interface elements to reflect that there is no longer an ongoing call, and to allow a new call to be started.
RTCDataChannel: error event - Web APIs
examples // strings for each of the sctp cause codes found in rfc // 4960, section 3.3.10: // https://tools.ietf.org/html/rfc4960#section-3.3.10 const sctpcausecodes = [ "no sctp error", "invalid stream identifier", "missing mandatory parameter", "stale cookie error", "sender is out of resource (i.e., memory)", "unable to resolve address", "unrecognized sctp chunk type received", "invalid mandatory parameter", "unrecogn...
RTCDataChannel: message event - Web APIs
examples for a given rtcdatachannel, dc, created for a peer connection using its createdatachannel() method, this code sets up a handler for incoming messages and acts on them by adding the data contained within the message to the current document as a new <p> (paragraph) element.
RTCDataChannel: open event - Web APIs
bubbles no cancelable no interface rtcdatachannelevent event handler property onopen
examples this example adds to the rtcdatachannel dc a handler for the open event that adjusts the user interface to indicate that a chat window is ready to be used after a connection has been established.
RTCDataChannelEvent - Web APIs
constructorrtcdatachannelevent() the rtcdatachannelevent() constructor creates a new rtcdatachannelevent.propertiesalso inherits properties from: eventchannel read only the read-only property rtcdatachannelevent.channel returns the rtcdatachannel associated with the event.methodsthis interface has no methods, but inherits methods from: event
examples in this example, the datachannel event handler is set up to save the data channel reference and set up handlers for the events which need to be monitored.
RTCDtlsTransport.iceTransport - Web APIs
examples tbd specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcdtlstransport.icetransport' in that specification.
RTCDtlsTransport.state - Web APIs
examples this example presents a function, tallysenders(), which iterates over an rtcpeerconnection's rtcrtpsenders, tallying up how many of them are in various states.
RTCDtlsTransport - Web APIs
examples this example presents a function, tallysenders(), which iterates over an rtcpeerconnection's rtcrtpsenders, tallying up how many of them are in various states.
RTCError - Web APIs
examples in this example, a handler is established for an rtcdatachannel's error event.
Report.body - Web APIs
examples let options = { types: ['deprecation'], buffered: true } let observer = new reportingobserver(function(reports, observer) { let firstreport = reports[0]; // log the first report's report body, i.e.
Report.type - Web APIs
examples let options = { types: ['deprecation'], buffered: true } let observer = new reportingobserver(function(reports, observer) { let firstreport = reports[0]; // log the first report's report type, i.e.
Report.url - Web APIs
examples let options = { types: ['deprecation'], buffered: true } let observer = new reportingobserver(function(reports, observer) { let firstreport = reports[0]; // log the url of the document that generated the first report // e.g.
Report - 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...
ReportingObserver() - Web APIs
examples let options = { types: ['deprecation'], buffered: true } let observer = new reportingobserver(function(reports, observer) { reportbtn.onclick = () => displayreports(reports); }, options); specifications specification status comment reporting apithe definition of 'reportingobserver()' in that specification.
ReportingObserver.disconnect() - Web APIs
syntax reportingobserverinstance.disconnect()
examples let options = { types: ['deprecation'], buffered: true } let observer = new reportingobserver(function(reports, observer) { reportbtn.onclick = () => displayreports(reports); }, options); observer.observe() ...
ReportingObserver.observe() - Web APIs
syntax reportingobserverinstance.observe()
examples let options = { types: ['deprecation'], buffered: true } let observer = new reportingobserver(function(reports, observer) { reportbtn.onclick = () => displayreports(reports); }, options); observer.observe() specifications specification status comment reporting apithe definition of 'reportingobserver.observe()' in that specification.
ReportingObserver.takeRecords() - Web APIs
examples let options = { types: ['deprecation'], buffered: true } let observer = new reportingobserver(function(reports, observer) { reportbtn.onclick = () => displayreports(reports); }, options); observer.observe() // ...
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...
ReportingObserverOptions - Web APIs
examples let options = { types: ['deprecation'], buffered: true } let observer = new reportingobserver(function(reports, observer) { reportbtn.onclick = () => displayreports(reports); }, options); specifications specification status comment reporting apithe definition of 'reportingobserveroptions' in that specification.
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...
Request.context - Web APIs
note: you can find a full list of the different available contexts including associated context frame types, csp directives, and platform feature
examples in the fetch spec request context section.
Request.url - Web APIs
example in the following snippet, we create a new request using the request.request() constructor (for an image file in the same directory as the script), then save the url of the request in a variable: var myrequest = new request('flowers.jpg'); var myurl = myrequest.url; // "http://mdn.github.io/fetch-
examples/fetch-request/flowers.jpg" specifications specification status comment fetchthe definition of 'url' in that specification.
Request - Web APIs
examples in the following snippet, we create a new request using the request() constructor (for an image file in the same directory as the script), then return some property values of the request: const request = new request('https://www.mozilla.org/favicon.ico'); const url = request.url; const method = request.method; const credentials = request.credentials; you could then fetch this request by pass...
ResizeObserver() - Web APIs
the callback will generally follow a pattern along the lines of: function(entries, observer) { for (let entry of entries) { // do something to each entry // and possibly something to the observer itself } }
examples the following snippet is taken from the resize-observer-text.html (see source) example: const resizeobserver = new resizeobserver(entries => { for (let entry of entries) { if(entry.contentboxsize) { h1elem.style.fontsize = math.max(1.5, entry.contentboxsize.inlinesize/200) + 'rem'; pelem.style.fontsize = math.max(1, entry.contentboxsize.inlinesize/600) + 'rem'; } else { ...
ResizeObserver.disconnect() - Web APIs
examples btn.addeventlistener('click', () => { resizeobserver.disconnect(); }) specifications specification status comment resize observerthe definition of 'disconnect()' in that specification.
ResizeObserver.observe() - Web APIs
examples the following snippet is taken from the resize-observer-text.html (see source) example: const resizeobserver = new resizeobserver(entries => { for (let entry of entries) { if(entry.contentboxsize) { h1elem.style.fontsize = math.max(1.5, entry.contentboxsize.inlinesize/200) + 'rem'; pelem.style.fontsize = math.max(1, entry.contentboxsize.inlinesize/600) + 'rem'; } else { ...
ResizeObserver.unobserve() - Web APIs
examples the following snippet is taken from the resize-observer-text.html (see source) example: const resizeobserver = new resizeobserver(entries => { for (let entry of entries) { if(entry.contentboxsize) { h1elem.style.fontsize = math.max(1.5, entry.contentboxsize.inlinesize/200) + 'rem'; pelem.style.fontsize = math.max(1, entry.contentboxsize.inlinesize/600) + 'rem'; } else { h1elem.style.fontsize = math.max(1.5, entry.contentrect.width/200) + 'rem'; pelem.style.fontsize = math.max(1, entry.cont...
ResizeObserver - Web APIs
examples in the resize-observer-text.html (see source) example, we use the resize observer to change the font-size of a header and paragraph as a slider’s value is changed causing the containing <div> to change width.
ResizeObserverEntry.borderBoxSize - Web APIs
examples const resizeobserver = new resizeobserver(entries => { for (let entry of entries) { if(entry.borderboxsize && entry.borderboxsize.length > 0) { entry.target.style.borderradius = math.min(100, (entry.borderboxsize[0].inlinesize/10) + (entry.borderboxsize[0].blocksize/10)) + 'px'; } else { entry.target.style.borderradius =...
Resize Observer API - Web APIs
examples you find a couple of simple
examples on our github repo: resize-observer-border-radius.html (see source): a simple example with a green box, sized as a percentage of the viewport size.
Resource Timing API - Web APIs
for more details about the interfaces including
examples see each interface's reference page, using the resource timing api, and the references in the see also section.
Response() - Web APIs
examples in our fetch response example (see fetch response live) we create a new response object using the constructor, passing it a new blob as a body, and an init object containing a custom status and statustext: var myblob = new blob(); var init = { "status" : 200 , "statustext" : "supersmashinggreat!" }; var myresponse = new response(myblob,init); specifications specification status ...
Response.redirected - Web APIs
examples detecting redirects checking to see if the response comes from a redirected request is as simple as checking this flag on the response object.
Response - Web APIs
examples in our basic fetch example (run example live) we use a simple fetch() call to grab an image and display it in an <img> element.
format - Web APIs
string font format
examples of 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 - ...
SVGAnimationElement: beginEvent event - Web APIs
bubbles no cancelable no interface timeevent event handler property onbegin
examples animated circle <svg xmlns="http://www.w3.org/2000/svg" width="300px" height="100px"> <title>svg smil animate with path</title> <circle cx="0" cy="50" r="50" fill="blue" stroke="black" stroke-width="1"> <animatemotion path="m 0 0 h 300 z" dur="5s" repeatcount="indefinite" /> </circle> </svg> <hr> <ul> </ul> ul { height: 100px; border: 1px solid #ddd; overflow-y...
SVGAnimationElement: endEvent event - Web APIs
bubbles no cancelable no interface timeevent event handler property onend
examples animated circle <svg xmlns="http://www.w3.org/2000/svg" width="300px" height="100px"> <title>svg smil animate with path</title> <circle cx="0" cy="50" r="50" fill="blue" stroke="black" stroke-width="1"> <animatemotion path="m 0 0 h 300 z" dur="5s" repeatcount="indefinite" /> </circle> </svg> <hr> <button>stop animation</button> <ul> </ul> ul { height: 100px; bor...
SVGAnimationElement: repeatEvent event - Web APIs
bubbles no cancelable no interface timeevent event handler property onrepeat
examples animated circle <svg xmlns="http://www.w3.org/2000/svg" width="300px" height="100px"> <title>svg smil animate with path</title> <circle cx="0" cy="50" r="50" fill="blue" stroke="black" stroke-width="1"> <animatemotion path="m 0 0 h 300 z" dur="5s" repeatcount="indefinite" /> </circle> </svg> <hr> <ul> </ul> ul { height: 100px; border: 1px solid #ddd; overflow-y...
SVGElement: abort event - Web APIs
bubbles no cancelable no interface svgevent event handler property onabort
examples svgelem.addeventlistener('abort', () => { console.log('load aborted.'); }) specifications not really described anywhere specifically, but mentioned in the svg 2 spec.
SVGElement: error event - Web APIs
bubbles yes cancelable no interface svgevent event handler property onerror
examples svgelem.addeventlistener('error', () => { console.log('svg not loaded properly.'); }) specifications specification status comment scalable vector graphics (svg) 2the definition of 'error' in that specification.
SVGElement: load event - Web APIs
bubbles no cancelable no interface svgevent event handler property onload
examples svgelem.addeventlistener('load', () => { console.log('svg loaded.'); }) specifications specification status comment scalable vector graphics (svg) 2the definition of 'load' in that specification.
SVGElement: resize event - Web APIs
bubbles no cancelable no interface svgevent event handler property onresize
examples svgelem.addeventlistener('resize', () => { console.log('svg resized.'); }) specifications specification status comment scalable vector graphics (svg) 2the definition of 'event changes in svg2' in that specification.
SVGElement: scroll event - Web APIs
bubbles no cancelable no interface svgevent event handler property onscroll
examples svgelem.addeventlistener('scroll', () => { console.log('svg scrolled.'); }) specifications specification status comment scalable vector graphics (svg) 2the definition of 'event changes in svg2' in that specification.
SVGElement: unload event - Web APIs
bubbles no cancelable no interface svgevent event handler property onunload
examples svgelem.addeventlistener('unload', () => { console.log('svg unloaded.'); }) specifications specification status comment scalable vector graphics (svg) 2the definition of 'unload' in that specification.
SVGElement: zoom event - Web APIs
bubbles yes cancelable no interface svgevent event handler property onzoom
examples svgelem.addeventlistener('zoom', () => { console.log('svg zoomed.'); }) ...
SVGImageElement.decoding - Web APIs
examples var img = new image(); img.decoding = 'sync'; img.src = 'img/logo.svg'; specifications specification status comment html living standardthe definition of 'decoding' in that specification.
Screen.lockOrientation() - Web APIs
examples usage with a domstring argument screen.lockorientationuniversal = screen.lockorientation || screen.mozlockorientation || screen.mslockorientation; if (screen.lockorientationuniversal("landscape-primary")) { // orientation was locked } else { // orientation lock failed } usage with an array argument screen.lockorientationuniversal = screen.lockorientation || screen.mozlockorientation || ...
ScriptProcessorNode: audioprocess event - Web APIs
bubbles no cancelable no default action none interface audioprocessingevent event handler property scriptprocessornode.onaudioprocess
examples scriptnode.addeventlistener('audioprocess', function(audioprocessingevent) { // the input buffer is a song we loaded earlier var inputbuffer = audioprocessingevent.inputbuffer; // the output buffer contains the samples that will be modified and played var outputbuffer = audioprocessingevent.outputbuffer; // loop through the output channels (in this case there is only one) for (var channel = 0; channel < outputbuffer.numberofchannels; cha...
ScriptProcessorNode - Web APIs
examples the following example shows basic usage of a scriptprocessornode to take a track loaded via audiocontext.decodeaudiodata(), process it, adding a bit of white noise to each audio sample of the input track (buffer) and play it through the audiodestinationnode.
ScrollToOptions.behavior - Web APIs
examples in our scrolltooptions example (see it live) we include a form that allows the user to enter three values — two numbers representing the left and top properties (i.e.
ScrollToOptions.left - Web APIs
examples in our scrolltooptions example (see it live) we include a form that allows the user to enter three values — two numbers representing the left and top properties (i.e.
ScrollToOptions.top - Web APIs
examples in our scrolltooptions example (see it live) we include a form that allows the user to enter three values — two numbers representing the left and top properties (i.e.
ScrollToOptions - Web APIs
examples in our scrolltooptions example (see it live) we include a form that allows the user to enter three values — two numbers representing the left and top properties (i.e.
SecurityPolicyViolationEvent - Web APIs
examples document.addeventlistener("securitypolicyviolation", (e) => { console.log(e.blockeduri); console.log(e.violateddirective); console.log(e.originalpolicy); }); specifications specification status comment content security policy level 2the definition of 'securitypolicyviolationevent' in that specification.
Server-sent events - Web APIs
examples simple sse demo using php specification specification status comment html living standardthe definition of 'server-sent events' in that specification.
ServiceWorker.scriptURL - Web APIs
syntax someurl = serviceworker.scripturl value a usvstring (see the webidl definition of usvstring.)
examples tbd specifications specification status comment service workersthe definition of 'scripturl' in that specification.
ServiceWorker.state - Web APIs
syntax someurl = serviceworker.state value a serviceworkerstate definition (see the spec.)
examples this code snippet is from the service worker registration-events sample (live demo).
ServiceWorkerContainer: message event - Web APIs
bubbles no cancelable no interface messageevent event handler property onmessage
examples in this example the service worker get the client's id from a fetch event and then sends it a message using client.postmessage: // in the service worker async function messageclient(clientid) { const client = await clients.get(clientid); client.postmessage('hi client!'); } addeventlistener('fetch', (event) => { messageclient(event.clientid); event.respondwith(() => { // ...
ServiceWorkerGlobalScope: activate event - Web APIs
bubbles no cancelable no interface extendableevent event handler property serviceworkerglobalscope.onactivate
examples the following snippet shows how you could use an activate event handler to upgrade a cache.
ServiceWorkerGlobalScope: install event - Web APIs
bubbles no cancelable no interface extendableevent event handler property serviceworkerglobalscope.oninstall
examples the following snippet shows how an install event handler can be used to populate a cache with a number of responses, which the service worker can then use to serve assets offline: this.addeventlistener('install', function(event) { event.waituntil( caches.open('v1').then(function(cache) { return cache.add( '/sw-test/', '/sw-test/index.html', '/sw-test/style.css', '/sw-test/app.js', '/sw-test/image-list.js', ...
ServiceWorkerGlobalScope: message event - Web APIs
bubbles no cancelable no interface extendablemessageevent event handler property onmessage
examples in the below example a page gets a handle to the serviceworker object via serviceworkerregistration.active, and then calls its postmessage() function.
ServiceWorkerGlobalScope: notificationclick event - Web APIs
bubbles no cancelable no interface notificationevent event handler onnotificationclick
examples you can use the notificationclick event in an addeventlistener method: self.addeventlistener('notificationclick', function(event) { console.log('on notification click: ', event.notification.tag); event.notification.close(); // this looks to see if the current is already open and // focuses if it is event.waituntil(clients.matchall({ type: "window" }).then(function(clientlist) { for (var i = 0; i < clientlist.length; i++) { var client = clientlist[i]; if (client.url ...
ServiceWorkerGlobalScope.oninstall - Web APIs
};
examples the following snippet shows how an install event handler can be used to populate a cache with a number of responses, which the service worker can then use to serve assets offline: this.addeventlistener('install', function(event) { event.waituntil( caches.open('v1').then(function(cache) { return cache.add( '/sw-test/', '/sw-test/index.html', '/sw-test/style.css', '/sw-test/app.js', '/sw-test/image-list.js', '/sw-test/star-wars-logo.jpg', '/sw-test/gallery/',...
ShadowRoot.innerHTML - Web APIs
examples let customelem = document.queryselector('my-shadow-dom-element'); let shadow = customelem.shadowroot; shadow.innerhtml = '<strong>this element should be more important!</strong>'; specifications this property is not defined by any specifications yet; see this open spec issue to specify it.
ShadowRoot.mode - Web APIs
examples let customelem = document.queryselector('my-shadow-dom-element'); let shadow = customelem.shadowroot; // another way to check whether the shadow root is open; it will return null if not if(shadow) { // if it is open, close it to stop people stealing our secrets!
ShadowRoot - Web APIs
examples the following snippets are taken from our life-cycle-callbacks example (see it live also), which creates an element that displays a square of a size and color specified in the element's attributes.
SharedWorker() - Web APIs
examples the following code snippet shows creation of a sharedworker object using the sharedworker() constructor and subsequent usage of the object: var myworker = new sharedworker('worker.js'); myworker.port.start(); first.onchange = function() { myworker.port.postmessage([first.value,second.value]); console.log('message posted to worker'); } second.onchange = function() { myworker.port.postme...
SharedWorkerGlobalScope: connect event - Web APIs
bubbles no cancelable no interface messageevent event handler property sharedworkerglobalscope.onconnect
examples this example shows a shared worker file — when a connection to the worker occurs from a main thread via a messageport, the onconnect event handler fires.
Slottable: assignedSlot - Web APIs
examples in our simple-template example (see it live), we create a trivial custom element example called <my-paragraph> in which a shadow root is attached and then populated using the contents of a template that contains a slot named my-text.
SourceBuffer - Web APIs
examples the following simple example loads a video chunk by chunk as fast as possible, playing it as soon as it can.
SpeechGrammar.SpeechGrammar() - Web APIs
examples var grammar = '#jsgf v1.0; grammar colors; public <color> = aqua | azure | beige | bisque | black | blue | brown | chocolate | coral | crimson | cyan | fuchsia | ghostwhite | gold | goldenrod | gray | green | indigo | ivory | khaki | lavender | lime | linen | magenta | maroon | moccasin | navy | olive | orange | orchid | peru | pink | plum | purple | red | salmon | sienna | silver | snow | tan | teal | thistle | tomato | turquoise | violet | white | yellow ;' var recognition = new speechrecognition(); var speechrecognitionlist = new speechgrammarlist(); speechrecognitionlist.addfromstring(grammar, 1); recognit...
SpeechGrammar.src - Web APIs
examples var grammar = '#jsgf v1.0; grammar colors; public <color> = aqua | azure | beige | bisque | black | blue | brown | chocolate | coral | crimson | cyan | fuchsia | ghostwhite | gold | goldenrod | gray | green | indigo | ivory | khaki | lavender | lime | linen | magenta | maroon | moccasin | navy | olive | orange | orchid | peru | pink | plum | purple | red | salmon | sienna | silver | snow | tan | teal | thistle | tomato | turquoise | violet | white | yellow ;' var recognition = new speechrecognition(); var speechrecognitionlist = new speechgrammarlist()...
SpeechGrammar.weight - Web APIs
examples var grammar = '#jsgf v1.0; grammar colors; public <color> = aqua | azure | beige | bisque | black | blue | brown | chocolate | coral | crimson | cyan | fuchsia | ghostwhite | gold | goldenrod | gray | green | indigo | ivory | khaki | lavender | lime | linen | magenta | maroon | moccasin | navy | olive | orange | orchid | peru | pink | plum | purple | red | salmon | sienna | silver | snow | tan | teal | thistle | tomato | turquoise | violet | white | yellow ;' var recognition = new speechrecognition(); var speechrecognitionlist = n...
SpeechGrammar - Web APIs
examples var grammar = '#jsgf v1.0; grammar colors; public <color> = aqua | azure | beige | bisque | black | blue | brown | chocolate | coral | crimson | cyan | fuchsia | ghostwhite | gold | goldenrod | gray | green | indigo | ivory | khaki | lavender | lime | linen | magenta | maroon | moccasin | navy | olive | orange | orchid | peru | pink | plum | purple | red | salmon | sienna | silver | snow | tan |...
SpeechGrammarList.SpeechGrammarList() - Web APIs
examples in our simple speech color changer example, we create a new speechrecognition object instance using the speechrecognition() constructor, create a new speechgrammarlist, add our grammar string to it using the speechgrammarlist.addfromstring method, and set it to be the grammar that will be recognised by the speechrecognition instance using the speechrecognition.grammars property.
SpeechGrammarList.addFromString() - Web APIs
examples var grammar = '#jsgf v1.0; grammar colors; public <color> = aqua | azure | beige | bisque | black | blue | brown | chocolate | coral | crimson | cyan | fuchsia | ghostwhite | gold | goldenrod | gray | green | indigo | ivory | khaki | lavender | lime | linen | magenta | maroon | moccasin | navy | olive | orange | orchid | peru | pink | plum | purple | red | salmon | sienna | silver | snow | tan |...
SpeechGrammarList.addFromURI() - Web APIs
examples var grammar = '#jsgf v1.0; grammar colors; public <color> = aqua | azure | beige | bisque | black | blue | brown | chocolate | coral | crimson | cyan | fuchsia | ghostwhite | gold | goldenrod | gray | green | indigo | ivory | khaki | lavender | lime | linen | magenta | maroon | moccasin | navy | olive | orange | orchid | peru | pink | plum | purple | red | salmon | sienna | silver | snow | tan |...
SpeechGrammarList.item() - Web APIs
examples var grammar = '#jsgf v1.0; grammar colors; public <color> = aqua | azure | beige | bisque | black | blue | brown | chocolate | coral | crimson | cyan | fuchsia | ghostwhite | gold | goldenrod | gray | green | indigo | ivory | khaki | lavender | lime | linen | magenta | maroon | moccasin | navy | olive | orange | orchid | peru | pink | plum | purple | red | salmon | sienna | silver | snow | tan | teal | thistle | tomato | turquoise | violet | white | yellow ;' var recognition = new speechrecognition(); var speechr...
SpeechGrammarList.length - Web APIs
examples var grammar = '#jsgf v1.0; grammar colors; public <color> = aqua | azure | beige | bisque | black | blue | brown | chocolate | coral | crimson | cyan | fuchsia | ghostwhite | gold | goldenrod | gray | green | indigo | ivory | khaki | lavender | lime | linen | magenta | maroon | moccasin | navy | olive | orange | orchid | peru | pink | plum | purple | red | salmon | sienna | silver | snow | tan | teal | thistle | tomato | turquoise | violet | white | yellow ;' var recognition = new s...
SpeechGrammarList - Web APIs
examples in our simple speech color changer example, we create a new speechrecognition object instance using the speechrecognition() constructor, create a new speechgrammarlist, add our grammar string to it using the speechgrammarlist.addfromstring method, and set it to be the grammar that will be recognised by the speechrecognition instance using the speechrecognition.grammars property.
SpeechRecognition.abort() - Web APIs
examples var grammar = '#jsgf v1.0; grammar colors; public <color> = aqua | azure | beige | bisque | black | blue | brown | chocolate | coral | crimson | cyan | fuchsia | ghostwhite | gold | goldenrod | gray | green | indigo | ivory | khaki | lavender | lime | linen | magenta | maroon | moccasin | navy | olive | orange | orchid | peru | pink | plum | purple | red | salmon | sienna | silver | snow | tan | teal | thistle | tomato | turquoise | violet | white | yellow ;' var recognition = new speechrecognition(); var speechrecognitionlist = new speechgrammar...
SpeechRecognition: audioend event - Web APIs
bubbles no cancelable no interface event event handler onaudioend
examples you can use the audioend event in an addeventlistener method: var recognition = new webkitspeechrecognition() || new speechrecognition(); recognition.addeventlistener('audioend', function() { console.log('audio capturing ended'); }); or use the onaudioend event handler property: recognition.onaudioend = function() { console.log('audio capturing ended'); } specifications specification status comment web speech apithe definition of 'speech recognition events' in that specification.
SpeechRecognition: audiostart event - Web APIs
bubbles no cancelable no interface event event handler onaudiostart
examples you can use the audiostart event in an onaudiostart method: var recognition = new webkitspeechrecognition() || new speechrecognition(); recognition.addeventlistener('audiostart', function() { console.log('audio capturing started'); }); or use the onaudiostart event handler property: recognition.onaudiostart = function() { console.log('audio capturing started'); } specifications specification status comment web speech apithe definition of 'speech recognition events' in that specification.
SpeechRecognition: end event - Web APIs
bubbles no cancelable no interface event event handler property onend
examples you can use the end event in an addeventlistener method: var recognition = new webkitspeechrecognition() || new speechrecognition(); recognition.addeventlistener('end', function() { console.log('speech recognition service disconnected'); }); or use the onend event handler property: recognition.onend = function() { console.log('speech recognition service disconnected'); } specifications specification status comment web speech apithe definition of 'speech recognition events' in that specification.
SpeechRecognition: error event - Web APIs
bubbles no cancelable no interface speechrecognitionerrorevent event handler property onerror
examples you can use the error event in an addeventlistener method: var recognition = new webkitspeechrecognition() || new speechrecognition(); recognition.addeventlistener('error', function(event) { console.log('speech recognition error detected: ' + event.error'); }); or use the onerror event handler property: recognition.onerror = function(event) { console.log('speech recognition error detected: ' + event.error'); } specifications specification status comment web speech apithe definition o...
SpeechRecognition: nomatch event - Web APIs
bubbles no cancelable no interface speechrecognitionevent event handler property onnomatch
examples you can use the nomatch event in an addeventlistener method: var recognition = new webkitspeechrecognition() || new speechrecognition(); recognition.addeventlistener('nomatch', function() { console.log('speech not recognized'); }); or use the onnomatch event handler property: recognition.onnomatch = function() { console.log('speech not recognized'); } specifications specificat...
SpeechRecognition.onaudioend - Web APIs
};
examples var recognition = new speechrecognition(); recognition.onaudioend = function() { console.log('audio capturing ended'); } specifications specification status comment web speech apithe definition of 'onaudioend' in that specification.
SpeechRecognition.onaudiostart - Web APIs
};
examples var recognition = new speechrecognition(); recognition.onaudiostart = function() { console.log('audio capturing started'); } specifications specification status comment web speech apithe definition of 'onaudiostart' in that specification.
SpeechRecognition.onend - Web APIs
};
examples var recognition = new speechrecognition(); recognition.onend = function() { console.log('speech recognition service disconnected'); } specifications specification status comment web speech apithe definition of 'onend' in that specification.
SpeechRecognition.onerror - Web APIs
};
examples var recognition = new speechrecognition(); recognition.onerror = function(event) { console.log('speech recognition error detected: ' + event.error); } specifications specification status comment web speech apithe definition of 'onerror' in that specification.
SpeechRecognition.onnomatch - Web APIs
};
examples var recognition = new speechrecognition(); recognition.onnomatch = function() { console.log('speech not recognised'); } specifications specification status comment web speech apithe definition of 'onnomatch' in that specification.
SpeechRecognition.onsoundend - Web APIs
};
examples recognition.onsoundend = function() { console.log('sound has stopped being received'); } specifications specification status comment web speech apithe definition of 'onsoundend' in that specification.
SpeechRecognition.onsoundstart - Web APIs
};
examples recognition.onsoundstart = function() { console.log('some sound is being received'); } specifications specification status comment web speech apithe definition of 'onsoundstart' in that specification.
SpeechRecognition.onspeechend - Web APIs
};
examples recognition.onspeechend = function() { console.log('speech has stopped being detected'); } specifications specification status comment web speech apithe definition of 'onspeechend' in that specification.
SpeechRecognition.onspeechstart - Web APIs
};
examples recognition.onspeechstart = function() { console.log('speech has been detected'); } specifications specification status comment web speech apithe definition of 'onspeechstart' in that specification.
SpeechRecognition.onstart - Web APIs
};
examples recognition.onstart = function() { console.log('speech recognition service has started'); } specifications specification status comment web speech apithe definition of 'onstart' in that specification.
SpeechRecognition: result event - Web APIs
the result event of the web speech api is fired when the speech recognition service returns a result — a word or phrase has been positively recognized and this has been communicated back to the app bubbles no cancelable no interface speechrecognitionevent event handler property onresult
examples this code is excerpted from our speech color changer example.
SpeechRecognition: soundend event - Web APIs
bubbles no cancelable no interface event event handler property onsoundend
examples you can use the soundend event in an addeventlistener method: var recognition = new webkitspeechrecognition() || new speechrecognition(); recognition.addeventlistener('soundend', function(event) { console.log('sound has stopped being received'); }); or use the onsoundend event handler property: recognition.onsoundend = function(event) { console.log('sound has stopped being received'); } specifications specification status comment web speech apithe definition of 'speech recognition event...
SpeechRecognition: soundstart event - Web APIs
bubbles no cancelable no interface event event handler property onsoundstart
examples you can use the soundstart event in an addeventlistener method: var recognition = new webkitspeechrecognition() || new speechrecognition(); recognition.addeventlistener('soundstart', function() { console.log('some sound is being received'); }); or use the onsoundstart event handler property: recognition.onsoundstart = function() { console.log('some sound is being received'); } specifications specification status comment web speech apithe definition of 'speech recognition events' in that specif...
SpeechRecognition: speechend event - Web APIs
bubbles no cancelable no interface event event handler property onspeechend
examples you can use the speechend event in an addeventlistener method: var recognition = new webkitspeechrecognition() || new speechrecognition(); recognition.addeventlistener('speechend', function() { console.log('speech has stopped being detected'); }); or use the onspeechend event handler property: recognition.onspeechend = function() { console.log('speech has stopped being detected'); } specifications specification status comment web speech apithe definition of 'speech recognition ev...
SpeechRecognition: speechstart event - Web APIs
bubbles no cancelable no interface event event handler property onspeechstart
examples you can use the speechstart event in an addeventlistener method: var recognition = new webkitspeechrecognition() || new speechrecognition(); recognition.addeventlistener('speechstart', function() { console.log('speech has been detected'); }); or use the onspeechstart event handler property: recognition.onspeechstart = function() { console.log('speech has been detected'); } specifications specification status comment web speech apithe definition of 'speech recognition events...
SpeechRecognition.start() - Web APIs
examples var grammar = '#jsgf v1.0; grammar colors; public <color> = aqua | azure | beige | bisque | black | blue | brown | chocolate | coral | crimson | cyan | fuchsia | ghostwhite | gold | goldenrod | gray | green | indigo | ivory | khaki | lavender | lime | linen | magenta | maroon | moccasin | navy | olive | orange | orchid | peru | pink | plum | purple | red | salmon | sienna | silver | snow | tan | teal | thistle | tomato | turquoise | violet | white | yellow ;' var recognition = new speechrecognition(); var speechrecognition...
SpeechRecognition: start event - Web APIs
bubbles no cancelable no interface event event handler property onstart
examples you can use the start event in an addeventlistener method: var recognition = new webkitspeechrecognition() || new speechrecognition(); recognition.addeventlistener('start', function() { console.log('speech recognition service has started'); }); or use the onstart event handler property: recognition.onstart = function() { console.log('speech recognition service has started'); } specifications specification ...
SpeechRecognition.stop() - Web APIs
examples var grammar = '#jsgf v1.0; grammar colors; public <color> = aqua | azure | beige | bisque | black | blue | brown | chocolate | coral | crimson | cyan | fuchsia | ghostwhite | gold | goldenrod | gray | green | indigo | ivory | khaki | lavender | lime | linen | magenta | maroon | moccasin | navy | olive | orange | orchid | peru | pink | plum | purple | red | salmon | sienna | silver | snow | tan | teal | thistle | tomato | turquoise | violet | white | yellow ;' var recognition = new speechrecognition(); var speechrecognitionl...
SpeechRecognition - Web APIs
examples in our simple speech color changer example, we create a new speechrecognition object instance using the speechrecognition() constructor, create a new speechgrammarlist, and set it to be the grammar that will be recognised by the speechrecognition instance using the speechrecognition.grammars property.
SpeechRecognitionError.error - Web APIs
examples var recognition = new speechrecognition(); recognition.onerror = function(event) { console.log('speech recognition error detected: ' + event.error); console.log('additional information: ' + event.message); } ...
SpeechRecognitionError.message - Web APIs
examples var recognition = new speechrecognition(); recognition.onerror = function(event) { console.log('speech recognition error detected: ' + event.error); console.log('additional information: ' + event.message); } ...
SpeechRecognitionError - Web APIs
examples var recognition = new speechrecognition(); recognition.onerror = function(event) { console.log('speech recognition error detected: ' + event.error); console.log('additional information: ' + event.message); } ...
SpeechRecognitionErrorEvent.error - Web APIs
examples var recognition = new speechrecognition(); recognition.onerror = function(event) { console.log('speech recognition error detected: ' + event.error); console.log('additional information: ' + event.message); } specifications specification status comment web speech apithe definition of 'error' in that specification.
SpeechRecognitionErrorEvent.message - Web APIs
examples var recognition = new speechrecognition(); recognition.onerror = function(event) { console.log('speech recognition error detected: ' + event.error); console.log('additional information: ' + event.message); } specifications specification status comment web speech apithe definition of 'message' in that specification.
SpeechSynthesis: voiceschanged event - Web APIs
the voiceschanged event of the web speech api is fired when the list of speechsynthesisvoice objects that would be returned by the speechsynthesis.getvoices() method has changed (when the voiceschanged event fires.) bubbles no cancelable no interface event event handler property onvoiceschanged
examples this could be used to repopulate a list of voices that the user can choose between when the event fires.
SpeechSynthesis - Web APIs
examples first, a simple example: let utterance = new speechsynthesisutterance("hello world!"); speechsynthesis.speak(utterance); now we'll look at a more fully-fledged example.
SpeechSynthesisErrorEvent.error - Web APIs
examples var synth = window.speechsynthesis; var inputform = document.queryselector('form'); var inputtxt = document.queryselector('input'); var voiceselect = document.queryselector('select'); var voices = synth.getvoices(); ...
SpeechSynthesisErrorEvent - Web APIs
examples var synth = window.speechsynthesis; var inputform = document.queryselector('form'); var inputtxt = document.queryselector('input'); var voiceselect = document.queryselector('select'); var voices = synth.getvoices(); ...
SpeechSynthesisEvent.charIndex - Web APIs
examples utterthis.onpause = function(event) { var char = event.utterance.text.charat(event.charindex); console.log('speech paused at character ' + event.charindex + ' of "' + event.utterance.text + '", which is "' + char + '".'); } specifications specification status comment web speech apithe definition of 'charindex' in that specification.
SpeechSynthesisEvent.elapsedTime - Web APIs
examples utterthis.onboundary = function(event) { console.log(event.name + ' boundary reached after ' + event.elapsedtime + ' seconds.'); } specifications specification status comment web speech apithe definition of 'elapsedtime' in that specification.
SpeechSynthesisEvent.name - Web APIs
examples utterthis.onboundary = function(event) { console.log(event.name + ' boundary reached after ' + event.elapsedtime + ' milliseconds.'); } specifications specification status comment web speech apithe definition of 'name' in that specification.
SpeechSynthesisEvent.utterance - Web APIs
examples utterthis.onpause = function(event) { var char = event.utterance.text.charat(event.charindex); console.log('speech paused at character ' + event.charindex + ' of "' + event.utterance.text + '", which is "' + char + '".'); } specifications specification status comment web speech apithe definition of 'utterance' in that specification.
SpeechSynthesisEvent - Web APIs
examples utterthis.onpause = function(event) { var char = event.utterance.text.charat(event.charindex); console.log('speech paused at character ' + event.charindex + ' of "' + event.utterance.text + '", which is "' + char + '".'); } utterthis.onboundary = function(event) { console.log(event.name + ' boundary reached after ' + event.elapsedtime + ' milliseconds.'); } specifications spe...
SpeechSynthesisUtterance: boundary event - Web APIs
bubbles no cancelable no interface speechsynthesisevent event handler onboundary
examples you can use the boundary event in an addeventlistener method: utterthis.addeventlistener('boundary', function(event) { console.log(event.name + ' boundary reached after ' + event.elapsedtime + ' milliseconds.'); }); or use the onboundary event handler property: utterthis.onboundary = function(event) { console.log(event.name + ' boundary reached after ' + event.elapsedtime + ' milliseconds.'); } specifications specification status comment web speech apithe definition of 'speech synthesis utterance ...
SpeechSynthesisUtterance: end event - Web APIs
bubbles no cancelable no interface speechsynthesisevent event handler property onend
examples you can use the end event in an addeventlistener method: utterthis.addeventlistener('end', function(event) { console.log('utterance has finished being spoken after ' + event.elapsedtime + ' milliseconds.'); }); or use the onend event handler property: utterthis.onend = function(event) { console.log('utterance has finished being spoken after ' + event.elapsedtime + ' milliseconds.'); } specifications specification status comment web speech apithe definition of 'speech synthesis uttera...
SpeechSynthesisUtterance: error event - Web APIs
bubbles no cancelable no interface speechsynthesiserrorevent event handler property onerror
examples you can use the error event in an addeventlistener method: utterthis.addeventlistener('error', function(event) { console.log('an error has occurred with the speech synthesis: ' + event.error'); }); or use the onerror event handler property: utterthis.onerror = function(event) { console.log('an error has occurred with the speech synthesis: ' + event.error'); } specifications specification status comment web speech apithe definition of 'speech...
SpeechSynthesisUtterance.lang - Web APIs
examples var synth = window.speechsynthesis; var inputform = document.queryselector('form'); var inputtxt = document.queryselector('input'); var voiceselect = document.queryselector('select'); var voices = synth.getvoices(); ...
SpeechSynthesisUtterance: mark event - Web APIs
bubbles no cancelable no interface speechsynthesisevent event handler property onmark
examples you can use the mark event in an addeventlistener method: utterthis.addeventlistener('mark', function(event) { console.log('a mark was reached: ' + event.name); }); or use the onmark event handler property: utterthis.onmark = function(event) { console.log('a mark was reached: ' + event.name); } specifications specification status comment web speech apithe definition of 'speech synthesis utterance events' in that specification.
SpeechSynthesisUtterance.onboundary - Web APIs
};
examples var synth = window.speechsynthesis; var inputform = document.queryselector('form'); var inputtxt = document.queryselector('input'); var voiceselect = document.queryselector('select'); var voices = synth.getvoices(); ...
SpeechSynthesisUtterance.onend - Web APIs
};
examples var synth = window.speechsynthesis; var inputform = document.queryselector('form'); var inputtxt = document.queryselector('input'); var voiceselect = document.queryselector('select'); var voices = synth.getvoices(); ...
SpeechSynthesisUtterance.onerror - Web APIs
};
examples var synth = window.speechsynthesis; var inputform = document.queryselector('form'); var inputtxt = document.queryselector('input'); var voiceselect = document.queryselector('select'); var voices = synth.getvoices(); ...
SpeechSynthesisUtterance.onmark - Web APIs
};
examples var synth = window.speechsynthesis; var inputform = document.queryselector('form'); var inputtxt = document.queryselector('input'); var voiceselect = document.queryselector('select'); var voices = synth.getvoices(); ...
SpeechSynthesisUtterance.onpause - Web APIs
};
examples var synth = window.speechsynthesis; var inputform = document.queryselector('form'); var inputtxt = document.queryselector('input'); var voiceselect = document.queryselector('select'); var voices = synth.getvoices(); ...
SpeechSynthesisUtterance.onresume - Web APIs
};
examples var synth = window.speechsynthesis; var inputform = document.queryselector('form'); var inputtxt = document.queryselector('input'); var voiceselect = document.queryselector('select'); var voices = synth.getvoices(); ...
SpeechSynthesisUtterance.onstart - Web APIs
};
examples var synth = window.speechsynthesis; var inputform = document.queryselector('form'); var inputtxt = document.queryselector('input'); var voiceselect = document.queryselector('select'); var voices = synth.getvoices(); ...
SpeechSynthesisUtterance: pause event - Web APIs
bubbles no cancelable no interface speechsynthesisevent event handler property onpause
examples you can use the pause event in an addeventlistener method: utterthis.addeventlistener('pause', function(event) { console.log('speech paused after ' + event.elapsedtime + ' milliseconds.'); }); or use the onpause event handler property: utterthis.onpause = function(event) { console.log('speech paused after ' + event.elapsedtime + ' milliseconds.'); } specifications specification status comment web speech apithe definition of 'speech synthesis utterance events' in that specificati...
SpeechSynthesisUtterance.pitch - Web APIs
examples var synth = window.speechsynthesis; var inputform = document.queryselector('form'); var inputtxt = document.queryselector('input'); var voiceselect = document.queryselector('select'); var voices = synth.getvoices(); ...
SpeechSynthesisUtterance.rate - Web APIs
examples var synth = window.speechsynthesis; var inputform = document.queryselector('form'); var inputtxt = document.queryselector('input'); var voiceselect = document.queryselector('select'); var voices = synth.getvoices(); ...
SpeechSynthesisUtterance: resume event - Web APIs
bubbles no cancelable no interface speechsynthesisevent event handler property onresume
examples you can use the resume event in an addeventlistener method: utterthis.addeventlistener('resume', function(event) { console.log('speech resumed after ' + event.elapsedtime + ' milliseconds.'); }); or use the onresume event handler property: utterthis.onresume = function(event) { console.log('speech resumed after ' + event.elapsedtime + ' milliseconds.'); } specifications specification status comment web speech apithe definition of 'speech synthesis utterance events' in that specification.
SpeechSynthesisUtterance: start event - Web APIs
bubbles no cancelable no interface speechsynthesisevent event handler property onstart
examples you can use the start event in an addeventlistener method: utterthis.addeventlistener('start', function(event) { console.log('we have started uttering this speech: ' + event.utterance.text); }); or use the onstart event handler property: utterthis.onstart = function(event) { console.log('we have started uttering this speech: ' + event.utterance.text); } specifications specification status comment web speech apithe definition of 'speech synthesis utterance events' in that specificati...
SpeechSynthesisUtterance.text - Web APIs
examples var synth = window.speechsynthesis; var inputform = document.queryselector('form'); var inputtxt = document.queryselector('input'); var voiceselect = document.queryselector('select'); var voices = synth.getvoices(); ...
SpeechSynthesisUtterance.voice - Web APIs
examples var synth = window.speechsynthesis; var inputform = document.queryselector('form'); var inputtxt = document.queryselector('input'); var voiceselect = document.queryselector('select'); var voices = synth.getvoices(); ...
SpeechSynthesisUtterance.volume - Web APIs
examples var synth = window.speechsynthesis; var inputform = document.queryselector('form'); var inputtxt = document.queryselector('input'); var voiceselect = document.queryselector('select'); var voices = synth.getvoices(); ...
SpeechSynthesisUtterance - Web APIs
examples in our basic speech synthesiser demo (source), we first grab a reference to the speechsynthesis controller using window.speechsynthesis.
SpeechSynthesisVoice.default - Web APIs
examples for(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); voiceselect.appendchild(option); } specifications sp...
SpeechSynthesisVoice.lang - Web APIs
examples for(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); voiceselect.appendchild(option); } specifications specification status comment web speech apithe definition of 'lang' in that specification.
SpeechSynthesisVoice.localService - Web APIs
examples for(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'; } console.log(voices[i].localservice); option.setattribute('data-lang', voices[i].lang); option.setattribute('data-name', voices[i].name); voiceselect.appendchild...
SpeechSynthesisVoice.name - Web APIs
examples for(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); voiceselect.appendchild(option); } specifications specification status comment web speech apithe definition of 'name' in that specification.
SpeechSynthesisVoice.voiceURI - Web APIs
examples for(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'; } console.log(voices[i].voiceuri); // on mac, this returns urns, for example 'urn:moz-tts:osx:com.apple.speech.synthesis.voice.daniel' option.setattribute('data-lan...
Storage.clear() - Web APIs
examples the following function creates three data entries in local storage, and then deletes them by using clear().
Storage.key() - Web APIs
examples the following function iterates over the local storage keys: function foreachkey(callback) { for (var i = 0; i < localstorage.length; i++) { callback(localstorage.key(i)); } } the following function iterates over the local storage keys and gets the value set for each key: for(var i =0; i < localstorage.length; i++){ console.log(localstorage.getitem(localstorage.key(i))); } note: f...
TextDecoder - Web APIs
examples representing text with typed arrays this example shows how to decode a chinese/japanese character , as represented by five different typed arrays: uint8array, int8array, uint16array, int16array, and int32array.
TextEncoder.prototype.encode() - Web APIs
examples <p class="source">this is a sample paragraph.</p> <p class="result">encoded result: </p> const sourcepara = document.queryselector('.source'); const resultpara = document.queryselector('.result'); const string = sourcepara.textcontent; const textencoder = new textencoder(); let encoded = textencoder.encode(string); resultpara.textcontent += encoded; specifications specification status comment encodingthe definition of '...
TextEncoder.prototype.encodeInto() - Web APIs
u8array.subarray(position|0) : u8array); if (stats.written < u8array.length) u8array[stats.written] = 0; // append null if room return stats; }
examples <p class="source">this is a sample paragraph.</p> <p class="result"></p> const sourcepara = document.queryselector('.source'); const resultpara = document.queryselector('.result'); const string = sourcepara.textcontent; const textencoder = new textencoder(); const utf8 = new uint8array(string.length); let encodedresults = textencoder.encodeinto(string, utf8); resultpara.textcontent += 'bytes ...
TextMetrics.actualBoundingBoxAscent - Web APIs
examples const canvas = document.createelement('canvas'); const ctx = canvas.getcontext('2d'); const text = ctx.measuretext('foo'); // returns textmetrics object text.actualboundingboxascent; // 8; specifications specification html living standardthe definition of 'textmetrics.actualboundingboxascent' in that specification.
TextMetrics.actualBoundingBoxDescent - Web APIs
examples const canvas = document.createelement('canvas'); const ctx = canvas.getcontext('2d'); const text = ctx.measuretext('foo'); // returns textmetrics object text.actualboundingboxdescent; // 0; specifications specification html living standardthe definition of 'textmetrics.actualboundingboxdescent' in that specification.
TextMetrics.actualBoundingBoxLeft - Web APIs
examples const canvas = document.createelement('canvas'); const ctx = canvas.getcontext('2d'); const text = ctx.measuretext('foo'); // returns textmetrics object text.actualboundingboxleft; // 0; specifications specification html living standardthe definition of 'textmetrics.actualboundingboxleft' in that specification.
TextMetrics.actualBoundingBoxRight - Web APIs
examples const canvas = document.createelement('canvas'); const ctx = canvas.getcontext('2d'); const text = ctx.measuretext('foo'); // returns textmetrics object text.actualboundingboxright; // 15.633333333333333; specifications specification html living standardthe definition of 'textmetrics.actualboundingboxright' in that specification.
TextMetrics.alphabeticBaseline - Web APIs
examples const canvas = document.createelement('canvas'); const ctx = canvas.getcontext('2d'); const text = ctx.measuretext('foo'); // returns textmetrics object text.alphabeticbaseline; // -0; specifications specification html living standardthe definition of 'textmetrics.alphabeticbaseline' in that specification.
TextMetrics.emHeightAscent - Web APIs
examples const canvas = document.createelement('canvas'); const ctx = canvas.getcontext('2d'); const text = ctx.measuretext('foo'); // returns textmetrics object text.emheightascent; // 7.59765625; specifications specification html living standardthe definition of 'textmetrics.emheightascent' in that specification.
TextMetrics.emHeightDescent - Web APIs
examples const canvas = document.createelement('canvas'); const ctx = canvas.getcontext('2d'); const text = ctx.measuretext('foo'); // returns textmetrics object text.emheightdescent; // -2.40234375; specifications specification html living standardthe definition of 'textmetrics.emheightdescent' in that specification.
TextMetrics.fontBoundingBoxAscent - Web APIs
examples const canvas = document.createelement('canvas'); const ctx = canvas.getcontext('2d'); const text = ctx.measuretext('foo'); // returns textmetrics object text.fontboundingboxascent; // 10; specifications specification html living standardthe definition of 'textmetrics.fontboundingboxascent' in that specification.
TextMetrics.fontBoundingBoxDescent - Web APIs
examples const canvas = document.createelement('canvas'); const ctx = canvas.getcontext('2d'); const text = ctx.measuretext('foo'); // returns textmetrics object text.fontboundingboxdescent; // 3; specifications specification html living standardthe definition of 'textmetrics.fontboundingboxdescent' in that specification.
TextMetrics.hangingBaseline - Web APIs
examples const canvas = document.createelement('canvas'); const ctx = canvas.getcontext('2d'); const text = ctx.measuretext('foo'); // returns textmetrics object text.hangingbaseline; // 6.078125; specifications specification html living standardthe definition of 'textmetrics.hangingbaseline' in that specification.
TextMetrics.ideographicBaseline - Web APIs
examples const canvas = document.createelement('canvas'); const ctx = canvas.getcontext('2d'); const text = ctx.measuretext('foo'); // returns textmetrics object text.ideographicbaseline; // -1.201171875; specifications specification html living standardthe definition of 'textmetrics.ideographicbaseline' in that specification.
TextMetrics - Web APIs
examples baselines illustrated this example demonstrates the baselines the textmetrics object holds.
TextTrack: cuechange event - Web APIs
bubbles no cancelable no interface event event handler property globaleventhandlers.oncuechange
examples on the texttrack you can set up a listener for the cuechange event on a texttrack using the addeventlistener() method: track.addeventlistener('cuechange', function () { let cues = track.activecues; // array of current cues }); or you can just set the oncuechange event handler property: track.oncuechange = function () { let cues = track.activecues; // array of current cues } on the track element the underlying texttrack, indicated by th...
TextTrackList: addtrack event - Web APIs
bubbles no cancelable no interface trackevent event handler property onaddtrack
examples using addeventlistener(): const mediaelement = document.queryselector('video, audio'); mediaelement.texttracks.addeventlistener('addtrack', (event) => { console.log(`text track: ${event.track.label} added`); }); using the onaddtrack event handler property: const mediaelement = document.queryselector('video, audio'); mediaelement.texttracks.onaddtrack = (event) => { console.log(`text track: ${event.track.label} added`); }; specifications specification status html living standardthe definition of 'addtrack' in that specification.
TextTrackList: change event - Web APIs
bubbles no cancelable no interface event event handler property onchange
examples using addeventlistener(): const mediaelement = document.queryselectorall('video, audio')[0]; mediaelement.texttracks.addeventlistener('change', (event) => { console.log(`'${event.type}' event fired`); }); using the onchange event handler property: const mediaelement = document.queryselector('video, audio'); mediaelement.texttracks.onchange = (event) => { console.log(`'${event.type}' event fired`); }; specifications specification status html living standardthe definition of 'change' in that specification.
TextTrackList: removeTrack event - Web APIs
bubbles no cancelable no interface trackevent event handler property onremovetrack
examples using addeventlistener(): const mediaelement = document.queryselector('video, audio'); mediaelement.texttracks.addeventlistener('removetrack', (event) => { console.log(`text track: ${event.track.label} removed`); }); using the onremovetrack event handler property: const mediaelement = document.queryselector('video, audio'); mediaelement.texttracks.onremovetrack = (event) => { console.log(`text track: ${event.track.label} removed`); }; specifications specification status html living standardthe definition of 'removetrack' in that specification.
Using Touch Events - Web APIs
examples and demos the following documents describe how to use touch events and include example code: touch events overview implement custom gestures introduction to touch events in javascript add touch screen support to your website (the easy way) touch event demonstrations: paint program (by rick byers) touch/pointer tests and demos (by patrick h.
UIEvent.layerX - Web APIs
examples <html> <head> <title>pagex\pagey & layerx\layery example</title> <script type="text/javascript"> function showcoords(evt){ var form = document.forms.form_coords; var parent_id = evt.target.parentnode.id; form.parentid.value = parent_id; form.pagexcoords.value = evt.pagex; form.pageycoords.value = evt.pagey; form.layerxcoords.value = evt.layerx; form.layerycoords.value = evt.layer...
UIEvent.pageX - Web APIs
examples for an example, see the documentation for the standard mouseevent.pagex property, which you should use instead.
URL() - Web APIs
examples // base urls let m = 'https://developer.mozilla.org'; let a = new url("/", m); // => 'https://developer.mozilla.org/' let b = new url(m); // => 'https://developer.mozilla.org/' new url('docs', b); // => 'https://developer.mozilla.org/docs' let d = new url('/docs', b); // => 'https...
URL.hash - Web APIs
examples const url = new url('/docs/web/api/url/href#
examples'); console.log(url.hash); // logs: '#
examples' specifications specification status comment urlthe definition of 'url.hash' in that specification.
URL.host - Web APIs
examples let url = new url('/docs/web/api/url/host'); console.log(url.host); // "developer.mozilla.org" url = new url('https://developer.mozilla.org:443/docs/web/api/url/host'); console.log(url.host); // "developer.mozilla.org" // the port number is not included because 443 is the scheme's default port url = new url('https://developer.mozilla.org:4097/docs/web/api/url/host'); console.log(url.host); // "developer.mozilla.org:4097" specifications specification status comment ...
URL.hostname - Web APIs
examples const url = new url('/docs/web/api/url/hostname'); console.log(url.hostname); // logs: 'developer.mozilla.org' specifications specification status comment urlthe definition of 'url.hostname' in that specification.
URL.href - Web APIs
examples const url = new url('/docs/web/api/url/href'); console.log(url.href); // logs: '/docs/web/api/url/href' specifications specification status comment urlthe definition of 'url.href' in that specification.
URL.origin - Web APIs
examples const url = new url("blob:https://mozilla.org:443/") console.log(url.origin); // logs 'https://mozilla.org' specifications specification status comment urlthe definition of 'url.origin' in that specification.
URL.password - Web APIs
examples const url = new url('https://anonymous:flabada@developer.mozilla.org/docs/web/api/url/password'); console.log(url.password) // logs "flabada" specifications specification status comment urlthe definition of 'url.password' in that specification.
URL.pathname - Web APIs
examples const url = new url('/docs/web/api/url/pathname?q=value'); console.log(url.pathname); // logs "/docs/web/api/url/pathname" specifications specification status comment urlthe definition of 'url.pathname' in that specification.
URL.pathname - Web APIs
examples const url = new url('/docs/web/api/url/pathname?q=value'); console.log(url.pathname); // logs "/docs/web/api/url/pathname" specifications specification status comment urlthe definition of 'url.pathname' in that specification.
URL.port - Web APIs
examples const url = new url('https://mydomain.com:80/svn/repos/'); console.log(url.port); // logs '80' specifications specification status comment urlthe definition of 'url.port' in that specification.
URL.protocol - Web APIs
examples const url = new url('/docs/web/api/url/protocol'); console.log(url.protocol); // logs "https:" specifications specification status comment urlthe definition of 'protocol' in that specification.
URL.search - Web APIs
examples const url = new url('/docs/web/api/url/search?q=123'); console.log(url.search); // logs "?q=123" specifications specification status comment urlthe definition of 'url.search' in that specification.
URL.search - Web APIs
examples const url = new url('/docs/web/api/url/search?q=123'); console.log(url.search); // logs "?q=123" specifications specification status comment urlthe definition of 'url.search' in that specification.
URL.searchParams - Web APIs
examples if the url of your page is https://example.com/?name=jonathan%20smith&age=18 you could parse out the name and age parameters using: let params = (new url(document.location)).searchparams; let name = params.get('name'); // is the string "jonathan smith".
URL.toJSON() - Web APIs
examples const url = new url("/docs/web/api/url/tostring"); url.tojson(); // should return the url as a string specifications specification status comment urlthe definition of 'tojson()' in that specification.
URL.toString() - Web APIs
examples const url = new url("/docs/web/api/url/tostring"); url.tostring(); // should return the url as a string specifications specification status comment urlthe definition of 'stringifier' in that specification.
URL.username - Web APIs
examples const url = new url('https://anonymous:flabada@developer.mozilla.org/docs/web/api/url/username'); console.log(url.username) // logs "anonymous" specifications specification status comment urlthe definition of 'username' in that specification.
URLSearchParams.append() - Web APIs
examples let url = new url('https://example.com?foo=1&bar=2'); let params = new urlsearchparams(url.search.slice(1)); //add a second foo parameter.
URLSearchParams.delete() - Web APIs
return value void
examples let url = new url('https://example.com?foo=1&bar=2&foo=3'); let params = new urlsearchparams(url.search.slice(1)); // delete the foo parameter.
URLSearchParams.entries() - Web APIs
examples // create a test urlsearchparams object var searchparams = new urlsearchparams("key1=value1&key2=value2"); // display the key/value pairs for(var pair of searchparams.entries()) { console.log(pair[0]+ ', '+ pair[1]); } the result is: key1, value1 key2, value2 specifications specification status comment urlthe definition of 'entries() (see "iterable")' in that specification.
URLSearchParams.forEach() - Web APIs
examples // create a test urlsearchparams object var searchparams = new urlsearchparams("key1=value1&key2=value2"); // log the values searchparams.foreach(function(value, key) { console.log(value, key); }); the result is: value1 key1 value2 key2 specifications specification status comment urlthe definition of 'foreach() (see "iterable")' in that specification.
URLSearchParams.get() - Web APIs
examples if the url of your page is https://example.com/?name=jonathan&age=18 you could parse out the 'name' and 'age' parameters using: let params = new urlsearchparams(document.location.search.substring(1)); let name = params.get("name"); // is the string "jonathan" let age = parseint(params.get("age"), 10); // is the number 18 requesting a parameter that isn't present in the query string will return null: let address = params.get("address"); // null ...
URLSearchParams.getAll() - Web APIs
examples let url = new url('https://example.com?foo=1&bar=2'); let params = new urlsearchparams(url.search.slice(1)); //add a second foo parameter.
URLSearchParams.has() - Web APIs
examples let url = new url('https://example.com?foo=1&bar=2'); let params = new urlsearchparams(url.search.slice(1)); params.has('bar') === true; //true specifications specification status comment urlthe definition of 'has()' in that specification.
URLSearchParams.keys() - Web APIs
examples // create a test urlsearchparams object var searchparams = new urlsearchparams("key1=value1&key2=value2"); // display the keys for(var key of searchparams.keys()) { console.log(key); } the result is: key1 key2 specifications specification status comment urlthe definition of 'keys() (see "iterable")' in that specification.
URLSearchParams.set() - Web APIs
examples let's start with a simple example: let url = new url('https://example.com?foo=1&bar=2'); let params = new urlsearchparams(url.search.slice(1)); //add a third parameter.
URLSearchParams.sort() - Web APIs
examples // create a test urlsearchparams object var searchparams = new urlsearchparams("c=4&a=2&b=3&a=1"); // sort the key/value pairs searchparams.sort(); // display the sorted query string console.log(searchparams.tostring()); the result is: a=2&a=1&b=3&c=4 specifications specification status comment urlthe definition of 'sort()' in that specification.
URLSearchParams.toString() - Web APIs
(returns an empty string if no search parameters have been set.)
examples let url = new url('https://example.com?foo=1&bar=2'); let params = new urlsearchparams(url.search.slice(1)); //add a second foo parameter.
URLSearchParams.values() - Web APIs
examples // create a test urlsearchparams object var searchparams = new urlsearchparams("key1=value1&key2=value2"); // display the values for(var value of searchparams.values()) { console.log(value); } the result is: value1 value2 specifications specification status comment urlthe definition of 'values() (see "iterable")' in that specification.
URLSearchParams - Web APIs
examples var paramsstring = "q=urlutils.searchparams&topic=api"; var searchparams = new urlsearchparams(paramsstring); //iterate the search parameters.
URLUtilsReadOnly.hash - Web APIs
syntax string = object.hash;
examples // in a web worker, on the page https://developer.mozilla.org/docs/urlutilsreadonly.hash#example var result = window.self.hash; // returns:'#hash' specifications specification status comment urlthe definition of 'urlutilsreadonly.hash' in that specification.
URLUtilsReadOnly.host - Web APIs
syntax string = object.host;
examples // in a web worker, on the page https://developer.mozilla.org/urlutilsreadonly.host var result = window.self.host; // returns:'developer.mozilla.org:80' specifications specification status comment urlthe definition of 'urlutilsreadonly.host' in that specification.
URLUtilsReadOnly.hostname - Web APIs
syntax string = object.hostname;
examples // in a web worker, on the page https://developer.mozilla.org/urlutilsreadonly.hostname var result = window.self.hostname; // returns:'developer.mozilla.org' specifications specification status comment urlthe definition of 'urlutilsreadonly.hostname' in that specification.
URLUtilsReadOnly.href - Web APIs
syntax string = object.href;
examples // in a web worker, on the page https://developer.mozilla.org/urlutilsreadonly.href var result = window.self.href; // returns:'https://developer.mozilla.org/urlutilsreadonly.href' specifications specification status comment urlthe definition of 'urlutilsreadonly.href' in that specification.
URLUtilsReadOnly.origin - Web APIs
syntax string = object.origin;
examples // on this page, returns the origin var result = self.location.origin; // returns:'https://developer.mozilla.org:443' specifications specification status comment urlthe definition of 'urlutilsreadonly.origin' in that specification.
URLUtilsReadOnly.pathname - Web APIs
syntax string = object.pathname;
examples // in a web worker, on the page https://developer.mozilla.org/urlutilsreadonly.pathname var result = window.self.pathname; // returns:'/urlutilsreadonly.pathname' specifications specification status comment urlthe definition of 'urlutilsreadonly.pathname' in that specification.
URLUtilsReadOnly.port - Web APIs
syntax string = object.port;
examples // in a web worker, on the page https://developer.mozilla.org/urlutilsreadonly.port var result = window.self.port; // returns:'80' specifications specification status comment urlthe definition of 'urlutilsreadonly.port' in that specification.
URLUtilsReadOnly.protocol - Web APIs
syntax string = object.protocol;
examples // in a web worker, on the page https://developer.mozilla.org/urlutilsreadonly.href var result = window.self.protocol; // returns:'https:' specifications specification status comment urlthe definition of 'urlutilsreadonly.protocol' in that specification.
URLUtilsReadOnly.search - Web APIs
syntax string = object.search;
examples // in a web worker, on the page https://developer.mozilla.org/docs/urlutilsreadonly.href?t=67 var result = window.self.search; // returns:'?t=67' specifications specification status comment urlthe definition of 'urlutilsreadonly.search' in that specification.
URLUtilsReadOnly.toString() - Web APIs
syntax string = object.tostring();
examples // in a web worker, on the page https://developer.mozilla.org/urlutilsreadonly.href var result = window.self.tostring(); // returns:'https://developer.mozilla.org/urlutilsreadonly.href' browser compatibility the compatibility table in this page is generated from structured data.
URL API - Web APIs
examples if you want to process the parameters included in a url, you could do it manually, but it's much easier to create a url object to do it for you.
USBEndpoint - Web APIs
examples while sometimes the developer knows ahead of time the exact layout of a device's endpoints there are cases where this must be discovered at runtime.
VRStageParameters - Web APIs
examples var info = document.queryselector('p'); var vrdisplay; navigator.getvrdisplays().then(function(displays) { vrdisplay = displays[0]; var stageparams = vrdisplay.stageparameters; // stageparams is a vrstageparameters object if(stageparams === null) { info.textcontent = 'your vr hardware does not support room-scale experiences.' } else { info.innerhtml = '<strong>display stage p...
VTTRegion - Web APIs
examples var region = new vttregion(); region.width = 50; // use 50% of the video width region.lines = 4; // use 4 lines of height.
ValidityState.patternMismatch - Web APIs
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-di...
ValidityState.typeMismatch - Web APIs
type attribute conformance input type value expected value email x@y or x@y.z email address, with or without tld url x: or x://y.z protocol or full url with protocol
examples given the following: <p> <label> enter an email address: <input type="email" value="example.com"/> </label> </p> <p> <label> enter a url: <input type="url" value="example.com"/> </label> </p> input:invalid { border: red solid 3px; } the above each produce a typemismatch because the email address is just a domain and the url has no protocol the typemismatch occurs w...
Vibration API - Web APIs
a single vibration you may pulse the vibration hardware one time by specifying either a single value or an array consisting of only one value: window.navigator.vibrate(200); window.navigator.vibrate([200]); both of these
examples vibrate the device for 200 ms.
VideoConfiguration - Web APIs
examples // create media configuration to be tested const mediaconfig = { type : 'file', // see mediadecodingconfiguration and mediaencodingconfiguration video : { contenttype : "video/webm;codecs=vp8", // valid content type width : 800, // width of the video height : 600, // height of the video bitrate : 10000, // number of bits used to encode 1s of video ...
VideoTrackList: addtrack event - Web APIs
bubbles no cancelable no interface trackevent event handler property onaddtrack
examples using addeventlistener(): const videoelement = document.queryselector('video'); videoelement.videotracks.addeventlistener('addtrack', (event) => { console.log(`video track: ${event.track.label} added`); }); using the onaddtrack event handler property: const videoelement = document.queryselector('video'); videoelement.videotracks.onaddtrack = (event) => { console.log(`video track: ${event.track.label} added`); }; specifications specification status html living standardthe definition of 'addtrack' in that specification.
VideoTrackList: change event - Web APIs
bubbles no cancelable no interface event event handler property onchange
examples using addeventlistener(): const videoelement = document.queryselector('video'); videoelement.videotracks.addeventlistener('change', (event) => { console.log(`'${event.type}' event fired`); }); // changing the value of `selected` will trigger the `change` event const toggletrackbutton = document.queryselector('.toggle-track'); toggletrackbutton.addeventlistener('click', () => { const track = videoelement.videotracks[0]; track.selected = !track.selected; }); using the onchange event handler property: const videoelement = do...
VideoTrackList: removetrack event - Web APIs
bubbles no cancelable no interface trackevent event handler property onremovetrack
examples using addeventlistener(): const videoelement = document.queryselector('video'); videoelement.videotracks.addeventlistener('removetrack', (event) => { console.log(`video track: ${event.track.label} removed`); }); using the onremovetrack event handler property: const videoelement = document.queryselector('video'); videoelement.videotracks.onremovetrack = (event) => { console.log(`video track: ${event.track.label} removed`); }; specifications specification status html living standardthe definition of 'removetrack' in that specification.
VisualViewport: resize event - Web APIs
bubbles no cancelable no interface event event handler property onresize
examples you can use the resize event in an addeventlistener method: visualviewport.addeventlistener('resize', function() { ...
VisualViewport: scroll event - Web APIs
bubbles no cancelable no interface event event handler property onscroll
examples you can use the scroll event in an addeventlistener method: visualviewport.addeventlistener('scroll', function() { ...
VisualViewport - Web APIs
examples hiding an overlaid box on zoom this example, taken from the visual viewport readme, shows how to write a simple bit of code that will hide an overlaid box (which might contain an advert, say) when the user zooms in.
WEBGL_color_buffer_float - Web APIs
examples var ext = gl.getextension('webgl_color_buffer_float'); gl.renderbufferstorage(gl.renderbuffer, ext.rbga32f_ext, 256, 256); specifications specification status comment webgl_color_buffer_floatthe definition of 'webgl_color_buffer_float' in that specification.
WEBGL_compressed_texture_astc.getSupportedProfiles() - Web APIs
examples var ext = gl.getextension('webgl_compressed_texture_astc'); ext.getsupportedprofiles(); // ["ldr"] specifications specification status comment webgl_compressed_texture_astcthe definition of 'webgl_compressed_texture_astc' in that specification.
WEBGL_compressed_texture_astc - Web APIs
r((height + 9) / 10) * 16 43264 ext.compressed_rgba_astc_12x10_khr ext.compressed_srgb8_alpha8_astc_12x10_khr 12x10 1.07 floor((width + 11) / 12) * floor((height + 9) / 10) * 16 35776 ext.compressed_rgba_astc_12x12_khr ext.compressed_srgb8_alpha8_astc_12x12_khr 12x12 0.89 floor((width + 11) / 12) * floor((height + 11) / 12) * 16 29584
examples var ext = gl.getextension('webgl_compressed_texture_astc'); var texture = gl.createtexture(); gl.bindtexture(gl.texture_2d, texture); gl.compressedteximage2d(gl.texture_2d, 0, ext.compressed_rgba_astc_12x12_khr, 512, 512, 0, texturedata); specifications specification status comment webgl_compressed_texture_astcthe definition of 'webgl_compressed_texture_astc' in that...
WEBGL_compressed_texture_atc - Web APIs
examples var ext = gl.getextension('webgl_compressed_texture_atc'); var texture = gl.createtexture(); gl.bindtexture(gl.texture_2d, texture); gl.compressedteximage2d(gl.texture_2d, 0, ext.compressed_rgb_atc_webgl, 512, 512, 0, texturedata); specifications specification status comment webgl_compressed_texture_atcthe definition of 'webgl_compressed_texture_atc' in that specific...
WEBGL_compressed_texture_etc - Web APIs
examples var ext = gl.getextension('webgl_compressed_texture_etc'); var texture = gl.createtexture(); gl.bindtexture(gl.texture_2d, texture); gl.compressedteximage2d(gl.texture_2d, 0, ext.compressed_rgba8_etc2_eac, 512, 512, 0, texturedata); specifications specification status comment webgl_compressed_texture_etcthe definition of 'webgl_compressed_texture_etc' in that specifi...
WEBGL_compressed_texture_etc1 - Web APIs
examples var ext = gl.getextension('webgl_compressed_texture_etc1'); var texture = gl.createtexture(); gl.bindtexture(gl.texture_2d, texture); gl.compressedteximage2d(gl.texture_2d, 0, ext.compressed_rgb_etc1_webgl, 512, 512, 0, texturedata); specifications specification status comment webgl_compressed_texture_etc1the definition of 'webgl_compressed_texture_etc1' in that spec...
WEBGL_compressed_texture_pvrtc - Web APIs
examples var ext = gl.getextension('webgl_compressed_texture_pvrtc'); var texture = gl.createtexture(); gl.bindtexture(gl.texture_2d, texture); gl.compressedteximage2d(gl.texture_2d, 0, ext.compressed_rgb_pvrtc_4bppv1_img, 512, 512, 0, texturedata); specifications specification status comment webgl_compressed_texture_pvrtcthe definition of 'webgl_compressed_texture_pvrtc' in ...
WEBGL_compressed_texture_s3tc - Web APIs
examples var ext = ( gl.getextension('webgl_compressed_texture_s3tc') || gl.getextension('moz_webgl_compressed_texture_s3tc') || gl.getextension('webkit_webgl_compressed_texture_s3tc') ); var texture = gl.createtexture(); gl.bindtexture(gl.texture_2d, texture); gl.compressedteximage2d(gl.texture_2d, 0, ext.compressed_rgba_s3tc_dxt5_ext, 512, 512, 0, texturedata); gl.texparameteri(gl.texture_2d, ...
WEBGL_compressed_texture_s3tc_srgb - Web APIs
examples var ext = gl.getextension('webgl_compressed_texture_s3tc_srgb'); var texture = gl.createtexture(); gl.bindtexture(gl.texture_2d, texture); gl.compressedteximage2d(gl.texture_2d, 0, ext.compressed_srgb_s3tc_dxt1_ext, 512, 512, 0, texturedata); gl.texparameteri(gl.texture_2d, gl.texture_mag_filter, gl.linear); gl.texparameteri(gl.texture_2d, gl.texture_min_filter, gl.linear); specifications ...
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_r...
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 = v...
WEBGL_depth_texture - Web APIs
examples var ext = gl.getextension('webgl_depth_texture'); gl.teximage2d(gl.texture_2d, 0, gl.depth_component, 512, 512, 0, gl.depth_component, gl.unsigned_short, null); specifications specification status comment webgl_depth_texturethe definition of 'webgl_depth_texture' in that specification.
WEBGL_draw_buffers - Web APIs
examples enabling the extension: var ext = gl.getextension('webgl_draw_buffers'); binding multiple textures (to a tx[] array) to different framebuffer color attachments: var fb = gl.createframebuffer(); gl.bindframebuffer(gl.framebuffer, fb); gl.framebuffertexture2d(gl.framebuffer, ext.color_attachment0_webgl, gl.texture_2d, tx[0], 0); gl.framebuffertexture2d(gl.framebuffer, ext.color_attachment1_we...
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.
WakeLock - Web APIs
examples the following asynchronous function requests a wakelocksentinel object.
WaveShaperNode - Web APIs
for applied
examples/information, check out our voice-change-o-matic demo (see app.js for relevant code).
WebGL2RenderingContext.beginTransformFeedback() - Web APIs
examples var transformfeedback = gl.createtransformfeedback(); gl.bindtransformfeedback(gl.transform_feedback, transformfeedback); gl.begintransformfeedback(gl.triangles); gl.drawarrays(gl.triangles, 0, 3); specifications specification status comment webgl 2.0the definition of 'begintransformfeedback' in that specification.
WebGL2RenderingContext.bindTransformFeedback() - Web APIs
examples var transformfeedback = gl.createtransformfeedback(); gl.bindtransformfeedback(gl.transform_feedback, transformfeedback); specifications specification status comment webgl 2.0the definition of 'bindtransformfeedback' in that specification.
WebGL2RenderingContext.blitFramebuffer() - Web APIs
examples gl.blitframebuffer(0, 0, canvas.width, canvas.height, 0, 0, canvas.width, canvas.height, gl.color_buffer_bit, gl.nearest); specifications specification status comment webgl 2.0the definition of 'blitframebuffer' in that specification.
WebGL2RenderingContext.clearBuffer[fiuv]() - Web APIs
examples gl.clearbufferiv(gl.color, 0, new int32array([r, g, b, a])); gl.clearbufferuiv(gl.color, 0, new uint32array([r, g, b, a])); gl.clearbufferfv(gl.color, 0, new float32array([r, g, b, a])); gl.clearbufferfv(gl.color, 0, [0.0, 0.0, 0.0, 0.0]); gl.clearbufferfi(gl.depth_stencil, 0, 1.0, 0); specifications specification status comment webgl 2.0the definition of 'clearbuffer[...
WebGL2RenderingContext.clientWaitSync() - Web APIs
examples var sync = gl.fencesync(gl.sync_gpu_commands_complete, 0); var status = gl.clientwaitsync(sync, 0, 0); specifications specification status comment webgl 2.0the definition of 'clientwaitsync' in that specification.
WebGL2RenderingContext.endTransformFeedback() - Web APIs
examples var transformfeedback = gl.createtransformfeedback(); gl.bindtransformfeedback(gl.transform_feedback, transformfeedback); gl.begintransformfeedback(gl.triangles); gl.drawarrays(gl.triangles, 0, 3); gl.endtransformfeedback(); specifications specification status comment webgl 2.0the definition of 'endtransformfeedback' in that specification.
WebGL2RenderingContext.getActiveUniforms() - Web APIs
examples var uniformindices = gl.getuniformindices(program, ['ubored', 'ubogreen', 'uboblue']); var uniformoffsets = gl.getactiveuniforms(program, uniformindices, gl.uniform_offset); specifications specification status comment webgl 2.0the definition of 'getactiveuniforms' in that specification.
WebGL2RenderingContext.getBufferSubData() - Web APIs
examples var buffer = gl.createbuffer(); gl.bindbuffer(gl.array_buffer, buffer); gl.bufferdata(gl.array_buffer, new float32array(vertices), gl.static_draw); var arrbuffer = new arraybuffer(vertices.length * float32array.bytes_per_element); gl.getbuffersubdata(gl.array_buffer, 0, arrbuffer); specifications specification status comment webgl 2.0the definition of 'getbuffersubdat...
WebGL2RenderingContext.getQuery() - Web APIs
examples var currentquery = gl.getquery(gl.any_samples_passed, gl.current_query); specifications specification status comment webgl 2.0the definition of 'getquery' in that specification.
WebGL2RenderingContext.getQueryParameter() - Web APIs
examples var query = gl.createquery(); gl.beginquery(gl.any_samples_passed, query); var result = gl.getqueryparameter(query, gl.query_result); specifications specification status comment webgl 2.0the definition of 'getqueryparameter' in that specification.
WebGL2RenderingContext.texSubImage3D() - Web APIs
examples gl.texsubimage3d(gl.texture_3d, 0, 0, 0, 0, image.width, image.height, 1, gl.rgba, gl.unsigned_byte, image); specifications specification status comment webgl 2.0the definition of 'texsubimage3d' in that specification.
WebGL2RenderingContext.transformFeedbackVaryings() - Web APIs
examples var transformfeedback = gl.createtransformfeedback(); gl.bindtransformfeedback(gl.transform_feedback, transformfeedback); var transformfeedbackoutputs = ['gl_position', 'anotheroutput']; gl.transformfeedbackvaryings(shaderprog, transformfeedbackoutputs, gl.interleaved_attribs); gl.linkprogram(shaderprog); specifications specification status comment...
WebGL2RenderingContext.waitSync() - Web APIs
examples var sync = gl.fencesync(gl.sync_gpu_commands_complete, 0); gl.waitsync(sync, 0, gl.timeout_ignored); specifications specification status comment webgl 2.0the definition of 'waitsync' in that specification.
WebGLActiveInfo.name - Web APIs
examples var activeattrib = gl.getactiveattrib(program, index); activeattrib.name; var activeuniform = gl.getactiveuniform(program, index); activeuniform.name; specifications specification status comment webgl 1.0the definition of 'webglactiveinfo.name' in that specification.
WebGLActiveInfo.size - Web APIs
examples var activeattrib = gl.getactiveattrib(program, index); activeattrib.size; var activeuniform = gl.getactiveuniform(program, index); activeuniform.size; specifications specification status comment webgl 1.0the definition of 'webglactiveinfo.size' in that specification.
WebGLActiveInfo.type - Web APIs
examples var activeattrib = gl.getactiveattrib(program, index); activeattrib.type; var activeuniform = gl.getactiveuniform(program, index); activeuniform.type; specifications specification status comment webgl 1.0the definition of 'webglactiveinfo.type' in that specification.
WebGLActiveInfo - Web APIs
examples a webglactiveinfo object is returned by: webglrenderingcontext.getactiveattrib() webglrenderingcontext.getactiveuniform() or webgl2renderingcontext.gettransformfeedbackvarying() webglactiveinfo?
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 - 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 "webglcont...
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.
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.
WebGLQuery - Web APIs
when working with webglquery objects, the following methods of the webgl2renderingcontext are useful: webgl2renderingcontext.createquery() webgl2renderingcontext.deletequery() webgl2renderingcontext.isquery() webgl2renderingcontext.beginquery() webgl2renderingcontext.endquery() webgl2renderingcontext.getquery() webgl2renderingcontext.getqueryparameter()
examples creating a webglquery object in this example, gl must be a webgl2renderingcontext.
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.blendEquation() - Web APIs
examples to set the blend equation, use: gl.blendequation(gl.func_add); gl.blendequation(gl.func_subtract); gl.blendequation(gl.func_reverse_subtract); to get the blend equations, query the blend_equation, blend_equation_rgb and blend_equation_alpha constants which return gl.func_add, gl.func_subtract, gl.func_reverse_subtract, or if the ext_blend_minmax is enabled: ext.min_ext or ext.max_ext.
WebGLRenderingContext.blendEquationSeparate() - Web APIs
examples to set the blend equations, use: gl.blendequationseparate(gl.func_add, gl.func_subtract); to get the current blend equations, query the blend_equation, blend_equation_rgb and blend_equation_alpha constants which return gl.func_add, gl.func_subtract, gl.func_reverse_subtract, or if the ext_blend_minmax is enabled: ext.min_ext or ext.max_ext.
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 tha...
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.commit() - Web APIs
syntax void webglrenderingcontext.commit()
examples var htmlcanvas = document.createelement('canvas'); var offscreen = htmlcanvas.transfercontroltooffscreen(); var gl = offscreen.getcontext('webgl'); // ...
WebGLRenderingContext.compileShader() - Web APIs
examples var shader = gl.createshader(gl.vertex_shader); gl.shadersource(shader, shadersource); gl.compileshader(shader); specifications specification status comment webgl 1.0the definition of 'compileshader' in that specification.
WebGLRenderingContext.compressedTexImage[23]D() - Web APIs
examples var ext = ( gl.getextension('webgl_compressed_texture_s3tc') || gl.getextension('moz_webgl_compressed_texture_s3tc') || gl.getextension('webkit_webgl_compressed_texture_s3tc') ); var texture = gl.createtexture(); gl.bindtexture(gl.texture_2d, texture); gl.compressedteximage2d(gl.texture_2d, 0, ext.compressed_rgba_s3tc_dxt5_ext, 512, 512, 0, texturedata); gl.texparameteri(gl.texture_2d, gl...
WebGLRenderingContext.compressedTexSubImage2D() - Web APIs
examples var ext = ( gl.getextension('webgl_compressed_texture_s3tc') || gl.getextension('moz_webgl_compressed_texture_s3tc') || gl.getextension('webkit_webgl_compressed_texture_s3tc') ); gl.compressedtexsubimage2d(gl.texture_2d, 0, 256, 256, 512, 512, ext.compressed_rgba_s3tc_dxt5_ext, texturedata); specifications specification status comment webgl 1.0the definition of '...
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.createProgram() - Web APIs
examples creating a webgl program var program = gl.createprogram(); // attach pre-existing shaders gl.attachshader(program, vertexshader); gl.attachshader(program, fragmentshader); gl.linkprogram(program); if ( !gl.getprogramparameter( program, gl.link_status) ) { var info = gl.getprograminfolog(program); throw 'could not compile webgl program.
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.depthRange() - Web APIs
examples gl.depthrange(0.2, 0.6); to check the current depth range, query the depth_range constant which returns a float32array gl.getparameter(gl.depth_range); // float32array[0.2, 0.6] specifications specification status comment webgl 1.0the definition of 'depthrange' in that specification.
WebGLRenderingContext.disable() - Web APIs
examples gl.disable(gl.dither); to check if a capability is disabled, use the webglrenderingcontext.isenabled() method: gl.isenabled(gl.dither); // false specifications specification status comment webgl 1.0the definition of 'disable' in that specification.
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
examples gl.enable(gl.dither); to check if a capability is enabled, use the webglrenderingcontext.isenabled() method: gl.isenabled(gl.dither); // true specifications specification status comment webgl 1.0the definition of 'enable' in that specification.
WebGLRenderingContext.getActiveAttrib() - Web APIs
examples const numattribs = gl.getprogramparameter(program, gl.active_attributes); for (let i = 0; i < numattribs; ++i) { const info = gl.getactiveattrib(program, i); console.log('name:', info.name, 'type:', info.type, 'size:', info.size); } specifications specification status comment webgl 1.0the definition of 'getactiveattrib' in that specification.
WebGLRenderingContext.getActiveUniform() - Web APIs
examples const numuniforms = gl.getprogramparameter(program, gl.active_uniforms); for (let i = 0; i < numuniforms; ++i) { const info = gl.getactiveuniform(program, i); console.log('name:', info.name, 'type:', info.type, 'size:', info.size); } specifications specification status comment webgl 1.0the definition of 'getactiveuniform' in that specification.
WebGLRenderingContext.getAttachedShaders() - Web APIs
examples var program = gl.createprogram(); // attach pre-existing shaders gl.attachshader(program, vertexshader); gl.attachshader(program, fragmentshader); gl.linkprogram(program); gl.getattachedshaders(program); specifications specification status comment webgl 1.0the definition of 'getattachedshaders' in that specification.
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", premultipl...
WebGLRenderingContext.getError() - Web APIs
examples gl.geterror(); // gl.no_error (0) gl.enable(gl.foobar); gl.geterror(); // gl.invalid_enum; specifications specification status comment webgl 1.0the definition of 'geterror' in that specification.
WebGLRenderingContext.getParameter() - Web APIs
examples gl.getparameter(gl.dither); gl.getparameter(gl.version); gl.getparameter(gl.viewport); specifications specification status comment webgl 1.0the definition of 'getparameter' in that specification.
WebGLRenderingContext.getProgramInfoLog() - Web APIs
examples checking program errors var program = gl.createprogram(); // attach pre-existing shaders gl.attachshader(program, vertexshader); gl.attachshader(program, fragmentshader); gl.linkprogram(program); gl.getprograminfolog(program); specifications specification status comment webgl 1.0the definition of 'getprograminfolog' in that specification.
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.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.linkProgram() - Web APIs
examples var program = gl.createprogram(); // attach pre-existing shaders gl.attachshader(program, vertexshader); gl.attachshader(program, fragmentshader); gl.linkprogram(program); if ( !gl.getprogramparameter( program, gl.link_status) ) { var info = gl.getprograminfolog(program); throw new error('could not compile webgl program.
WebGLRenderingContext.makeXRCompatible() - Web APIs
examples this example demonstrates code logic you might find in a game that starts up using webgl to display menus and other ui, and uses webgl to render gameplay, but has a button on its main menu that offers an option to start the game in webxr mode.
WebGLRenderingContext.pixelStorei() - Web APIs
xel is read from memory glint 0 0 to infinity opengl es 3.0 gl.unpack_skip_rows number of rows of pixel locations skipped before the first pixel is read from memory glint 0 0 to infinity opengl es 3.0 gl.unpack_skip_images number of pixel images skipped before the first pixel is read from memory glint 0 0 to infinity opengl es 3.0
examples setting the pixel storage mode affects the webglrenderingcontext.readpixels() operations, as well as unpacking of textures with the webglrenderingcontext.teximage2d() and webglrenderingcontext.texsubimage2d() methods.
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...
WebGLRenderingContext.shaderSource() - Web APIs
examples var shader = gl.createshader(gl.vertex_shader); gl.shadersource(shader, originalsource); var source = gl.getshadersource(shader); specifications specification status comment webgl 1.0the definition of 'shadersource' in that specification.
WebGLRenderingContext.texImage2D() - Web APIs
examples gl.teximage2d(gl.texture_2d, 0, gl.rgba, gl.rgba, gl.unsigned_byte, image); specifications specification status comment webgl 1.0the definition of 'teximage2d' in that specification.
WebGLRenderingContext.texParameter[fi]() - Web APIs
examples gl.texparameterf(gl.texture_2d, gl.texture_mag_filter, gl.linear); gl.texparameteri(gl.texture_2d, gl.texture_min_filter, gl.linear_mipmap_nearest); specifications specification status comment webgl 1.0the definition of 'texparameter[fi]' in that specification.
WebGLRenderingContext.texSubImage2D() - Web APIs
examples gl.texsubimage2d(gl.texture_2d, 0, 0, 0, gl.rgba, gl.unsigned_byte, image); specifications specification status comment webgl 1.0the definition of 'texsubimage2d' in that specification.
WebGLRenderingContext.useProgram() - Web APIs
examples var program = gl.createprogram(); // attach pre-existing shaders gl.attachshader(program, vertexshader); gl.attachshader(program, fragmentshader); gl.linkprogram(program); gl.useprogram(program); specifications specification status comment webgl 1.0the definition of 'useprogram' in that specification.
WebGLRenderingContext.validateProgram() - Web APIs
examples var program = gl.createprogram(); // attach pre-existing shaders gl.attachshader(program, vertexshader); gl.attachshader(program, fragmentshader); gl.linkprogram(program); gl.validateprogram(program); if ( !gl.getprogramparameter( program, gl.link_status) ) { var info = gl.getprograminfolog(program); throw 'could not compile webgl program.
WebGLRenderingContext.vertexAttrib[1234]f[v]() - Web APIs
examples const a_foobar = gl.getattriblocation(shaderprogram, 'foobar'); //either set each component individually: gl.vertexattrib3f(a_foobar, 10.0, 5.0, 2.0); //or provide a float32array: const floatarray = new float32array([10.0, 5.0, 2.0]); gl.vertexattrib3fv(a_foobar, floatarray); // we want to load the following 3x3 matrix into attribute named "matrix3x3" // 0 1 2 // 3 4 5 // 6 7 8 const matrix3x...
WebGLSampler - Web APIs
when working with webglsampler objects, the following methods of the webgl2renderingcontext are useful: webgl2renderingcontext.createsampler() webgl2renderingcontext.deletesampler() webgl2renderingcontext.issampler() webgl2renderingcontext.bindsampler() webgl2renderingcontext.getsamplerparameter()
examples creating a webglsampler object in this example, gl must be a webgl2renderingcontext.
WebGLShader - Web APIs
examples creating a vertex shader note that there are many other strategies for writing and accessing shader source code strings.
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.
WebGLSync - Web APIs
when working with webglsync objects, the following methods of the webgl2renderingcontext are useful: webgl2renderingcontext.fencesync() webgl2renderingcontext.deletesync() webgl2renderingcontext.issync() webgl2renderingcontext.clientwaitsync() webgl2renderingcontext.waitsync() webgl2renderingcontext.getsyncparameter()
examples creating a webglsync object in this example, gl must be a webgl2renderingcontext.
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.
WebGLTransformFeedback - Web APIs
() webgl2renderingcontext.istransformfeedback() webgl2renderingcontext.bindtransformfeedback() webgl2renderingcontext.begintransformfeedback() webgl2renderingcontext.endtransformfeedback() webgl2renderingcontext.pausetransformfeedback() webgl2renderingcontext.resumetransformfeedback() webgl2renderingcontext.transformfeedbackvaryings() webgl2renderingcontext.gettransformfeedbackvarying()
examples creating a webgltransformfeedback object in this example, gl must be a webgl2renderingcontext.
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.
Compressed texture formats - Web APIs
no
examples async function getcompressedtextureifavailable(gl) { const texture = gl.createtexture(); gl.bindtexture(gl.texture_2d, texture); // create texture object on gpu const ext = gl.getextension('webgl_compressed_texture_s3tc'); // will be null if not supported if (ext) { // the file is already in the correct compressed format const dataarraybuffer = await fetch('/textures/foobar512x51...
WebGL constants - Web APIs
var debuginfo = gl.getextension('webgl_debug_renderer_info'); var vendor = gl.getparameter(debuginfo.unmasked_vendor_webgl); the webgl tutorial has more information,
examples, and resources on how to get started with webgl.
WebGL tutorial - Web APIs
the
examples provided should give you some clear ideas what you can do with webgl and will provide code snippets that may get you started in building your own content.
WebGL best practices - Web APIs
shaders, programs, and glsl avoid "#ifdef gl_es", which is always true you should never use #ifdef gl_es in your webgl shaders; although some early
examples used this, it's not necessary, since this condition is always true in webgl shaders.
WebSocket: error event - Web APIs
bubbles no cancelable no interface event event handler property onerror
examples // create websocket connection const socket = new websocket('ws://localhost:8080'); // listen for possible errors socket.addeventlistener('error', function (event) { console.log('websocket error: ', event); }); specifications specification status html living standardthe definition of 'websocket error' in that specification.
Using bounded reference spaces - Web APIs
xrsession.requestanimationframe(ondrawframe); } if you compare this code to the code used in
examples using unbounded reference spaces, you'll confirm that, indeed, the biggest difference is the reference space type bounded-floor.
Inputs and input sources - Web APIs
there are a number of
examples showing how to handle select events throughout the documentation, such as in the section on targeting and the targeting ray elsewhere in this article.
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.
Migrating from webkitAudioContext - Web APIs
this article attempts to summarize the areas where developers are likely to encounter these problems and provide
examples on how to port such code to standards based audiocontext, which will work across different browser engines.
Web Authentication API - Web APIs
examples for security reasons, web authentication calls (create() and get()) are cancelled if the browser window loses focus while the call is pending.
Web Speech API - Web APIs
examples the web speech api repo on github contains demos to illustrate speech recognition and synthesis.
Web Storage API - Web APIs
examples to illustrate some typical web storage usage, we have created a simple example, imaginatively called web storage demo.
Web Workers API - Web APIs
workernavigator represents the identity and state of the user agent (the client):
examples we have created a couple of simple demos to show basic usage: basic dedicated worker example (run dedicated worker).
Window: DOMContentLoaded event - Web APIs
examples basic usage window.addeventlistener('domcontentloaded', (event) => { console.log('dom fully loaded and parsed'); }); specifications specification status html living standard living standard ...
Window: afterprint event - Web APIs
bubbles no cancelable no interface event event handler property onafterprint
examples using addeventlistener(): window.addeventlistener('afterprint', (event) => { console.log('after print'); }); using the onafterprint event handler property: window.onafterprint = (event) => { console.log('after print'); }; specifications specification status html living standard living standard ...
Window: animationend event - Web APIs
examples this example listens for the animationend event: window.addeventlistener('animationend', () => { console.log('animation ended'); }); the same, but using the onanimationend event handler property: window.onanimationend = () => { console.log('animation ended'); }; see a live example of this event.
Window: animationiteration event - Web APIs
examples this code uses animationiteration to keep track of the number of iterations an animation has completed: let iterationcount = 0; window.addeventlistener('animationiteration', () => { iterationcount++; console.log(`animation iteration count: ${iterationcount}`); }); the same, but using the onanimationiteration event handler property: let iterationcount = 0; window.onanimationiteration = (...
Window: animationstart event - Web APIs
examples this listens for the animationstart event and logs a message when it is fired: window.addeventlistener('animationstart', () => { console.log('animation started'); }); the same, but using onanimationstart: window.onanimationstart = () => { console.log('animation started'); }; see a live example of this event.
Window: appinstalled event - Web APIs
bubbles no cancelable no interface event event handler onappinstalled
examples you can use the appinstalled event in an addeventlistener method: window.addeventlistener('appinstalled', function() { console.log('thank you for installing our app!'); }); or use the onappinstalled event handler property: window.onappinstalled = function() { console.log('thank you for installing our app!'); }; ...
Window: beforeprint event - Web APIs
bubbles no cancelable no interface event event handler property onbeforeprint
examples using addeventlistener(): window.addeventlistener('beforeprint', (event) => { console.log('before print'); }); using the onbeforeprint event handler property: window.onbeforeprint = (event) => { console.log('before print'); }; specifications specification status html living standard living standard ...
Window: blur event - Web APIs
bubbles no cancelable no interface focusevent event handler property onblur sync / async sync composed yes
examples live example this example changes the appearance of a document when it loses focus.
window.cancelAnimationFrame() - Web APIs
examples var requestanimationframe = window.requestanimationframe || window.mozrequestanimationframe || window.webkitrequestanimationframe || window.msrequestanimationframe; var cancelanimationframe = window.cancelanimationframe || window.mozcancelanimationframe; var start = window.mozanimationstarttime; // only supported in ff.
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: clipboardchange event - Web APIs
bubbles no cancelable no interface clipboardevent event handler property none
examples javascript window.addeventlistener('clipboardchange', () => { console.log('clipboard contents changed'); }); specifications specification status clipboard api and eventsthe definition of 'clipboardchange event' in that specification.
Window.close() - Web APIs
syntax window.close();
examples closing a window opened with window.open() this example shows a method which opens a window and a second one which closes the window; this demonstrates how to use window.close() to close a window opened by calling window.open().
Window.closed - Web APIs
examples change the url of a window from a popup the following example demonstrates how a popup window can change the url of the window that opened it.
Window: copy event - Web APIs
examples window.addeventlistener('copy', (event) => { console.log('copy action initiated') }); specifications specification status clipboard api and events working draft ...
Window: cut event - Web APIs
examples window.addeventlistener('cut', (event) => { console.log('cut action initiated') }); specifications specification status clipboard api and events working draft ...
Window: devicemotion event - Web APIs
bubbles no cancelable no interface devicemotionevent event handler property window.ondevicemotion
examples function handlemotionevent(event) { var x = event.accelerationincludinggravity.x; var y = event.accelerationincludinggravity.y; var z = event.accelerationincludinggravity.z; // do something awesome.
Window: deviceorientation event - Web APIs
bubbles no cancelable no interface deviceorientationevent event handler property window.ondeviceorientation
examples if (window.deviceorientationevent) { window.addeventlistener("deviceorientation", function(event) { // alpha: rotation around z-axis var rotatedegrees = event.alpha; // gamma: left to right var lefttoright = event.gamma; // beta: front back motion var fronttoback = event.beta; handleorientationevent(fronttoback, lefttoright, rotatedegr...
Window: error event - Web APIs
examples live example html <div class="controls"> <button id="script-error" type="button">generate script error</button> <img class="bad-img" /> </div> <div class="event-log"> <label>event log:</label> <textarea readonly class="event-log-contents" rows="8" cols="30"></textarea> </div> css body { display: grid; grid-template-areas: "control log"; } .controls { grid-area: control; d...
Window: focus event - Web APIs
bubbles no cancelable no interface focusevent event handler property onfocus sync / async sync composed yes
examples live example this example changes the appearance of a document when it loses focus.
Window: gamepadconnected event - Web APIs
bubbles no cancelable no interface gamepadevent event handler property ongamepadconnected
examples window.addeventlistener('gamepadconnected', event => { // all buttons and axes values can be accessed through event.gamepad; }); specifications specification status gamepad working draft ...
Window: gamepaddisconnected event - Web APIs
bubbles no cancelable no interface gamepadevent event handler property ongamepaddisconnected
examples window.addeventlistener('gamepaddisconnected', event => { console.log('lost connection with the gamepad.'); }); specifications specification status gamepad working draft ...
Window.getDefaultComputedStyle() - Web APIs
see http://blog.mozilla.com/security/2010/03/31/plugging-the-css-history-leak/ and http://hacks.mozilla.org/2010/03/privacy-related-changes-coming-to-css-vistited/ for details of the
examples of how this is implemented.
Window.getSelection() - Web APIs
examples function foo() { var selobj = window.getselection(); alert(selobj); var selrange = selobj.getrangeat(0); // do stuff with the range } notes string representation of the selection object in javascript, when an object is passed to a function expecting a string (like window.alert() or document.write()), the object's tostring() method is called and the returned value is passed to ...
Window: hashchange event - Web APIs
bubbles yes cancelable no interface hashchangeevent event handler onhashchange
examples you can use the hashchange event in an addeventlistener method: window.addeventlistener('hashchange', function() { console.log('the hash has changed!') }, false); or use the onhashchange event handler property: function locationhashchanged() { if (location.hash === '#cool-feature') { console.log("you're visiting a cool feature!"); } } window.onhashchange = locationhashchanged; specifications specification status comment html living standardthe definition of 'hashchan...
Window.isSecureContext - Web APIs
syntax var issecure = window.issecurecontext
examples feature detection you can use feature detection to check whether they are in a secure context or not by using the issecurecontext boolean which is exposed on the global scope.
Window: languagechange event - Web APIs
bubbles no cancelable no interface event event handler onlanguagechange
examples you can use the languagechange event in an addeventlistener method: window.addeventlistener('languagechange', function() { console.log('languagechange event detected!'); }); or use the onlanguagechange event handler property: window.onlanguagechange = function(event) { console.log('languagechange event detected!'); }; specification specification status html living standardthe definition of 'languagechange' in that specification.
Window: load event - Web APIs
bubbles no cancelable no interface event event handler property onload
examples log a message when the page is fully loaded: window.addeventlistener('load', (event) => { console.log('page is fully loaded'); }); the same, but using the onload event handler property: window.onload = (event) => { console.log('page is fully loaded'); }; live example html <div class="controls"> <button id="reload" type="button">reload</button> </div> <div class="event-log"> <label>ev...
window.location - Web APIs
syntax var oldlocation = location; location = newlocation;
examples basic example alert(location); // alerts "/docs/web/api/window/location" example #1: navigate to a new page whenever a new value is assigned to the location object, a document will be loaded using the url as if location.assign() had been called with the modified url.
Window: message event - Web APIs
bubbles no cancelable no interface messageevent event handler property onmessage
examples suppose a script sends a message to a different browsing context, such as another <iframe>, using code like this: const targetframe = window.top.frames[1]; const targetorigin = 'https://example.org'; const windowmessagebutton = document.queryselector('#window-message'); windowmessagebutton.addeventlistener('click', () => { targetframe.postmessage('hello there', targetorigin); }); the receiver can listen for the message using addeventlistener() with code like this: window.addeventlistene...
Window: messageerror event - Web APIs
bubbles no cancelable no interface messageevent event handler property onmessageerror
examples listen for messageerror using addeventlistener(): window.addeventlistener('messageerror', (event) => { console.error(event); }); the same, but using the onmessageerror event handler property: window.onmessageerror = (event) => { console.error(event); }; specifications specification status html living standard living standard ...
Window.navigator - Web APIs
syntax navigatorobject = window.navigator
examples example #1: browser detect and return a string var sbrowser, susrag = navigator.useragent; // the order matters here, and this may report false positives for unlisted browsers.
Window: offline event - Web APIs
bubbles no cancelable no interface event event handler property onoffline
examples // addeventlistener version window.addeventlistener('offline', (event) => { console.log("the network connection has been lost."); }); // onoffline version window.onoffline = (event) => { console.log("the network connection has been lost."); }; specifications specification status html living standardthe definition of 'offline event' in that specification.
Window.ongamepadconnected - Web APIs
};
examples window.ongamepadconnected = function(event) { // all buttons and axes values can be accessed through event.gamepad; }; specifications specification status comment gamepadthe definition of 'gamepadconnected event' in that specification.
Window.ongamepaddisconnected - Web APIs
};
examples window.ongamepaddisconnected = function() { // a gamepad has been disconnected }; specifications specification status comment gamepadthe definition of 'gamepaddisconnected event' in that specification.
Window: online event - Web APIs
bubbles no cancelable no interface event event handler property ononline
examples // addeventlistener version window.addeventlistener('online', (event) => { console.log("you are now connected to the network."); }); // ononline version window.ononline = (event) => { console.log("you are now connected to the network."); }; specifications specification status html living standardthe definition of 'online event' in that specification.
Window.open() - Web APIs
examples var windowobjectreference; var windowfeatures = "menubar=yes,location=yes,resizable=yes,scrollbars=yes,status=yes"; function openrequestedpopup() { windowobjectreference = window.open("http://www.cnn.com/", "cnn_windowname", windowfeatures); } var windowobjectreference; function openrequestedpopup() { windowobjectreference = window.open( "http://www.domainname.ext/path/imagefile.png",...
Window: pagehide event - Web APIs
bubbles no cancelable no interface pagetransitionevent event handler property onpagehide
examples in this example, an event handler is established to watch for pagehide events and to perform special handling if the page is being persisted for possible reuse.
Window: pageshow event - Web APIs
bubbles no cancelable no interface pagetransitionevent event handler property onpageshow
examples this example sets up event handlers for events listed in the array events.
Window: paste event - Web APIs
examples window.addeventlistener('paste', (event) => { console.log('paste action initiated') }); specifications specification status clipboard api and events working draft ...
Window: popstate event - Web APIs
examples a page at http://example.com/example.html running the following code will generate logs as indicated: window.addeventlistener('popstate', (event) => { console.log("location: " + document.location + ", state: " + json.stringify(event.state)); }); history.pushstate({page: 1}, "title 1", "?page=1"); history.pushstate({page: 2}, "title 2", "?page=2"); history.replacestate({page: 3}, "title 3", "?
window.postMessage() - Web APIs
examples of typical origins are https://example.org (implying port 443), http://example.net (implying port 80), and http://example.com:8080.
Window.screenX - Web APIs
examples in our screenleft-screentop (source code) example, you'll see a canvas onto which has been drawn a circle.
Window.screenY - Web APIs
examples in our screenleft-screentop example, you'll see a canvas onto which has been drawn a circle.
Window.scroll() - Web APIs
examples <!-- put the 100th vertical pixel at the top of the window --> <button onclick="scroll(0, 100);">click to scroll down 100 pixels</button> using options: window.scroll({ top: 100, left: 100, behavior: 'smooth' }); notes window.scrollto() is effectively the same as this method.
Window.scrollBy() - Web APIs
examples to scroll down one page: window.scrollby(0, window.innerheight); to scroll up: window.scrollby(0, -window.innerheight); using options: window.scrollby({ top: 100, left: 100, behavior: 'smooth' }); notes window.scrollby() scrolls by a particular amount, whereas window.scroll() scrolls to an absolute position in the document.
Window.scrollTo() - Web APIs
examples window.scrollto(0, 1000); using options: window.scrollto({ top: 100, left: 100, behavior: 'smooth' }); notes window.scroll() is effectively the same as this method.
Window.speechSynthesis - Web APIs
examples in our basic speech synthesiser demo, we first grab a reference to the speechsynthesis controller using window.speechsynthesis.
Window: storage event - Web APIs
bubbles no cancelable no interface storageevent event handler property onstorage
examples log the samplelist item to the console when the storage event fires: window.addeventlistener('storage', () => { // when local storage changes, dump the list to // the console.
Window: transitioncancel event - Web APIs
examples this code adds a listener to the transitioncancel event: window.addeventlistener('transitioncancel', () => { console.log('transition canceled'); }); the same, but using the ontransitioncancel property instead of addeventlistener(): window.ontransitioncancel = () => { console.log('transition canceled'); }; see a live example of this event.
Window: transitionend event - Web APIs
examples this code adds a listener to the transitionend event: window.addeventlistener('transitionend', () => { console.log('transition ended'); }); the same, but using the ontransitionend property instead of addeventlistener(): window.ontransitionend = () => { console.log('transition ended'); }; see a live example of this event.
Window: transitionrun event - Web APIs
examples this code adds a listener to the transitionrun event: window.addeventlistener('transitionrun', () => { console.log('transition is running but hasn't necessarily started transitioning yet'); }); the same, but using the ontransitionrun property instead of addeventlistener(): window.ontransitionrun = () => { console.log('transition started running'); }; see a live example of this event.
Window: transitionstart event - Web APIs
examples this code adds a listener to the transitionstart event: window.addeventlistener('transitionstart', () => { console.log('started transitioning'); }); the same, but using the ontransitionstart property instead of addeventlistener(): window.ontransitionrun = () => { console.log('started transitioning'); }; see a live example of this event.
Window: unload event - Web APIs
examples <!doctype html> <html> <head> <title>parent frame</title> <script> window.addeventlistener('beforeunload', function(event) { console.log('i am the 1st one.'); }); window.addeventlistener('unload', function(event) { console.log('i am the 3rd one.'); }); </script> </head> <body> <iframe src="child-frame.html"></iframe> </body> </html>...
Window - Web APIs
see also using navigation timing for additional information and
examples.
WindowEventHandlers.onpopstate - Web APIs
examples for example, a page at http://example.com/example.html running the following code will generate alerts as indicated: window.onpopstate = function(event) { alert("location: " + document.location + ", state: " + json.stringify(event.state)); }; history.pushstate({page: 1}, "title 1", "?page=1"); history.pushstate({page: 2}, "title 2", "?page=2"); history.replacestate({page: 3}, "title 3", "?pa...
WindowOrWorkerGlobalScope.crossOriginIsolated - Web APIs
syntax var mycrossoriginisolated = self.crossoriginisolated; // or just crossoriginisolated value a boolean value
examples if(crossoriginisolated) { // post sharedarraybuffer } else { // do something else } specifications specification status comment html living standardthe definition of 'crossoriginisolated' in that specification.
WindowOrWorkerGlobalScope.origin - Web APIs
examples executed from inside a worker script, the following snippet will log the worker's global scope's origin to the console each time it receives a message onmessage = function() { console.log(self.origin); }; if the origin is not a scheme/host/port tuple (say you are trying to run it locally, i.e.
WindowOrWorkerGlobalScope.queueMicrotask() - Web APIs
examples self.queuemicrotask(() => { // function contents here }) taken from the queuemicrotask spec: myelement.prototype.loaddata = function (url) { if (this._cache[url]) { queuemicrotask(() => { this._setdata(this._cache[url]); this.dispatchevent(new event("load")); }); } else { fetch(url).then(res => res.arraybuffer()).then(data => { this._cache[url] = data; ...
Worker() - Web APIs
examples the following code snippet shows creation of a worker object using the worker() constructor and subsequent usage of the object: var myworker = new worker('worker.js'); first.onchange = function() { myworker.postmessage([first.value,second.value]); console.log('message posted to worker'); } for a full example, see our basic dedicated worker example (run dedicated worker).
Worker: message event - Web APIs
bubbles no cancelable no interface messageevent event handler property onmessage
examples this code creates a new worker and listens to messages from it using addeventlistener(): const worker = new worker("static/scripts/worker.js"); worker.addeventlistener('message', (event) => { console.log(`received message from worker: ${event.data}`) }); alternatively, it could listen using the onmessage event handler property: const worker = new worker("static/scripts/worker.js"); worker.onmessage = (event) => { console.log(`received message from wo...
Worker: messageerror event - Web APIs
bubbles no cancelable no interface messageevent event handler property onmessageerror
examples create a worker, and listen for message and messageerror events using addeventlistener(): // inside main.js const worker = new worker("static/scripts/worker.js"); worker.addeventlistener("message", (event) => { console.error(`received message from worker: ${event}`); }); worker.addeventlistener("messageerror", (event) => { console.error(`error receiving message from worker: ${event}`); }); the same, but using the onmessageerror event handler property: // inside main.js const worker = new worker("static/scripts/worker.js"); work...
WorkerGlobalScope: languagechange event - Web APIs
bubbles no cancelable no interface event event handler onlanguagechange
examples you can use the languagechange event in an addeventlistener method: worker.addeventlistener('languagechange', function() { console.log('languagechange event detected!'); }); or use the onlanguagechange event handler property: worker.onlanguagechange = function(event) { console.log('languagechange event detected!'); }; specification specification status html living standardthe definition of 'languagechange' in that specification.
WorkerNavigator.permissions - Web APIs
examples self.navigator.permissions.query({name:'notifications'}).then(function(result) { if (result.state === 'granted') { shownotification(); } else if (result.state === 'prompt') { requestnotificationpermission() } }); specification specification status comment permissions working draft initial definition.
Worklet.addModule() - Web APIs
examples audioworklet example const audioctx = new audiocontext(); const audioworklet = audioctx.audioworklet; await audioworklet.addmodule('modules/bypassfilter.js', { credentials: 'omit', }); paintworklet example css.paintworklet.addmodule('https://mdn.github.io/houdini-
examples/csspaint/intro/worklets/hilite.js'); once a paintworklet is included, the css paint() function can be used to include ...
WritableStreamDefaultController.error() - Web APIs
examples const writablestream = new writablestream({ start(controller) { // do stuff with controller // error stream if necessary controller.error('my error is broken'); }, write(chunk, controller) { ...
WritableStreamDefaultController - Web APIs
examples const writablestream = new writablestream({ start(controller) { // do stuff with controller // error stream if necessary controller.error('my stream is broken'); }, write(chunk, controller) { ...
XMLDocument.load() - Web APIs
examples var xmldoc = document.implementation.createdocument("", "test", null); function documentloaded (e) { alert(new xmlserializer().serializetostring(e.target)); // gives querydata.xml contents as string } xmldoc.addeventlistener("load", documentloaded, false); xmldoc.load('querydata.xml'); see also the load sample in the xml tests directory.
XMLHttpRequest: abort event - Web APIs
bubbles no cancelable no interface progressevent event handler property onabort
examples live example html <div class="controls"> <input class="xhr success" type="button" name="xhr" value="click to start xhr (success)" /> <input class="xhr error" type="button" name="xhr" value="click to start xhr (error)" /> <input class="xhr abort" type="button" name="xhr" value="click to start xhr (abort)" /> </div> <textarea readonly class="event-log"></textarea> css .event-log { width: 25rem; height: 4rem; border: 1px solid black; margin: .5rem; padding: .2rem; } input { width: 11rem; mar...
XMLHttpRequest: error event - Web APIs
bubbles no cancelable no interface progressevent event handler property onerror
examples live example html <div class="controls"> <input class="xhr success" type="button" name="xhr" value="click to start xhr (success)" /> <input class="xhr error" type="button" name="xhr" value="click to start xhr (error)" /> <input class="xhr abort" type="button" name="xhr" value="click to start xhr (abort)" /> </div> <textarea readonly class="event-log"></textarea> css .event-log { width: 25rem; height: 4rem; border: 1px solid black; margin: .5rem; padding: .2rem; } input { width: 11rem; margin: .5rem; } js const xhrbuttonsuccess = document.qu...
XMLHttpRequest: load event - Web APIs
bubbles no cancelable no interface progressevent event handler property onload
examples live example html <div class="controls"> <input class="xhr success" type="button" name="xhr" value="click to start xhr (success)" /> <input class="xhr error" type="button" name="xhr" value="click to start xhr (error)" /> <input class="xhr abort" type="button" name="xhr" value="click to start xhr (abort)" /> </div> <textarea readonly class="event-log"></textarea> css .event-log { width: 25rem; height: 4rem; border: 1px solid black; margin: .5rem; padding: .2rem; } input { width: 11rem; margin: .5rem; } js const xhrbuttonsuc...
XMLHttpRequest: loadend event - Web APIs
bubbles no cancelable no interface progressevent event handler property onloadend
examples live example html <div class="controls"> <input class="xhr success" type="button" name="xhr" value="click to start xhr (success)" /> <input class="xhr error" type="button" name="xhr" value="click to start xhr (error)" /> <input class="xhr abort" type="button" name="xhr" value="click to start xhr (abort)" /> </div> <textarea readonly class="event-log"></textarea> css .event-log { width: 25rem; height: 4rem; border: 1px solid black; margin: .5rem; padding: .2rem; } input { width: ...
XMLHttpRequest: loadstart event - Web APIs
bubbles no cancelable no interface progressevent event handler property onloadstart
examples live example html <div class="controls"> <input class="xhr success" type="button" name="xhr" value="click to start xhr (success)" /> <input class="xhr error" type="button" name="xhr" value="click to start xhr (error)" /> <input class="xhr abort" type="button" name="xhr" value="click to start xhr (abort)" /> </div> <textarea readonly class="event-log"></textarea> css .event-log { width: 25rem; height: 4rem; border: 1px solid black; margin: .5rem; padding: .2rem; } input { width: 11rem; margin: .5rem; } js const xhrbuttonsuccess = d...
XMLHttpRequest.onreadystatechange - Web APIs
examples const xhr = new xmlhttprequest(), method = "get", url = "https://developer.mozilla.org/"; xhr.open(method, url, true); xhr.onreadystatechange = function () { // in local files, status is 0 upon success in mozilla firefox if(xhr.readystate === xmlhttprequest.done) { var status = xhr.status; if (status === 0 || (status >= 200 && status < 400)) { // the request has been c...
XMLHttpRequest: progress event - Web APIs
bubbles no cancelable no interface progressevent event handler property onprogress
examples live example html <div class="controls"> <input class="xhr success" type="button" name="xhr" value="click to start xhr (success)" /> <input class="xhr error" type="button" name="xhr" value="click to start xhr (error)" /> <input class="xhr abort" type="button" name="xhr" value="click to start xhr (abort)" /> </div> <textarea readonly class="event-log"></textarea> css .event-log { width: 25rem; height: 4rem; border: 1px solid black; margin: .5rem; padding: .2rem; } input { width: 11rem; margin: .5rem; } js const xhrbuttonsucces...
XMLHttpRequest: timeout event - Web APIs
bubbles no cancelable no interface progressevent event handler property ontimeout
examples const client = new xmlhttprequest(); client.open('get', 'http://www.example.org/example.txt'); client.ontimeout = () => { console.error('timeout!!') }; client.send(); you could also set up the event handler using the addeventlistener() method: client.addeventlistener('timeout', () => { console.error("timeout!!"); }); specifications specification status comment xmlhttprequestthe definition of 'timeout event' in that specification.
XMLSerializer - Web APIs
examples serializing xml into a string the first, basic, example just serializes an entire document into a string containing xml.
XRFrame.getViewerPose() - Web APIs
examples in this callback function for requestanimationframe(), the xrviewerpose describing the viewer's viewpoint on the world is obtained by calling getviewerpose() on the xrframe passed into the callback.
XRHandedness - Web APIs
examples one important usage scentario for handedness is to determine which hand a controller is in so you can draw a representation of that hand (or the device that hand is controlling) in virtual space.
XRInputSource.gripSpace - Web APIs
examples in tis example, taken from the frame rendering callback, the gripspace is used to render a mesh that represents the position and orieintation of the controller in the virtual environment.
XRInputSource.handedness - Web APIs
examples one important usage scentario for handedness is to determine which hand a controller is in so you can draw a representation of that hand (or the device that hand is controlling) in virtual space.
XRInputSourceArray.length - Web APIs
examples in this example, a game that requires at least one input source uses length to check this before proceeding to allow the user to play the game.
XRInputSourceArray - Web APIs
let sources = xrsession.inputsources; if (sources.length > 0) { handleinput(sources[0]); }
examples specifications specification status comment webxr device apithe definition of 'xrinputsourcearray' in that specification.
XRInputSourceEvent() - Web APIs
examples the code below sets up handlers for primary action events in order to determine when the user clicks on (shoots at/pokes at/whatever) objects in the scene.
XRInputSourceEvent.frame - Web APIs
examples this code shows a handler for the selectstart event which gets the target ray's pose from the frame, mapping the pose representing the ray (event.inputsource.targetrayspace) to the overall reference space myrefspace.
XRReferenceSpaceEvent.transform - Web APIs
examples this example handles the reset event by walking through all the objects in a scene, updating each object's position by multiplying it with the event's given transform.
XRRigidTransform.inverse - Web APIs
examples in this example, the model view matrix for an object is computed by taking the view matrix and multiplying it by the object's pose matrix.
XRRigidTransform.matrix - Web APIs
returned by matrix: [1-2(qy2+qz2)2(qxqy-qzqw)2(qxqz+qyqw)px2(qxqy+qzqw)1-2(qx2+qz2)2(qyqz-qxqw)py2(qxqz-qyqw)2(qyqz+qxqw)1-2(qx2+qy2)pz0001]\begin{bmatrix} 1 - 2(q_y^2 + q_z^2) & 2(q_xq_y - q_zq_w) & 2(q_xq_z + q_yq_w) & p_x\\ 2(q_xq_y + q_zq_w) & 1 - 2(q_x^2 + q_z^2) & 2(q_yq_z - q_xq_w) & p_y\\ 2(q_xq_z - q_yq_w) & 2(q_yq_z + q_xq_w) & 1 - 2(q_x^2 + q_y^2) & p_z\\ 0 & 0 & 0 & 1 \end{bmatrix}
examples in this example, a transform is created to create a matrix which can be used as a transform during rendering of webgl objects, in order to place objects to match a given offset and orientation.
XRRigidTransform.orientation - Web APIs
examples to create a reference space which is oriented to look straight up, positioned 2 meters off of ground level: xrreferencespace = refspace.getoffsetreferencespace( new xrrigidtransform({y: -2}, {x: 0.0, y: 1.0, z: 0.0, w: 1.0}); ); the unit quaternion specified here is [0.0, 1.0, 0.0, 1.0] to indicate that the object should be facing directly along the y axis.
XRSession.onsqueezeend - Web APIs
examples this snippet of code adds a simple handler for the squeezeend event, which responds only to events on the user's dominant hand.
XRSession.onsqueezestart - Web APIs
examples this snippet of code adds a simple handler for the squeezestart event, which responds only to events on the user's dominant hand by getting the target ray, then calling a function findobjectusingray() to identify the object that the user is pointing at.
Using the presentation role - Accessibility
examples example 1: <ul role="tablist"> <li role="presentation"> <a role="tab" href="#">tab 1</a> </li> <li role="presentation"> <a role="tab" href="#">tab 2</a> </li> <li role="presentation"> <a role="tab" href="#">tab 3</a> </li> </ul> working
examples: notes aria attributes used related aria techniques compatibility tbd: add support information for common ua and at...
Using the toolbar role - Accessibility
examples example 1: code working
examples: w3c toolbar example notes aria attributes used related aria techniques compatibility tbd: add support information for common ua and at product combinations additional resources ...
ARIA: timer role - Accessibility
examples some prominent web timers include clocks, stop watches and countdowns, such as ticketing websites, e-commerce sites, and event countdowns (see https://countingdownto.com/).
ARIA: application role - Accessibility
examples some prominent web applications that use the application role properly are: google docs, sheets and slides ckeditor and tinymce wysiwyg web editors, like the one used on the mozilla developer network some parts of gmail accessibility concerns improperly using the application role can unintentionally take away access from information on a web page, so be very mindful of using it.
ARIA: banner role - Accessibility
associated aria roles, states, and properties none keyboard interactions none required javascript features none
examples here's a fake simple banner with a skip to navigation link, a logo, a title and a subtitle.
ARIA: cell role - Accessibility
examples <div role="table" aria-label="semantic elements" aria-describedby="semantic_elements_table_desc" aria-rowcount="81"> <div id="semantic_elements_table_desc">semantic elements to use instead of aria's roles</div> <div role="rowgroup"> <div role="row"> <span role="columnheader" aria-sort="none" aria-rowindex="1">aria role</span> <span role="columnheader" aria-sort="none" aria...
ARIA: Complementary role - Accessibility
examples <div role="complementary"> <h2>trending articles</h2> <ul> <li><a href="#">18 tweets that will make you feel all the feels</a></li> <li><a href="#">stop searching for the perfect lunch containers because i've found them</a></li> <li><a href="#">the time has come to finally decide what we should be calling these foods</a></li> <li><a href="#">17 really good posts we saw on...
ARIA: contentinfo role - Accessibility
examples <body> <!-- other page content --> <div role="contentinfo"> <h2>mdn web docs</h2> <ul> <li><a href="#">web technologies</a></li> <li><a href="#">learn web development</a></li> <li><a href="#">about mdn</a></li> <li><a href="#">feedback</a></li> </ul> <p>© 2005-2018 mozilla and individual contributors.
ARIA: figure role - Accessibility
examples we could extend the initial example on the page to also identify a paragraph that provides a descriptive label for the figure by referencing its id in aria-labelledby: <div role="figure" aria-labelledby="figure-1"> <img src="diagram.png" alt="diagram showing the four layers of awesome and their relative priority order — music, cats, nature, and ice cream"> <pre><code> ...
ARIA: form role - Accessibility
examples <div role="form" id="send-comment" aria-label="add a comment"> <label for="username">username</label> <input id="username" name="username" autocomplete="nickname" autocorrect="off" type="text"> <label for="email">email</label> <input id="email" name="email" autocomplete="email" autocapitalize="off" autocorrect="off" spellcheck="false" type="text"> <label for="comment">comment</label>...
ARIA: gridcell role - Accessibility
examples the following example creates a table-style grouping of information: <h3 id="table-title">jovian gas giant planets</h3> <div role="grid" aria-describedby="table-title"> <div role="rowgroup"> <div role="row"> <div role="columnheader">name</div> <div role="columnheader">diameter (km)</div> <div role="columnheader">length of day (hours)</div> <div role="columnheader">...
ARIA: List role - Accessibility
examples aria lists — some useful
examples and thoughts by scott o'hara best practices only use role="list" and role="listitem" if you have to — for example if you don't have control over your html but are able to improve accessibility dynamically after the fact with javascript.
ARIA: Listitem role - Accessibility
examples aria lists — some useful
examples and thoughts by scott o'hara best practices only use role="list" and role="listitem" if you have to — for example if you don't have control over your html but are able to improve accessibility dynamically after the fact with javascript.
ARIA: Navigation Role - Accessibility
examples <div role="navigation" aria-label="customer service"> <ul> <li><a href="#">help</a></li> <li><a href="#">order tracking</li> <li><a href="#">shipping & delivery</a></li> <li><a href="#">returns</a></li> <li><a href="#">contact us</a></li> <li><a href="#">find a store</a></li> </ul> </div> accessibility concerns landmark roles are intended to be used sparingly, ...
ARIA: Region role - Accessibility
examples <div role="region" aria-labelledby="region-heading"> <h2 id="region-heading">this heading's <code>id</code> attribute helps this region have an accessible name</h2> <!-- region content --> </div> accessibility concerns use sparingly!
ARIA: img role - Accessibility
an aria-label attribute keyboard interactions required javascript features
examples star rating role="img" example specifications specification status accessible rich internet applications (wai-aria) 1.1the definition of 'img' in that specification.
ARIA: row role - Accessibility
examples <div role="table" aria-label="semantic elements" aria-describedby="semantic_elements_table_desc" aria-rowcount="81"> <div id="semantic_elements_table_desc">semantic elements to use instead of aria's roles</div> <div role="rowgroup"> <div role="row"> <span role="columnheader" aria-sort="none">aria role</span> <span role="columnheader" aria-sort="none">semantic element</span...
ARIA: rowgroup role - Accessibility
examples <div role="table" aria-label="semantic elements" aria-describedby="semantic_elements_table_desc" aria-rowcount="81"> <div id="semantic_elements_table_desc">semantic elements to use instead of aria's roles</div> <div role="rowgroup"> <div role="row"> <span role="columnheader" aria-sort="none">aria role</span> <span role="columnheader" aria-sort="none">semantic element</span...
ARIA: search role - Accessibility
examples <form id="search" role="search"> <label for="search-input">search this site</label> <input type="search" id="search-input" name="search" spellcheck="false"> <input value="submit" type="submit"> </form> accessibility concerns landmark roles are intended to be used sparingly, to identify larger overall sections of the document.
ARIA: Suggestion role - Accessibility
examples when you’ve got a content change that involves an insertion and a deletion, there is no way for a screenreader user to work out if the two are related or not.
ARIA: table role - Accessibility
examples <div role="table" aria-label="semantic elements" aria-describedby="semantic_elements_table_desc" aria-rowcount="81"> <div id="semantic_elements_table_desc">semantic elements to use instead of aria's roles</div> <div role="rowgroup"> <div role="row"> <span role="columnheader" aria-sort="none">aria role</span> <span role="columnheader" aria-sort="none">semantic element</span...
ARIA: button role - Accessibility
this attribute has one of four possible values: true, false, mixed, undefined
examples basic button example in this example, a span element has been given the button role.
ARIA: checkbox role - Accessibility
checkbox by changing the value of the aria-checked attribute and the appearance of the checkbox so it appears checked or unchecked to the sighted user onkeypress handle the case where the user presses the space key to change the state of the checkbox by changing the value of the aria-checked attribute and the appearance of the checkbox so it appears checked or unchecked to the sighted user
examples the following example creates a simple checkbox element using css and javascript to handle the checked or unchecked status of the element.
ARIA: textbox role - Accessibility
examples example 1: adding the role in the html code for single line input the snippet below shows how the textbox role is added directly into the html source code.
Alerts - Accessibility
examples of common problems include e-mail addresses which are not valid, or a name field which does not contain at least a first name or a surname.
Accessibility: What users can do to browse more safely - Accessibility
examples include: transitionrun transitionstart transitionend transitioncancel edge 75 and above (desktop, in windows 10) according to eric bailey, in his april 30, 2019 article revisiting prefers-reduced-motion, the reduced motion media query, "while microsoft edge does not have support for prefers-reduced-motion, it will become chrome under the hood soon." safari 10.1 and above (desktop) do n...
An overview of accessible web applications and widgets - Accessibility
examples include (but are certainly not limited to): aria-checked: indicates the state of a checkbox or radio button aria-disabled: indicates that an element is visible, but not editable or otherwise operable aria-grabbed: indicates the 'grabbed' state of an object in a drag-and-drop operation (for a full list of aria states, consult the aria list of states and properties.) developers should use a...
Accessibility Information for Web Authors - Accessibility
effective color contrast and effective color brightness difference have a decisive importance for reading, furthermore for people with partial color deficiency (see the excellent
examples in effective color contrast by lighthouse international).
Understandable - Accessibility
providing a dedicated link to a help page or service on each page, providing
examples showing what successful completion should look like.
-moz-context-properties - CSS: Cascading Style Sheets
formal definition initial valuenoneapplies toany element that can have an image applied to it, for example as a background-image, border-image, or list-style-image.inheritedyescomputed valueas specifiedanimation typediscrete formal syntax none | [ fill | fill-opacity | stroke | stroke-opacity ]#
examples exposing fill and stroke to an svg image in this example we have a simple svg embedded using an <img> element.
-moz-float-edge - CSS: Cascading Style Sheets
formal definition initial valuecontent-boxapplies toall elementsinheritednocomputed valueas specifiedanimation typediscrete formal syntax border-box | content-box | margin-box | padding-box
examples html <div class="box"> <p>lorem ipsum dolor sit amet, consectetur adipiscing elit.</p> </div> css .box { display: block; height: 5px; margin: 0.5em auto 0.5em auto; color: gray; -moz-float-edge: margin-box; box-sizing: border-box; } result specifications not part of any standard.
-moz-force-broken-image-icon - CSS: Cascading Style Sheets
formal definition initial value0applies toimagesinheritednocomputed valueas specifiedanimation typediscrete formal syntax <integer>
examples html <img src='/broken/image/link.png' alt='broken image link'> css img { -moz-force-broken-image-icon: 1; height: 100px; width: 100px; } result screenshotlive sample note: unless the image has a specified height and width the broken image icon will not be displayed but the alt attribute will also be hidden if -moz-force-broken-image-icon is set to 1.
-moz-image-region - CSS: Cascading Style Sheets
it will not work with xul <image src="url" />.inheritedyescomputed valueas specifiedanimation typediscrete formal syntax <shape> | autowhere <shape> = rect(<top>, <right>, <bottom>, <left>)
examples clipping an image #example-button { /* display only the 4x4 area from the top left of this image */ list-style-image: url("chrome://example/skin/example.png"); -moz-image-region: rect(0px, 4px, 4px, 0px); } #example-button:hover { /* use the 4x4 area to the right of the first for the hovered button */ -moz-image-region: rect(0px, 8px, 4px, 4px); } specifications not part of any stan...
-moz-orient - CSS: Cascading Style Sheets
formal definition initial valueinlineapplies toany element; it has an effect on progress and meter, but not on <input type="range"> or other elementsinheritednocomputed valueas specifiedanimation typediscrete formal syntax inline | block | horizontal | vertical
examples html <p> the following progress meter is horizontal (the default): </p> <progress max="100" value="75"></progress> <p> the following progress meter is vertical: </p> <progress class="vert" max="100" value="75"></progress> css .vert { -moz-orient: vertical; width: 16px; height: 150px; } result specifications not part of any standard.
-moz-outline-radius-bottomleft - CSS: Cascading Style Sheets
formal definition initial value0applies toall elementsinheritednopercentagesrefer to the corresponding dimension of the border boxcomputed valueas specifiedanimation typea length, percentage or calc(); formal syntax <outline-radius>where <outline-radius> = <length> | <percentage>
examples rounding a outline since this is a firefox-only property, this example will not display the desired effect if you are viewing this in a browser other than firefox.
-moz-outline-radius-bottomright - CSS: Cascading Style Sheets
formal definition initial value0applies toall elementsinheritednopercentagesrefer to the corresponding dimension of the border boxcomputed valueas specifiedanimation typea length, percentage or calc(); formal syntax <outline-radius>where <outline-radius> = <length> | <percentage>
examples html <p>look at this paragraph's bottom-right corner.</p> css p { margin: 5px; border: solid cyan; outline: dotted red; -moz-outline-radius-bottomright: 2em; } result the example above will not display the desired effect if you are viewing this in a browser other than firefox.
-moz-outline-radius-topleft - CSS: Cascading Style Sheets
formal definition initial value0applies toall elementsinheritednopercentagesrefer to the corresponding dimension of the border boxcomputed valueas specifiedanimation typea length, percentage or calc(); formal syntax <outline-radius>where <outline-radius> = <length> | <percentage>
examples the example below will not display the desired effect if you are viewing this in a browser other than firefox.
-moz-outline-radius-topright - CSS: Cascading Style Sheets
formal definition initial value0applies toall elementsinheritednopercentagesrefer to the corresponding dimension of the border boxcomputed valueas specifiedanimation typea length, percentage or calc(); formal syntax <outline-radius>where <outline-radius> = <length> | <percentage>
examples html <p>look at this paragraph's top-right corner.</p> css p { margin: 5px; border: solid cyan; outline: dotted red; -moz-outline-radius-topright: 2em; } result the example above will not display the desired effect if you are viewing this in a browser other than firefox.
-moz-outline-radius - CSS: Cascading Style Sheets
of the properties of the shorthand:-moz-outline-radius-topleft: a length, percentage or calc();-moz-outline-radius-topright: a length, percentage or calc();-moz-outline-radius-bottomright: a length, percentage or calc();-moz-outline-radius-bottomleft: a length, percentage or calc(); formal syntax <outline-radius>{1,4} [ / <outline-radius>{1,4} ]?where <outline-radius> = <length> | <percentage>
examples rounding an outline note: this example will not display the desired effect if you are viewing this in a browser other than firefox.
-moz-user-focus - CSS: Cascading Style Sheets
formal definition initial valuenoneapplies toall elementsinheritednocomputed valueas specifiedanimation typediscrete formal syntax ignore | normal | select-after | select-before | select-menu | select-same | select-all | none
examples html <input class="ignored" value="the user cannot focus on this element."> css .ignored { -moz-user-focus: ignore; } specifications not part of any standard.
-moz-user-input - CSS: Cascading Style Sheets
formal definition initial valueautoapplies toall elementsinheritedyescomputed valueas specifiedanimation typediscrete formal syntax auto | none | enabled | disabled
examples disabling user input for an element input.example { /* the user will be able to select the text, but not change it.
-webkit-border-before - CSS: Cascading Style Sheets
)where <alpha-value> = <number> | <percentage><hue> = <number> | <angle>
examples applying a border with vertical text html <div> <p class="exampletext">example text</p> </div> css div { background-color: yellow; width: 120px; height: 120px; } .exampletext { writing-mode: vertical-rl; -webkit-border-before: 5px dashed blue; } result specifications not part of any standard, but it relates to the standards-track border-block-start property.
-webkit-line-clamp - CSS: Cascading Style Sheets
formal definition initial valuenoneapplies toall elementsinheritednocomputed valueas specifiedanimation typeby computed value type formal syntax none | <integer>
examples truncating a paragraph html <p> in this example the <code>-webkit-line-clamp</code> property is set to <code>3</code>, which means the text is clamped after three lines.
-webkit-mask-attachment - CSS: Cascading Style Sheets
formal definition initial valuescrollapplies toall elementsinheritednocomputed valueas specifiedanimation typediscrete formal syntax <attachment>#where <attachment> = scroll | fixed | local
examples fixing a mask image to the viewport body { -webkit-mask-image: url('images/mask.png'); -webkit-mask-attachment: fixed; } specifications not part of any standard.
-webkit-mask-box-image - CSS: Cascading Style Sheets
examples setting an image .exampleone { -webkit-mask-box-image: url('mask.png'); } offsetting and filling an image .exampletwo { -webkit-mask-box-image: url('logo.png') 100 100 0 0 round round; } specifications not part of any standard.
-webkit-mask-composite - CSS: Cascading Style Sheets
formal definition initial valuesource-overapplies toall elementsinheritednocomputed valueas specifiedanimation typediscrete formal syntax <composite-style>#where <composite-style> = clear | copy | source-over | source-in | source-out | source-atop | destination-over | destination-in | destination-out | destination-atop | xor
examples compositing with xor .example { -webkit-mask-image: url(mask1.png), url('mask2.png'); -webkit-mask-composite: xor, source-over; } specifications not part of any standard.
-webkit-mask-position-x - CSS: Cascading Style Sheets
formal definition initial value0%applies toall elementsinheritednopercentagesrefer to the size of the box itselfcomputed valuefor <length> the absolute value, otherwise a percentageanimation typediscrete formal syntax [ <length-percentage> | left | center | right ]#where <length-percentage> = <length> | <percentage>
examples horizontally positioning a mask image .exampleone { -webkit-mask-image: url(mask.png); -webkit-mask-position-x: right; } .exampletwo { -webkit-mask-image: url(mask.png); -webkit-mask-position-x: 25%; } specifications not part of any standard.
-webkit-mask-position-y - CSS: Cascading Style Sheets
formal definition initial value0%applies toall elementsinheritednopercentagesrefer to the size of the box itselfcomputed valuefor <length> the absolute value, otherwise a percentageanimation typediscrete formal syntax [ <length-percentage> | top | center | bottom ]#where <length-percentage> = <length> | <percentage>
examples vertically positioning a mask image .exampleone { -webkit-mask-image: url(mask.png); -webkit-mask-position-y: bottom; } .exampletwo { -webkit-mask-image: url(mask.png); -webkit-mask-position-y: 25%; } specifications not part of any standard.
-webkit-mask-repeat-x - CSS: Cascading Style Sheets
formal definition initial valuerepeatapplies toall elementsinheritednocomputed valueas specifiedanimation typediscrete formal syntax repeat | no-repeat | space | round
examples using a repeating or non-repeating mask image .exampleone { -webkit-mask-image: url('mask.png'); -webkit-mask-repeat-x: repeat; } .exampletwo { -webkit-mask-image: url('mask.png'); -webkit-mask-repeat-x: no-repeat; } using multiple mask images you can specify a different <repeat-style> for each mask image, separated by commas: .examplethree { -webkit-mask-image: url('mask1.png'),...
-webkit-mask-repeat-y - CSS: Cascading Style Sheets
formal definition initial valuerepeatapplies toall elementsinheritednocomputed valuefor <length> the absolute value, otherwise a percentageanimation typediscrete formal syntax repeat | no-repeat | space | round
examples using a repeating or non-repeating mask image .exampleone { -webkit-mask-image: url('mask.png'); -webkit-mask-repeat-y: repeat; } .exampletwo { -webkit-mask-image: url('mask.png'); -webkit-mask-repeat-y: no-repeat; } using multiple mask images you can specify a different <repeat-style> for each mask image, separated by commas: .examplethree { -webkit-mask-image: url('mask1.png'),...
-webkit-overflow-scrolling - CSS: Cascading Style Sheets
formal definition initial valueautoapplies toscrolling boxesinheritedyescomputed valueas specifiedanimation typediscrete formal syntax auto | touch
examples html <div class="scroll-touch"> <p> this paragraph has momentum scrolling </p> </div> <div class="scroll-auto"> <p> this paragraph does not.
-webkit-print-color-adjust - CSS: Cascading Style Sheets
examples forcing white-on-black printing article { -webkit-print-color-adjust: exact; background: #222; color: #eee; } specifications not part of any standard, though there is a proposal in the csswg wiki to standardize it.
-webkit-text-fill-color - CSS: Cascading Style Sheets
)where <alpha-value> = <number> | <percentage><hue> = <number> | <angle>
examples changing the fill color css p { margin: 0; font-size: 3em; -webkit-text-fill-color: green; } html <p>this text is green.</p> results specifications specification status comment compatibility standardthe definition of '-webkit-text-fill-color' in that specification.
-webkit-text-stroke-color - CSS: Cascading Style Sheets
)where <alpha-value> = <number> | <percentage><hue> = <number> | <angle>
examples varying the stroke color html <p>text with stroke</p> <input type="color" value="#ff0000"> css p { margin: 0; font-size: 4em; -webkit-text-stroke-width: 3px; -webkit-text-stroke-color: #ff0000; /* can be changed in the live sample */ } javascript var colorpicker = document.queryselector("input"); colorpicker.addeventlistener("change", function(evt) { document.queryselector("p")...
-webkit-text-stroke-width - CSS: Cascading Style Sheets
formal definition initial value0applies toall elementsinheritedyescomputed valueabsolute <length>animation typediscrete formal syntax <length>
examples varying stroke widths css p { margin: 0; font-size: 4em; -webkit-text-stroke-color: red; } #thin { -webkit-text-stroke-width: thin; } #medium { -webkit-text-stroke-width: 3px; } #thick { -webkit-text-stroke-width: 1.5mm; } html <p id="thin">thin stroke</p> <p id="medium">medium stroke</p> <p id="thick">thick stroke</p> results specifications specification st...
-webkit-text-stroke - CSS: Cascading Style Sheets
)where <alpha-value> = <number> | <percentage><hue> = <number> | <angle>
examples adding a red text stroke html <p id="example">the stroke of this text is red.</p> css #example { font-size: 3em; margin: 0; -webkit-text-stroke: 2px red; } result specifications specification status comment compatibility standardthe definition of '-webkit-text-stroke' in that specification.
-webkit-touch-callout - CSS: Cascading Style Sheets
formal definition initial valuedefaultapplies toall elementsinheritedyescomputed valueas specifiedanimation typediscrete formal syntax default | none
examples turn off touch callout .example { -webkit-touch-callout: none; } specifications not part of any standard.
:-moz-drag-over - CSS: Cascading Style Sheets
syntax :-moz-drag-over
examples html <table border="1"> <tr> <td width="100px" height="100px">drag over</td> </tr> </table> css td:-moz-drag-over { color: red; } result specifications not part of any standard.
:-moz-focusring - CSS: Cascading Style Sheets
syntax :-moz-focusring
examples html <input /> css input { margin: 5px; } :-moz-focusring { color: red; outline: 2px dotted green; } result specifications not part of any standard.
:-moz-last-node - CSS: Cascading Style Sheets
syntax :-moz-last-node
examples css span:-moz-last-node { background-color: lime; } html <p> <span>this does not match.</span> <span>this matches!</span> </p> <p> <span>this doesn't match because it's followed by text.</span> blahblah.
::-moz-list-bullet - CSS: Cascading Style Sheets
syntax li::-moz-list-bullet
examples html <ul> <li>item 1</li> <li>item 2</li> <li>item 3</li> </ul> css ::-moz-list-bullet { color: red; font-size: 1.5em; } result specifications not part of any standard.
::-moz-list-number - CSS: Cascading Style Sheets
syntax li::-moz-list-number
examples html <ol> <li>first item</li> <li>second item</li> <li>third item</li> </ol> css li::-moz-list-number { font-style: italic; font-weight: bold; } result screenshotlive sample specifications not part of any standard.
:-moz-loading - CSS: Cascading Style Sheets
syntax :-moz-loading
examples setting a background for images that are loading :-moz-loading { background-color: #aaa; background-image: url(loading-animation.gif) center no-repeat; } specifications not part of any standard.
:-moz-only-whitespace - CSS: Cascading Style Sheets
examples html <div> </div> css :root { overflow: hidden; max-width: 100vw; max-height: 100vh; } div { background-color: #ccc; box-sizing: border-box; height: 100vh; min-height: 16px; min-height: 1rem; } div { border: 4px solid red; } :-moz-only-whitespace { border-color: lime; } result specifications briefly defined as :blank in selectors level 4, but then the functionality was merged into :...
::-moz-focus-inner - CSS: Cascading Style Sheets
examples html <input type="submit" value="input"/> <button type="submit">button</button> css button::-moz-focus-inner, input[type="color"]::-moz-focus-inner, input[type="reset"]::-moz-focus-inner, input[type="button"]::-moz-focus-inner, input[type="submit"]::-moz-focus-inner { padding-block-start: 0px; padding-inline-end: 2px; padding-block-end: 0px; padding-inline-start: 2px; border: 1px dotted red; } res...
::-moz-progress-bar - CSS: Cascading Style Sheets
syntax ::-moz-progress-bar
examples html <progress value="30" max="100">30%</progress> <progress max="100">indeterminate</progress> css ::-moz-progress-bar { background-color: red; } /* force indeterminate bars to have zero width */ :indeterminate::-moz-progress-bar { width: 0; } result specifications not part of any standard.
::-moz-range-progress - CSS: Cascading Style Sheets
syntax ::-moz-range-progress
examples html <input type="range" min="0" max="100" step="5" value="50"/> css input[type=range]::-moz-range-progress { background-color: green; height: 1em; } result a progress bar using this style might look something like this: specifications not part of any standard.
::-moz-range-thumb - CSS: Cascading Style Sheets
syntax ::-moz-range-thumb
examples html <input type="range" min="0" max="100" step="5" value="50"/> css input[type=range]::-moz-range-thumb { background-color: green; } result a progress bar using this style might look something like this: specifications not part of any standard.
::-moz-range-track - CSS: Cascading Style Sheets
syntax ::-moz-range-track
examples html <input type="range" min="0" max="100" step="5" value="50"/> css input[type=range]::-moz-range-track { background-color: green; } result a progress bar using this style might look something like this: specifications not part of any standard.
::-webkit-file-upload-button - CSS: Cascading Style Sheets
syntax selector::-webkit-file-upload-button
examples html <form> <label for="fileupload">upload file</label><br> <input type="file" id="fileupload"> </form> css input, label { display: block; } input[type=file]::-webkit-file-upload-button { border: 1px solid grey; background: #fffaaa; } below is the example for you to try.
::-webkit-meter-bar - CSS: Cascading Style Sheets
examples html <meter min="0" max="10" value="6">score out of 10</meter> css meter { /* reset the default appearance */ -webkit-appearance: none; -moz-appearance: none; appearance: none; } meter::-webkit-meter-bar { background: #eee; box-shadow: 0 2px 3px rgba(0, 0, 0, 0.2) inset; border-radius: 3px; } result ...
::-webkit-progress-bar - CSS: Cascading Style Sheets
syntax ::-webkit-progress-bar
examples css content progress { -webkit-appearance: none; } ::-webkit-progress-bar { background-color: orange; } html content <progress value="10" max="50"> result result screenshot if you're not using a webkit or blink browser, the code above results in a progress bar that looks like this: specifications not part of any standard.
::-webkit-scrollbar - CSS: Cascading Style Sheets
examples .visible-scrollbar, .invisible-scrollbar, .mostly-customized-scrollbar { display: block; width: 10em; overflow: auto; height: 2em; } .invisible-scrollbar::-webkit-scrollbar { display: none; } /* demonstrate a "mostly customized" scrollbar * (won't be visible otherwise if width/height is specified) */ .mostly-customized-scrollbar::-webkit-scrollbar { width: 5px; height: 8px; ba...
::backdrop - CSS: Cascading Style Sheets
syntax ::backdrop
examples styling the backdrop for full-screen video in this example, the backdrop style used when a video is shifted to full-screen mode is configured to be a grey-blue color rather than the black it defaults to in most browsers.
::cue - CSS: Cascading Style Sheets
osition background-repeat background-size color font font-family font-size font-stretch font-style font-variant font-weight line-height opacity outline outline-color outline-style outline-width ruby-position text-combine-upright text-decoration text-decoration-color text-decoration-line text-decoration-style text-decoration-thickness text-shadow visibility white-space
examples styling webvtt cues as white-on-black the following css sets the cue style so that the text is white and the background is a translucent black box.
::first-letter (:first-letter) - CSS: Cascading Style Sheets
dius, border-image, and the longhands properties the color property the text-decoration, text-shadow, text-transform, letter-spacing, word-spacing (when appropriate), line-height, text-decoration-color, text-decoration-line, text-decoration-style, box-shadow, float, vertical-align (only if float is none) css properties syntax /* css3 syntax */ ::first-letter /* css2 syntax */ :first-letter
examples simple drop cap in this example we will use the ::first-letter pseudo-element to create a simple drop cap effect on the first letter of the paragraph coming right after the <h2>.
::grammar-error - CSS: Cascading Style Sheets
allowable properties only a small subset of css properties can be used in a rule with ::grammar-error in its selector: color background-color cursor caret-color outline and its longhands text-decoration and its associated properties text-emphasis-color text-shadow syntax ::grammar-error
examples simple document grammar check in this example, eventual supporting browsers should highlight any flagged grammatical errors with the styles shown.
::marker - CSS: Cascading Style Sheets
syntax ::marker
examples html <ul> <li>peaches</li> <li>apples</li> <li>plums</li> </ul> css ul li::marker { color: red; font-size: 1.5em; } result specifications specification status comment css pseudo-elements level 4the definition of '::marker' in that specification.
::part() - CSS: Cascading Style Sheets
custom-element::part(foo) { /* styles to apply to the `foo` part */ } syntax ::part( <ident>+ )
examples html <template id="tabbed-custom-element"> <style type="text/css"> *, ::before, ::after { box-sizing: border-box; padding: 1rem; } :host { display: flex; } </style> <div part="tab active">tab 1</div> <div part="tab">tab 2</div> <div part="tab">tab 3</div> </template> <tabbed-custom-element></tabbed-custom-element> css tabbed-custom-element::part(tab) { color: #0c0c0dcc; border-bottom: transparent solid 2px; } tabbed-custom-element::part(tab):hover { background-color: #0c0c0d19; border-color: #0c0c0d33; } tabbed-custom-element::part(tab):hover:active { back...
::placeholder - CSS: Cascading Style Sheets
mdn basic form hints placeholders in form fields are harmful — nielsen norman group
examples red text html <input placeholder="type something here!"> css input::placeholder { color: red; font-size: 1.2em; font-style: italic; } result green text html <input placeholder="type something here..."> css input::placeholder { color: green; } result specifications specification status comment css pseudo-elements level 4the definition of '::pl...
::spelling-error - CSS: Cascading Style Sheets
allowable properties only a small subset of css properties can be used in a rule with ::spelling-error in its selector: color background-color cursor caret-color outline and its longhands text-decoration and its associated properties text-emphasis-color text-shadow syntax ::spelling-error
examples simple document spell check in this example, eventual supporting browsers should highlight any flagged spelling errors with the styles shown.
:active - CSS: Cascading Style Sheets
syntax :active
examples active links html <p>this paragraph contains a link: <a href="#">this link will turn red while you click on it.</a> the paragraph will get a gray background while you click on it or the link.
:any-link - CSS: Cascading Style Sheets
/* selects any element that would be matched by :link or :visited */ :any-link { color: green; } syntax :any-link
examples html <a href="https://example.com">external link</a><br> <a href="#">internal target link</a><br> <a>placeholder link (won't get styled)</a> css a:any-link { border: 1px solid blue; color: orange; } /* webkit browsers */ a:-webkit-any-link { border: 1px solid blue; color: orange; } result specifications specification status comment selectors level 4t...
:blank - CSS: Cascading Style Sheets
syntax :blank
examples simple :blank example in eventual supporting browsers, the :blank pseudo-class will enable developers to highlight in some way input controls that are not required, but still have no content filled in, perhaps as a reminder to users.
:checked - CSS: Cascading Style Sheets
syntax :checked
examples basic example html <div> <input type="radio" name="my-input" id="yes"> <label for="yes">yes</label> <input type="radio" name="my-input" id="no"> <label for="no">no</label> </div> <div> <input type="checkbox" name="my-checkbox" id="opt-in"> <label for="opt-in">check me!</label> </div> <select name="my-select" id="fruit"> <option value="opt1">apples</option> <option value="opt...
:default - CSS: Cascading Style Sheets
syntax :default
examples html <fieldset> <legend>favorite season</legend> <input type="radio" name="season" id="spring"> <label for="spring">spring</label> <input type="radio" name="season" id="summer" checked> <label for="summer">summer</label> <input type="radio" name="season" id="fall"> <label for="fall">fall</label> <input type="radio" name="season" id="winter"> <label for="winter">winter</lab...
:defined - CSS: Cascading Style Sheets
/* selects any defined element */ :defined { font-style: italic; } /* selects any instance of a specific custom element */ simple-custom:defined { display: block; } syntax :defined
examples hiding elements until they are defined the following snippets are taken from our defined-pseudo-class demo (see it live also).
:dir() - CSS: Cascading Style Sheets
formal syntax :dir( ltr | rtl )
examples html <div dir="rtl"> <span>test1</span> <div dir="ltr">test2 <div dir="auto">עִבְרִית</div> </div> </div> css :dir(ltr) { background-color: yellow; } :dir(rtl) { background-color: powderblue; } result specifications specification status comment html living standardthe definition of ':dir(ltr)' in that specification.
:empty - CSS: Cascading Style Sheets
/* selects any <div> that contains no content */ div:empty { background: lime; } syntax :empty
examples html <div class="box"><!-- i will be lime.
:enabled - CSS: Cascading Style Sheets
/* selects any enabled <input> */ input:enabled { color: blue; } syntax :enabled
examples the following example makes the color of text and button <input>s green when enabled, and gray when disabled.
:first-child - CSS: Cascading Style Sheets
syntax :first-child
examples basic example html <div> <p>this text is selected!</p> <p>this text isn't selected.</p> </div> <div> <h2>this text isn't selected: it's not a `p`.</h2> <p>this text isn't selected.</p> </div> css p:first-child { color: lime; background-color: black; padding: 5px; } result styling a list html <ul> <li>item 1</li> <li>item 2</li> <li>item 3 <ul> <li>item 3.1</li> <li>item 3.2</li> ...
:first-of-type - CSS: Cascading Style Sheets
syntax :first-of-type
examples styling the first paragraph html <h2>heading</h2> <p>paragraph 1</p> <p>paragraph 2</p> css p:first-of-type { color: red; font-style: italic; } result nested elements this example shows how nested elements can also be targeted.
:first - CSS: Cascading Style Sheets
syntax :first
examples html <p>first page.</p> <p>second page.</p> <button>print!</button> css @page :first { margin-left: 50%; margin-top: 50%; } p { page-break-after: always; } javascript document.queryselector("button").addeventlistener('click', () => { window.print(); }); result press the "print!" button to print the example.
:focus - CSS: Cascading Style Sheets
syntax :focus
examples html <input class="red-input" value="i'll be red when focused."><br> <input class="blue-input" value="i'll be blue when focused."> css .red-input:focus { background: yellow; color: red; } .blue-input:focus { background: yellow; color: blue; } result accessibility concerns make sure the visual focus indicator can be seen by people with low vision.
:has() - CSS: Cascading Style Sheets
examples matching <a> elements that directly contain an <img> the following selector matches only <a> elements that directly contain an <img> child: a:has(> img) matching <h1> elements that are followed by a <p> the following selector matches <h1> elements only if they have a <p> element directly following them: h1:has(+ p) specifications specification status comment s...
:host() - CSS: Cascading Style Sheets
'='<attr-modifier> = i | s
examples selectively styling shadow hosts the following snippets are taken from our host-selectors example (see it live also).
:host - CSS: Cascading Style Sheets
/* selects a shadow root host */ :host { font-weight: bold; } syntax :host
examples styling the shadow host the following snippets are taken from our host-selectors example (see it live also).
:hover - CSS: Cascading Style Sheets
syntax :hover
examples basic example html <a href="#">try hovering over this link.</a> css a { background-color: powderblue; transition: background-color .5s; } a:hover { background-color: gold; } result image gallery you can use the :hover pseudo-class to build an image gallery with full-size images that show only when the mouse moves over a thumbnail.
:in-range - CSS: Cascading Style Sheets
in the absence of such a limitation, the element can neither be "in-range" nor "out-of-range." syntax :in-range
examples html <form action="" id="form1"> <ul>values between 1 and 10 are valid.
:indeterminate - CSS: Cascading Style Sheets
y <input> whose state is indeterminate */ input:indeterminate { background: lime; } elements targeted by this selector are: <input type="checkbox"> elements whose indeterminate property is set to true by javascript <input type="radio"> elements, when all radio buttons with the same name value in the form are unchecked <progress> elements in an indeterminate state syntax :indeterminate
examples checkbox & radio button this example applies special styles to the labels associated with indeterminate form fields.
:is() (:matches(), :any()) - CSS: Cascading Style Sheets
'='<attr-modifier> = i | s
examples cross-browser example <header> <p>this is my header paragraph</p> </header> <main> <ul> <li><p>this is my first</p><p>list item</p></li> <li><p>this is my second</p><p>list item</p></li> </ul> </main> <footer> <p>this is my footer paragraph</p> </footer> :-webkit-any(header, main, footer) p:hover { color: red; cursor: pointer; } :-moz-any(header, main, footer) p:hover { ...
:last-child - CSS: Cascading Style Sheets
syntax :last-child
examples basic example html <div> <p>this text isn't selected.</p> <p>this text is selected!</p> </div> <div> <p>this text isn't selected.</p> <h2>this text isn't selected: it's not a `p`.</h2> </div> css p:last-child { color: lime; background-color: black; padding: 5px; } result styling a list html <ul> <li>item 1</li> <li>item 2</li> <li>item 3 <ul> <li>item 3.1</li> <li>item 3.2</li> <li>...
:last-of-type - CSS: Cascading Style Sheets
syntax :last-of-type
examples styling the last paragraph html <h2>heading</h2> <p>paragraph 1</p> <p>paragraph 2</p> css p:last-of-type { color: red; font-style: italic; } result nested elements this example shows how nested elements can also be targeted.
:left - CSS: Cascading Style Sheets
syntax :left
examples setting a margin for left-hand pages @page :left { margin: 2in 3in; } specifications specification status comment css paged media module level 3the definition of ':left' in that specification.
:not() - CSS: Cascading Style Sheets
examples html <p>i am a paragraph.</p> <p class="fancy">i am so very fancy!</p> <div>i am not a paragraph.</div> css .fancy { text-shadow: 2px 2px 3px gold; } /* <p> elements that are not in the class `.fancy` */ p:not(.fancy) { color: green; } /* elements that are not <p> elements */ body :not(p) { text-decoration: underline; } /* elements that are not <div> and not <span> elements */ body ...
:nth-last-of-type() - CSS: Cascading Style Sheets
formal syntax :nth-last-of-type( <nth> )where <nth> = <an-plus-b> | even | odd
examples html <div> <span>this is a span.</span> <span>this is another span.</span> <em>this is emphasized.</em> <span>wow, this span gets limed!!!</span> <strike>this is struck through.</strike> <span>here is one last span.</span> </div> css span:nth-last-of-type(2) { background-color: lime; } result specifications specification status comment selectors ...
:nth-of-type() - CSS: Cascading Style Sheets
formal syntax :nth-of-type( <nth> )where <nth> = <an-plus-b> | even | odd
examples basic example html <div> <div>this element isn't counted.</div> <p>1st paragraph.</p> <p>2nd paragraph.</p> <div>this element isn't counted.</div> <p>3rd paragraph.</p> <p class="fancy">4th paragraph.</p> </div> css /* odd paragraphs */ p:nth-of-type(2n+1) { color: red; } /* even paragraphs */ p:nth-of-type(2n) { color: blue; } /* first paragraph */ p:nth-of-type(1) { fon...
:only-child - CSS: Cascading Style Sheets
syntax :only-child
examples basic example html <div> <div>i am an only child.</div> </div> <div> <div>i am the 1st sibling.</div> <div>i am the 2nd sibling.</div> <div>i am the 3rd sibling, <div>but this is an only child.</div></div> </div> css div:only-child { color: red; } div { display: inline-block; margin: 6px; outline: 1px solid; } result a list example html <ol> <li>first <ul> ...
:only-of-type - CSS: Cascading Style Sheets
syntax :only-of-type
examples styling elements with no siblings of the same type html <main> <div>i am `div` #1.</div> <p>i am the only `p` among my siblings.</p> <div>i am `div` #2.</div> <div>i am `div` #3.
:out-of-range - CSS: Cascading Style Sheets
in the absence of such a limitation, the element can neither be "in-range" nor "out-of-range." syntax :out-of-range
examples html <form action="" id="form1"> <p>values between 1 and 10 are valid.</p> <ul> <li> <input id="value1" name="value1" type="number" placeholder="1 to 10" min="1" max="10" value="12"> <label for="value1">your value is </label> </li> </ul> </form> css li { list-style: none; margin-bottom: 1em; } input { border: 1px solid black; } input:in-range { background-c...
:placeholder-shown - CSS: Cascading Style Sheets
/* selects any element with an active placeholder */ :placeholder-shown { border: 2px solid silver; } syntax :placeholder-shown
examples basic example this example applies special font and border styles when the placeholder is shown.
:read-only - CSS: Cascading Style Sheets
input:read-only, textarea:read-only { background-color: #ccc; } p:read-only { background-color: #ccc; } syntax :read-only
examples confirming form information in read-only/read-write controls one use of readonly form controls is to allow the user to check and verify information that they may have entered in an earlier form (for example, shipping details), while still being able to submit the information along with the rest of the form.
:read-write - CSS: Cascading Style Sheets
input:read-write, textarea:read-write { background-color: #bbf; } p:read-write { background-color: #bbf; } syntax :read-write
examples confirming form information in read-only/read-write controls one use of readonly form controls is to allow the user to check and verify information that they may have entered in an earlier form (for example, shipping details), while still being able to submit the information along with the rest of the form.
:right - CSS: Cascading Style Sheets
syntax :right
examples setting margins for right-hand pages @page :right { margin: 2in 3in; } specifications specification status comment css paged media module level 3the definition of ':right' in that specification.
:root - CSS: Cascading Style Sheets
/* selects the root element of the document: <html> in the case of html */ :root { background: yellow; } syntax :root
examples declaring global css variables :root can be useful for declaring global css variables: :root { --main-color: hotpink; --pane-padding: 5px 42px; } specifications specification status comment selectors level 4the definition of ':root' in that specification.
:scope - CSS: Cascading Style Sheets
syntax :scope
examples identity match in this simple example, we demonstrate that using the :scope pseudo-class from the element.matches() method matches the element on which it's called.
:target - CSS: Cascading Style Sheets
ching the current url's fragment */ :target { border: 2px solid black; } for example, the following url has a fragment (denoted by the # sign) that points to an element called section2: http://www.example.com/index.html#section2 the following element would be selected by a :target selector when the current url is equal to the above: <section id="section2">example</section> syntax :target
examples a table of contents the :target pseudo-class can be used to highlight the portion of a page that has been linked to from a table of contents.
:valid - CSS: Cascading Style Sheets
syntax :valid
examples indicating valid and invalid form fields in this example, we use structures like this, which include extra <span>s to generate content on; we'll use these to provide indicators of valid/invalid data: <div> <label for="fname">first name *: </label> <input id="fname" name="fname" type="text" required> <span></span> </div> to provide these indicators, we use the following css: input + spa...
@charset - CSS: Cascading Style Sheets
formal syntax @charset "<charset>";
examples valid and invalid charset declarations @charset "utf-8"; /* set the encoding of the style sheet to unicode utf-8 */ @charset 'iso-8859-15'; /* invalid, wrong quoting style used */ @charset "utf-8"; /* invalid, more than one space */ @charset "utf-8"; /* invalid, there is a character (a space) before the at-rule */ @charset utf-8; /* invalid, without ' or ", the charset...
additive-symbols - CSS: Cascading Style Sheets
ge><hue> = <number> | <angle><linear-color-stop> = <color> <color-stop-length>?<linear-color-hint> = <length-percentage><length-percentage> = <length> | <percentage><angular-color-stop> = <color> && <color-stop-angle>?<angular-color-hint> = <angle-percentage>where <color-stop-length> = <length-percentage>{1,2}<color-stop-angle> = <angle-percentage>{1,2}<angle-percentage> = <angle> | <percentage>
examples specifying additive symbols html <ul class="list"> <li>one</li> <li>two</li> <li>three</li> <li>four</li> <li>five</li> </ul> css @counter-style additive-symbols-example { system: additive; additive-symbols: v 5, iv 4, i 1; } .list { list-style: additive-symbols-example; } result specifications specification status comment css counter styles l...
fallback - CSS: Cascading Style Sheets
formal definition related at-rule@counter-styleinitial valuedecimalcomputed valueas specified formal syntax <counter-style-name>where <counter-style-name> = <custom-ident>
examples specifying a fallback counter style html <ul class="list"> <li>one</li> <li>two</li> <li>three</li> <li>four</li> <li>five</li> </ul> css @counter-style fallback-example { system: fixed; symbols: "\24b6" "\24b7" "\24b8"; fallback: upper-alpha; } .list { list-style: fallback-example; } result specifications specification status comment css c...
negative - CSS: Cascading Style Sheets
ge><hue> = <number> | <angle><linear-color-stop> = <color> <color-stop-length>?<linear-color-hint> = <length-percentage><length-percentage> = <length> | <percentage><angular-color-stop> = <color> && <color-stop-angle>?<angular-color-hint> = <angle-percentage>where <color-stop-length> = <length-percentage>{1,2}<color-stop-angle> = <angle-percentage>{1,2}<angle-percentage> = <angle> | <percentage>
examples rendering negative counters html <ul class="list" start="-3"> <li>one</li> <li>two</li> <li>three</li> <li>four</li> <li>five</li> </ul> css @counter-style neg { system: numeric; symbols: "0" "1" "2" "3" "4" "5" "6" "7" "8" "9"; negative: "(-" ")"; } .list { list-style: neg; } result specifications specification status comment css counter s...
pad - CSS: Cascading Style Sheets
ge><hue> = <number> | <angle><linear-color-stop> = <color> <color-stop-length>?<linear-color-hint> = <length-percentage><length-percentage> = <length> | <percentage><angular-color-stop> = <color> && <color-stop-angle>?<angular-color-hint> = <angle-percentage>where <color-stop-length> = <length-percentage>{1,2}<color-stop-angle> = <angle-percentage>{1,2}<angle-percentage> = <angle> | <percentage>
examples padding a counter html <ul class="list"> <li>one</li> <li>two</li> <li>three</li> <li>four</li> <li>five</li> </ul> css @counter-style pad-example { system: numeric; symbols: "0" "1" "2" "3" "4" "5"; pad: 2 "0"; } .list { list-style: pad-example; } result specifications specification status comment css counter styles level 3the definition o...
prefix - CSS: Cascading Style Sheets
e><hue> = <number> | <angle><linear-color-stop> = <color> <color-stop-length>?<linear-color-hint> = <length-percentage><length-percentage> = <length> | <percentage><angular-color-stop> = <color> && <color-stop-angle>?<angular-color-hint> = <angle-percentage>where <color-stop-length> = <length-percentage>{1,2}<color-stop-angle> = <angle-percentage>{1,2}<angle-percentage> = <angle> | <percentage>
examples adding a prefix to a counter html <ul class="index"> <li>the boy who lived</li> <li>the vanishing glass</li> <li>the letters from no one</li> <li>the keeper of the keys</li> <li>diagon alley</li> </ul> css @counter-style chapters { system: numeric; symbols: "0" "1" "2" "3" "4" "5" "6" "7" "8" "9"; prefix: 'chapter '; } .index { list-style: chapters; padding-left: 15ch; }...
range - CSS: Cascading Style Sheets
formal definition related at-rule@counter-styleinitial valueautocomputed valueas specified formal syntax [ [ <integer> | infinite ]{2} ]# | auto
examples setting counter style over a range <ul class="list"> <li>one</li> <li>two</li> <li>three</li> <li>four</li> <li>five</li> <li>six</li> <li>seven</li> <li>eight</li> <li>nine</li> <li>ten</li> </ul> @counter-style range-multi-example { system: cyclic; symbols: "\25a0" "\25a1"; range: 2 4, 7 9; } .list { list-style: range-multi-example; } the above list will display...
speak-as - CSS: Cascading Style Sheets
let's talk about speech css | css tricks formal definition related at-rule@counter-styleinitial valueautocomputed valueas specified formal syntax auto | bullets | numbers | words | spell-out | <counter-style-name>where <counter-style-name> = <custom-ident>
examples setting the spoken form for a counter html <ul class="list"> <li>one</li> <li>two</li> <li>three</li> <li>four</li> <li>five</li> </ul> css @counter-style speak-as-example { system: fixed; symbols: ; suffix: " "; speak-as: numbers; } .list { list-style: speak-as-example; } result specifications specification status comment ...
suffix - CSS: Cascading Style Sheets
ge><hue> = <number> | <angle><linear-color-stop> = <color> <color-stop-length>?<linear-color-hint> = <length-percentage><length-percentage> = <length> | <percentage><angular-color-stop> = <color> && <color-stop-angle>?<angular-color-hint> = <angle-percentage>where <color-stop-length> = <length-percentage>{1,2}<color-stop-angle> = <angle-percentage>{1,2}<angle-percentage> = <angle> | <percentage>
examples setting a suffix for a counter html <ul class="choices"> <li>one</li> <li>two</li> <li>three</li> <li>none of the above</li> </ul> css @counter-style options { system: fixed; symbols: a b c d; suffix: ") "; } .choices { list-style: options; } result specifications specification status comment css counter styles level 3the definition of 'suffi...
symbols - CSS: Cascading Style Sheets
ge><hue> = <number> | <angle><linear-color-stop> = <color> <color-stop-length>?<linear-color-hint> = <length-percentage><length-percentage> = <length> | <percentage><angular-color-stop> = <color> && <color-stop-angle>?<angular-color-hint> = <angle-percentage>where <color-stop-length> = <length-percentage>{1,2}<color-stop-angle> = <angle-percentage>{1,2}<angle-percentage> = <angle> | <percentage>
examples setting counter symbols html <ul class="list"> <li>one</li> <li>two</li> <li>three</li> <li>four</li> <li>five</li> </ul> css @counter-style symbols-example { system: fixed; symbols: a "1" "\24b7" d e; } .list { list-style: symbols-example; } result specifications specification status comment css counter styles level 3the definition of 'symbo...
system - CSS: Cascading Style Sheets
] | [ extends <counter-style-name> ]where <counter-style-name> = <custom-ident>
examples cyclic counter if your browser supports it, this example will render a list like this: ◉ one ◉ two ◉ three css <ul> <li>one</li> <li>two</li> <li>three</li> </ul> @counter-style fisheye { system: cyclic; symbols: ◉; suffix: " "; } ul { list-style: fisheye; } result fixed counter if your browser supports it, this example will render a list like this: ➀ on...
@document - CSS: Cascading Style Sheets
formal syntax @document [ <url> | url-prefix(<string>) | domain(<string>) | media-document(<string>) | regexp(<string>) ]# { <group-rule-body> }
examples specifying document for css rule @document url("http://www.w3.org/"), url-prefix("http://www.w3.org/style/"), domain("mozilla.org"), media-document("video"), regexp("https:.*") { /* css rules here apply to: - the page "http://www.w3.org/" - any page whose url begins with "http://www.w3.org/style/" - any page whose url's host is "mozilla.o...
font-display - CSS: Cascading Style Sheets
formal definition related at-rule@font-faceinitial valueautocomputed valueas specified formal syntax [ auto | block | swap | fallback | optional ]
examples specifying fallback font-display @font-face { font-family: examplefont; src: url(/path/to/fonts/examplefont.woff) format('woff'), url(/path/to/fonts/examplefont.eot) format('eot'); font-weight: 400; font-style: normal; font-display: fallback; } specifications specification status comment css fonts module level 4the definition of 'font-display' in t...
font-family - CSS: Cascading Style Sheets
formal definition related at-rule@font-faceinitial valuen/a (required)computed valueas specified formal syntax <family-name>where <family-name> = <string> | <custom-ident>+
examples setting the font family name @font-face { font-family: examplefont; src: url('examplefont.ttf'); } specifications specification status comment css fonts module level 3the definition of 'font-family' in that specification.
font-stretch - CSS: Cascading Style Sheets
4 explanations understanding success criterion 1.4.8 | w3c understanding wcag 2.0 formal definition related at-rule@font-faceinitial valuenormalcomputed valueas specified formal syntax <font-stretch-absolute>{1,2}where <font-stretch-absolute> = normal | ultra-condensed | extra-condensed | condensed | semi-condensed | semi-expanded | expanded | extra-expanded | ultra-expanded | <percentage>
examples setting a percentage range for font-stretch the following find a local open sans font or import it, and allow using the font for normal, semi-condensed and semi-expanded states.
font-style - CSS: Cascading Style Sheets
formal definition related at-rule@font-faceinitial valuenormalcomputed valueas specified formal syntax normal | italic | oblique <angle>{0,2}
examples specifying an italic font style as an example, consider the garamond font family, in its normal form, we get the following result: @font-face { font-family: garamond; src: url('garamond.ttf'); } the italicized version of this text uses the same glyphs present in the unstyled version, but they are artificially sloped by a few degrees.
font-variation-settings - CSS: Cascading Style Sheets
formal definition related at-rule@font-faceinitial valuenormalcomputed valueas specified formal syntax normal | [ <string> <number> ]#
examples setting font weight and stretch in a @font-face rule @font-face { font-family: 'opentypefont'; src: url('open_type_font.woff2') format('woff2'); font-weight: normal; font-style: normal; font-variation-settings: 'wght' 400, 'wdth' 300; } specifications specification status comment css fonts module level 4the definition of 'font-variation-settings' in that ...
font-weight - CSS: Cascading Style Sheets
4.8 | w3c understanding wcag 2.0 formal definition related at-rule@font-faceinitial valuenormalcomputed valueas specified formal syntax <font-weight-absolute>{1,2}where <font-weight-absolute> = normal | bold | <number <a href="/docs/css/value_definition_syntax#brackets" title="brackets: enclose several entities, combinators, and multipliers to transform them as a single component">[1,1000]>
examples setting normal font weight in a @font-face rule the following finds a local open sans font or import it, and allows using the font for normal font weights.
src - CSS: Cascading Style Sheets
| local( <family-name> ) ]#where <family-name> = <string> | <custom-ident>+
examples specifying font resources using url() and local() @font-face { font-family: examplefont; src: local(example font), url('examplefont.woff') format("woff"), url('examplefont.otf') format("opentype"); } specifications specification status comment css fonts module level 3the definition of 'src' in that specification.
unicode-range - CSS: Cascading Style Sheets
formal definition related at-rule@font-faceinitial valueu+0-10ffffcomputed valueas specified formal syntax <unicode-range>#
examples using a different font for a single character in this example we create a simple html containing a single <div> element, including an ampersand, that we want to style with a different font.
@font-face - CSS: Cascading Style Sheets
t-family: <family-name>; ] | [ src: <src>; ] | [ unicode-range: <unicode-range>; ] | [ font-variant: <font-variant>; ] | [ font-feature-settings: <font-feature-settings>; ] | [ font-variation-settings: <font-variation-settings>; ] | [ font-stretch: <font-stretch>; ] | [ font-weight: <font-weight>; ] | [ font-style: <font-style>; ] }where <family-name> = <string> | <custom-ident>+
examples specifying a downloadable font this example simply specifies a downloadable font to use, applying it to the entire body of the document: view the live example <html> <head> <title>web font sample</title> <style type="text/css" media="screen, print"> @font-face { font-family: "bitstream vera serif bold"; src: url("https://mdn.mozillademos.org/files/2468/verasebd.ttf"); ...
@font-feature-values - CSS: Cascading Style Sheets
<custom-ident>+<feature-value-block-list> = <feature-value-block>+where <feature-value-block> = <feature-type> '{' <feature-value-declaration-list> '}'where <feature-type> = @stylistic | @historical-forms | @styleset | @character-variant | @swash | @ornaments | @annotation<feature-value-declaration-list> = <feature-value-declaration>where <feature-value-declaration> = <custom-ident>: <integer>+;
examples using @styleset in a @font-feature-values rule /* at-rule for "nice-style" in font one */ @font-feature-values font one { @styleset { nice-style: 12; } } /* at-rule for "nice-style" in font two */ @font-feature-values font two { @styleset { nice-style: 4; } } … /* apply the at-rules with a single declaration */ .nice-look { font-variant-alternates: styleset(nice-style); }...
@import - CSS: Cascading Style Sheets
<mf-value>where <mf-name> = <ident><mf-value> = <number> | <dimension> | <ident> | <ratio>
examples importing css rules @import 'custom.css'; @import url("chrome://communicator/skin/"); importing css rules conditionally @import url("fineprint.css") print; @import url("bluish.css") speech; @import "common.css" screen; @import url('landscape.css') screen and (orientation:landscape); specifications specification status comment css cascading and inheritance level 4...
@keyframes - CSS: Cascading Style Sheets
margin-bottom: 100px; } to { margin-top: 150px !important; /* ignored */ margin-bottom: 50px; } } formal syntax @keyframes <keyframes-name> { <keyframe-block-list> }where <keyframes-name> = <custom-ident> | <string><keyframe-block-list> = <keyframe-block>+where <keyframe-block> = <keyframe-selector># { <declaration-list> }where <keyframe-selector> = from | to | <percentage>
examples css animation
examples see using css animations for
examples.
-moz-device-pixel-ratio - CSS: Cascading Style Sheets
media: media/visual accepts min/max prefixes: yes
examples basic compatibility example -moz-device-pixel-ratio may be used for compatibility with firefox older than 16, and alongside -webkit-device-pixel-ratio for compatibility with webkit-based browsers that do not support dppx.
-ms-high-contrast - CSS: Cascading Style Sheets
examples the following declarations will match applications that are being displayed in high contrast mode with any color variation, a black-on-white color variation, and a white-on-black color variation, respectively.
resolution - CSS: Cascading Style Sheets
examples html <p>this is a test of your device's pixel density.</p> css /* exact resolution */ @media (resolution: 150dpi) { p { color: red; } } /* minimum resolution */ @media (min-resolution: 72dpi) { p { text-decoration: underline; } } /* maximum resolution */ @media (max-resolution: 300dpi) { p { background: yellow; } } result specifications specification status comment ...
shape - CSS: Cascading Style Sheets
examples basic example html <h1>hello world!</h1> css h1 { text-align: left; } @media (shape: rect) { h1 { text-align: left; } } @media (shape: round) { h1 { text-align: center; } } custom stylesheet this html will apply a special stylesheet for devices that have round screens.
width - CSS: Cascading Style Sheets
examples html <div>watch this element as you resize your viewport's width.</div> css /* exact width */ @media (width: 360px) { div { color: red; } } /* minimum width */ @media (min-width: 35rem) { div { background: yellow; } } /* maximum width */ @media (max-width: 50rem) { div { border: 2px solid blue; } } result specifications specification status comment media queries level 4the defi...
@namespace - CSS: Cascading Style Sheets
[ <string> | <url> ];where <namespace-prefix> = <ident>
examples specifying default and prefixed namespaces @namespace url(http://www.w3.org/1999/xhtml); @namespace svg url(http://www.w3.org/2000/svg); /* this matches all xhtml <a> elements, as xhtml is the default unprefixed namespace */ a {} /* this matches all svg <a> elements */ svg|a {} /* this matches both xhtml and svg <a> elements */ *|a {} specifications specification status comm...
bleed - CSS: Cascading Style Sheets
formal definition related at-rule@pageinitial valueautocomputed valueas specified formal syntax auto | <length>
examples setting a page bleed of 1cm @page { bleed: 1cm; } specifications specification status comment css paged media module level 3the definition of 'bleed' in that specification.
marks - CSS: Cascading Style Sheets
formal definition related at-rule@pageinitial valuenonecomputed valueas specified formal syntax none | [ crop | cross ]
examples adding crop and cross marks @page { marks: crop cross; } specifications specification status comment css paged media module level 3the definition of 'marks' in that specification.
size - CSS: Cascading Style Sheets
formal definition related at-rule@pageinitial valueautocomputed valueas specified, but with relative lengths converted into absolute lengths formal syntax <length>{1,2} | auto | [ <page-size> | [ portrait | landscape ] ]
examples specifying size and orientation @page { size: 4in 6in landscape; } nesting inside a @media rule @media print { @page { size: 50mm 150mm; } } specifications specification status comment css paged media module level 3the definition of 'size' in that specification.
@page - CSS: Cascading Style Sheets
argin-box> = <page-margin-box-type> '{' <declaration-list> '}'where <pseudo-page> = : [ left | right | first | blank ]<page-margin-box-type> = @top-left-corner | @top-left | @top-center | @top-right | @top-right-corner | @bottom-left-corner | @bottom-left | @bottom-center | @bottom-right | @bottom-right-corner | @left-top | @left-middle | @left-bottom | @right-top | @right-middle | @right-bottom
examples @page pseudo-class
examples please refer to the various pseudo-classes of @page for
examples.
height - CSS: Cascading Style Sheets
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.
max-height - CSS: Cascading Style Sheets
formal definition related at-rule@viewportinitial valueautopercentagesrefer to the height of the initial viewportcomputed valueif specified as a length, the corresponding absolute length; if specified as a percentage, the specified value; otherwise, auto formal syntax <viewport-length>where <viewport-length> = auto | <length-percentage>where <length-percentage> = <length> | <percentage>
examples setting viewport max height in pixels @viewport { max-height: 600px; } specifications specification status comment css device adaptationthe definition of '"max-height" descriptor' in that specification.
max-width - CSS: Cascading Style Sheets
formal definition related at-rule@viewportinitial valueautopercentagesrefer to the width of the initial viewportcomputed valueif specified as a length, the corresponding absolute length; if specified as a percentage, the specified value; otherwise, auto formal syntax <viewport-length>where <viewport-length> = auto | <length-percentage>where <length-percentage> = <length> | <percentage>
examples setting viewport max width in pixels @viewport { max-width: 600px; } specifications specification status comment css device adaptationthe definition of '"max-width" descriptor' in that specification.
max-zoom - CSS: Cascading Style Sheets
formal definition related at-rule@viewportinitial valueautopercentagesthe zoom factor itselfcomputed valueauto, or a non-negative number or percentage as specified formal syntax auto | <number> | <percentage>
examples setting max-zoom @viewport { max-zoom: 1.5; } specifications specification status comment css device adaptationthe definition of '"max-zoom" descriptor' in that specification.
min-height - CSS: Cascading Style Sheets
formal definition related at-rule@viewportinitial valueautopercentagesrefer to the height of the initial viewportcomputed valueif specified as a length, the corresponding absolute length; if specified as a percentage, the specified value; otherwise, auto formal syntax <viewport-length>where <viewport-length> = auto | <length-percentage>where <length-percentage> = <length> | <percentage>
examples setting viewport min height in pixels @viewport { min-height: 200px; } specifications specification status comment css device adaptationthe definition of '"min-height" descriptor' in that specification.
min-width - CSS: Cascading Style Sheets
formal definition related at-rule@viewportinitial valueautopercentagesrefer to the width of the initial viewportcomputed valueif specified as a length, the corresponding absolute length; if specified as a percentage, the specified value; otherwise, auto formal syntax <viewport-length>where <viewport-length> = auto | <length-percentage>where <length-percentage> = <length> | <percentage>
examples setting viewport min width in pixels @viewport { min-width: 200px; } specifications specification status comment css device adaptationthe definition of '"min-width" descriptor' in that specification.
min-zoom - CSS: Cascading Style Sheets
formal definition related at-rule@viewportinitial valueautopercentagesthe zoom factor itselfcomputed valueauto, or a non-negative number or percentage as specified formal syntax auto | <number> | <percentage>
examples setting min zoom factor @viewport { min-zoom: 2.0; } specifications specification status comment css device adaptationthe definition of '"min-zoom" descriptor' in that specification.
orientation - CSS: Cascading Style Sheets
formal definition related at-rule@viewportinitial valueautopercentagesrefer to the size of bounding boxcomputed valueas specified formal syntax auto | portrait | landscape
examples setting viewport orientation @viewport { orientation: landscape; } specifications specification status comment css device adaptationthe definition of '"orientation" descriptor' in that specification.
user-zoom - CSS: Cascading Style Sheets
mdn understanding wcag, guideline 1.4 explanations understanding success criterion 1.4.4 | understanding wcag 2.0 formal definition related at-rule@viewportinitial valuezoompercentagesrefer to the size of bounding boxcomputed valueas specified formal syntax zoom | fixed
examples disabling user zoom @viewport { user-zoom: fixed; } specifications specification status comment css device adaptationthe definition of '"user-zoom" descriptor' in that specification.
viewport-fit - CSS: Cascading Style Sheets
formal definition related at-rule@viewportinitial valueautocomputed valueas specified formal syntax auto | contain | cover
examples scaling viewport to fit device display @viewport { viewport-fit: cover; } specifications specification status comment css round display level 1the definition of '"viewport-fit" descriptor' in that specification.
width - CSS: Cascading Style Sheets
containing blockmax-width: refer to the width of the containing blockcomputed valueas each of the properties of the shorthand:min-width: the percentage as specified or the absolute lengthmax-width: 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 width @viewport { width: 500px; } specifications specification status comment css device adaptationthe definition of '"min-width" descriptor' in that specification.
zoom - CSS: Cascading Style Sheets
formal definition related at-rule@viewportinitial valueautopercentagesthe zoom factor itselfcomputed valueauto, or a non-negative number or percentage as specified formal syntax auto | <number> | <percentage>
examples setting viewport zoom factor @viewport { zoom: 2.0; } specifications specification status comment css device adaptationthe definition of '"zoom" descriptor' in that specification.
@viewport - CSS: Cascading Style Sheets
formal syntax @viewport { <group-rule-body> }
examples setting viewport size, zoom, and orientation @viewport { min-width: 640px; max-width: 800px; } @viewport { zoom: 0.75; min-zoom: 0.5; max-zoom: 0.9; } @viewport { orientation: landscape; } specifications specification status comment css round display level 1the definition of '@viewport' in that specification.
Adjacent sibling combinator - CSS: Cascading Style Sheets
/* 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.
Attribute selectors - CSS: Cascading Style Sheets
examples links css a { color: blue; } /* internal links, beginning with "#" */ a[href^="#"] { background-color: gold; } /* links with "example" anywhere in the url */ a[href*="example"] { background-color: silver; } /* links with "insensitive" anywhere in the url, regardless of capitalization */ a[href*="insensitive" i] { color: cyan; } /* links with "case" anywhere in the url, with matc...
CSS Fonts - CSS: Cascading Style Sheets
00px; margin: 0 auto; font-family: "helvetica neue", "arial", sans-serif; font-style: italic; font-weight: 100; font-variant-ligatures: normal; font-size: 2rem; letter-spacing: 1px; } <p>three hundred years ago<br> i thought i might get some sleep<br> i stretched myself out onna antique bed<br> an' my spirit did a midnite creep</p> the result is as follows: variable fonts
examples you can find a number of variable fonts
examples at v-fonts.com and axis-praxis.org; see also our variable fonts guide for more information and usage information.
Box alignment in CSS Grid Layout - CSS: Cascading Style Sheets
margin-left: auto; } .item2 { grid-area: b; } .item3 { grid-area: c; } .item4 { grid-area: d; } <div class="wrapper"> <div class="item1">item 1</div> <div class="item2">item 2</div> <div class="item3">item 3</div> <div class="item4">item 4</div> </div> you can see how the item is aligned by using the firefox grid highlighter: alignment and writing modes in all of these
examples i have been working in english, which is a left-to-right language.
CSS Grid Layout - CSS: Cascading Style Sheets
other layout methods layout using line-based placement grid template areas layout using named grid lines auto-placement in css grid layout box alignment in css grid layout css grid, logical values and writing modes css grid layout and accessibility css grid and progressive enhancement realising common layouts using css grid subgrid external resources css grid and ie11 (polyfill)
examples from jen simmons grid by example - a collection of usage
examples and video tutorials codrops grid reference firefox devtools css grid inspector css grid playground grid garden - a game for learning css grid specifications specification status comment css grid layout module level 2 working draft added subgrids.
Using CSS gradients - CSS: Cascading Style Sheets
in both
examples, the gradient is written twice: the first is the css images level 3 method of repeating the color for each stop and the second example is the css images level 4 multiple color stop method of including two color-stop-lengths in a linear-color-stop declaration.
CSS Positioned Layout - CSS: Cascading Style Sheets
reference css properties bottom clear float left position right top z-index guides understanding css z-index presents the notion of stacking context and explains how z-ordering works, with several
examples.
CSS Text Decoration - CSS: Cascading Style Sheets
examples .under { text-decoration: underline red; } .over { text-decoration: wavy overline lime; } .line { text-decoration: line-through; } .plain { text-decoration: none; } .underover { text-decoration: dashed underline overline; } .thick { text-decoration: solid underline purple 4px; } .blink { text-decoration: blink; } <p class="under">this text has a line underneath it.</p> <p c...
Class selectors - CSS: Cascading Style Sheets
<li> elements with class="spacious" */ li.spacious { margin: 2em; } /* all <li> elements with a class list that includes both "spacious" and "elegant" */ /* for example, class="elegant retro spacious" */ li.spacious.elegant { margin: 2em; } syntax .class_name { style properties } note that this is equivalent to the following attribute selector: [class~=class_name] { style properties }
examples css .red { color: #f33; } .yellow-bg { background: #ffa; } .fancy { font-weight: bold; text-shadow: 4px 4px 3px #77f; } html <p class="red">this paragraph has red text.</p> <p class="red yellow-bg">this paragraph has red text and a yellow background.</p> <p class="red fancy">this paragraph has red text and "fancy" styling.</p> <p>this is just a regular paragraph.</p> result sp...
Column combinator - CSS: Cascading Style Sheets
/* table cells that belong to the "selected" column */ col.selected || td { background: gray; } syntax column-selector || cell-selector { /* style properties */ }
examples html <table border="1"> <colgroup> <col span="2"/> <col class="selected"/> </colgroup> <tbody> <tr> <td>a <td>b <td>c </tr> <tr> <td colspan="2">d</td> <td>e</td> </tr> <tr> <td>f</td> <td colspan="2">g</td> </tr> </tbody> </table> css col.selected || td { background: gray; color: white; font-weight: bold; } result specifications s...
Comments - CSS: Cascading Style Sheets
/* comment */
examples /* a one-line comment */ /* a comment which stretches over several lines */ /* the comment below is used to disable specific styling */ /* span { color: blue; font-size: 1.5em; } */ notes the /* */ comment syntax is used for both single and multiline comments.
Descendant combinator - CSS: Cascading Style Sheets
syntax selector1 selector2 { /* property declarations */ }
examples css li { list-style-type: disc; } li li { list-style-type: circle; } html <ul> <li> <div>item 1</div> <ul> <li>subitem a</li> <li>subitem b</li> </ul> </li> <li> <div>item 2</div> <ul> <li>subitem a</li> <li>subitem b</li> </ul> </li> </ul> result specifications specification status comment selecto...
General sibling combinator - CSS: Cascading Style Sheets
/* paragraphs that are siblings of and subsequent to any image */ img ~ p { color: red; } syntax former_element ~ target_element { style properties }
examples css p ~ span { color: red; } html <span>this is not red.</span> <p>here is a paragraph.</p> <code>here is some code.</code> <span>and here is a red span!</span> <code>more code...</code> <span>and this is a red span!</span> result specifications specification status comment selectors level 4the definition of 'subsequent-sibling combinator' in that specification.
ID selectors - CSS: Cascading Style Sheets
/* the element with id="demo" */ #demo { border: red 2px solid; } syntax #id_value { style properties } note that syntactically (but not specificity-wise), this is equivalent to the following attribute selector: [id=id_value] { style properties }
examples css #identified { background-color: skyblue; } html <div id="identified">this div has a special id on it!</div> <div>this is just a regular div.</div> result specifications specification status comment selectors level 4the definition of 'id selectors' in that specification.
CSS reference - CSS: Cascading Style Sheets
style rule
examples strong { color: red; } div.menu-bar li:hover > ul { display: block; } for a beginner-level introduction to the syntax of selectors, see our guide on css selectors.
Specificity - CSS: Cascading Style Sheets
some
examples with a higher specificity: table td { height: 50px !important; } .mytable td { height: 50px !important; } #mytable td { height: 50px !important; } b) or add the same selector after the existing one: td { height: 50px !important; } c) or, preferably, rewrite the original rule to avoid the use of !important altogether.
Type selectors - CSS: Cascading Style Sheets
*/ a { color: red; } syntax element { style properties }
examples css span { background-color: skyblue; } html <span>here's a span with some text.</span> <p>here's a p with some text.</p> <span>here's a span with more text.</span> result specifications specification status comment selectors level 4the definition of 'type (tag name) selector' in that specification.
Universal selectors - CSS: Cascading Style Sheets
examples css * [lang^=en] { color: green; } *.warning { color: red; } *#maincontent { border: 1px solid blue; } .floating { float: left } /* automatically clear the next sibling after a floating element */ .floating + * { clear: left; } html <p class="warning"> <span lang="en-us">a green span</span> in a red paragraph.
<alpha-value> - CSS: Cascading Style Sheets
examples setting text color opacity here an alpha value is used to set partially transparent text: /* <rgba()> */ color: rgba(34, 12, 64, 0.6); color: rgba(34.0 12 64 / 60%); setting shape image threshold here an alpha value is used to determine which parts of an image are considered part of a shape: /* shape-image-threshold */ shape-image-threshold: 70%; shape-image-threshold: 0.7; specifications...
aspect-ratio - CSS: Cascading Style Sheets
formal definition initial valueautoapplies toall elements except inline boxes and internal ruby or table boxesinheritednocomputed valueas specifiedanimation typediscrete formal syntax auto | <ratio>
examples mapping width and height to aspect-ratio firefox has added an internal aspect-ratio property (in version 69 onwards) that applies to replaced elements and other related elements that accept width and height attributes.
attr() - CSS: Cascading Style Sheets
)where <type-or-unit> = string | color | url | integer | number | length | angle | time | frequency | cap | ch | em | ex | ic | lh | rlh | rem | vb | vi | vw | vh | vmin | vmax | mm | q | cm | in | pt | pc | px | deg | grad | rad | turn | ms | s | hz | khz | %
examples content property html <p data-foo="hello">world</p> css [data-foo]::before { content: attr(data-foo) " "; } result <color> value html <div class="background" data-background="lime">background expected to be red if your browser does not support advanced usage of attr()</div> css .background { height: 100vh; } .background { background-color: red; } .background[data-backgr...
backdrop-filter - CSS: Cascading Style Sheets
)where <alpha-value> = <number> | <percentage><hue> = <number> | <angle>
examples css .box { background-color: rgba(255, 255, 255, 0.3); border-radius: 5px; font-family: sans-serif; text-align: center; line-height: 1; -webkit-backdrop-filter: blur(10px); backdrop-filter: blur(10px); max-width: 50%; max-height: 50%; padding: 20px 40px; } html, body { height: 100%; width: 100%; } body { background-image: url(https://picsum.photos/id/1080/6858/4574), ...
border-block-color - CSS: Cascading Style Sheets
formal definition initial valuecurrentcolorapplies toall elementsinheritednocomputed valuecomputed coloranimation typediscrete formal syntax <'border-top-color'>{1,2}
examples border with vertical text html <div> <p class="exampletext">example text</p> </div> css div { background-color: yellow; width: 120px; height: 120px; } .exampletext { writing-mode: vertical-lr; border: 10px solid blue; border-block-color: red; } results specifications specification status comment css logical properties and values level 1the def...
border-block-style - CSS: Cascading Style Sheets
formal definition initial valuenoneapplies toall elementsinheritednocomputed valueas specifiedanimation typediscrete formal syntax <'border-top-style'>
examples dashed border with vertical text html <div> <p class="exampletext">example text</p> </div> css div { background-color: yellow; width: 120px; height: 120px; } .exampletext { writing-mode: vertical-lr; border: 5px solid blue; border-block-style: dashed; } results specifications specification status comment css logical properties and values level...
border-block-width - CSS: Cascading Style Sheets
formal definition initial valuemediumapplies toall elementsinheritednopercentageslogical-width of containing blockcomputed valueabsolute length; 0 if the border style is none or hiddenanimation typediscrete formal syntax <'border-top-width'>
examples border width with vertical text html <div> <p class="exampletext">example text</p> </div> css div { background-color: yellow; width: 120px; height: 120px; } .exampletext { writing-mode: vertical-lr; border: 1px solid blue; border-block-width: 5px; } results specifications specification status comment css logical properties and values level 1th...
border-block - CSS: Cascading Style Sheets
)where <alpha-value> = <number> | <percentage><hue> = <number> | <angle>
examples border with vertical text html <div> <p class="exampletext">example text</p> </div> css div { background-color: yellow; width: 120px; height: 120px; } .exampletext { writing-mode: vertical-rl; border-block: 5px dashed blue; } results specifications specification status comment css logical properties and values level 1the definition of 'border-bl...
border-end-end-radius - CSS: Cascading Style Sheets
it also applies to ::first-letter.inheritednopercentagesrefer to the corresponding dimension of the border boxcomputed valuetwo absolute <length>s or <percentage>sanimation typea length, percentage or calc(); formal syntax <length-percentage>{1,2}where <length-percentage> = <length> | <percentage>
examples border radius with vertical text html <div> <p class="exampletext">example</p> </div> css content div { background-color: rebeccapurple; width: 120px; height: 120px; border-end-end-radius: 10px; } .exampletext { writing-mode: vertical-rl; padding: 10px; background-color: #fff; border-end-end-radius: 10px; } results specifications specification status c...
border-end-start-radius - CSS: Cascading Style Sheets
it also applies to ::first-letter.inheritednopercentagesrefer to the corresponding dimension of the border boxcomputed valuetwo absolute <length>s or <percentage>sanimation typea length, percentage or calc(); formal syntax <length-percentage>{1,2}where <length-percentage> = <length> | <percentage>
examples border radius with vertical text html <div> <p class="exampletext">example</p> </div> css div { background-color: rebeccapurple; width: 120px; height: 120px; border-end-start-radius: 10px; } .exampletext { writing-mode: vertical-rl; padding: 10px; background-color: #fff; border-end-start-radius: 10px; } results specifications specification status comme...
border-inline-color - CSS: Cascading Style Sheets
formal definition initial valuecurrentcolorapplies toall elementsinheritednocomputed valuecomputed coloranimation typediscrete formal syntax <'border-top-color'>{1,2}
examples border color with vertical text html <div> <p class="exampletext">example text</p> </div> css div { background-color: yellow; width: 120px; height: 120px; } .exampletext { writing-mode: vertical-lr; border: 10px solid blue; border-inline-color: red; } results specifications specification status comment css logical properties and values level 1...
border-inline-style - CSS: Cascading Style Sheets
formal definition initial valuenoneapplies toall elementsinheritednocomputed valueas specifiedanimation typediscrete formal syntax <'border-top-style'>
examples html content <div> <p class="exampletext">example text</p> </div> css content div { background-color: yellow; width: 120px; height: 120px; } .exampletext { writing-mode: vertical-lr; border: 5px solid blue; border-inline-style: dashed; } specifications specification status comment css logical properties and values level 1the definition of 'borde...
border-inline-width - CSS: Cascading Style Sheets
formal definition initial valuemediumapplies toall elementsinheritednopercentageslogical-width of containing blockcomputed valueabsolute length; 0 if the border style is none or hiddenanimation typediscrete formal syntax <'border-top-width'>
examples html <div> <p class="exampletext">example text</p> </div> css div { background-color: yellow; width: 120px; height: 120px; } .exampletext { writing-mode: vertical-lr; border: 1px solid blue; border-inline-width: 5px 10px; } specifications specification status comment css logical properties and values level 1the definition of 'border-inline-width...
border-inline - CSS: Cascading Style Sheets
)where <alpha-value> = <number> | <percentage><hue> = <number> | <angle>
examples border with vertical text html <div> <p class="exampletext">example text</p> </div> css div { background-color: yellow; width: 120px; height: 120px; } .exampletext { writing-mode: vertical-rl; border-inline: 5px dashed blue; } results specifications specification status comment css logical properties and values level 1the definition of 'border-i...
border-start-end-radius - CSS: Cascading Style Sheets
it also applies to ::first-letter.inheritednopercentagesrefer to the corresponding dimension of the border boxcomputed valuetwo absolute <length>s or <percentage>sanimation typea length, percentage or calc(); formal syntax <length-percentage>{1,2}where <length-percentage> = <length> | <percentage>
examples border radius with vertical text html <div> <p class="exampletext">example</p> </div> css div { background-color: rebeccapurple; width: 120px; height: 120px; border-start-end-radius: 10px; } .exampletext { writing-mode: vertical-rl; padding: 10px; background-color: #fff; border-start-end-radius: 10px; } results specifications specification status comme...
border-start-start-radius - CSS: Cascading Style Sheets
it also applies to ::first-letter.inheritednopercentagesrefer to the corresponding dimension of the border boxcomputed valuetwo absolute <length>s or <percentage>sanimation typea length, percentage or calc(); formal syntax <length-percentage>{1,2}where <length-percentage> = <length> | <percentage>
examples border radius with vertical text html <div> <p class="exampletext">example</p> </div> css div { background-color: rebeccapurple; width: 120px; height: 120px; border-start-start-radius: 10px; } .exampletext { writing-mode: vertical-rl; padding: 10px; background-color: #fff; border-start-start-radius: 10px; } results specifications specification status c...
box-align - CSS: Cascading Style Sheets
formal definition initial valuestretchapplies toelements with a css display value of box or inline-boxinheritednocomputed valueas specifiedanimation typediscrete formal syntax start | center | end | baseline | stretch
examples setting box alignment <!doctype html> <html> <head> <title>css box-align example</title> <style> div.example { display: box; /* as specified */ display: -moz-box; /* mozilla */ display: -webkit-box; /* webkit */ /* make this box taller than the children, so there is room for the box-pack */ height: 400px; /* make this box wider than ...
box-direction - CSS: Cascading Style Sheets
formal definition initial valuenormalapplies toelements with a css display value of box or inline-boxinheritednocomputed valueas specifiedanimation typediscrete formal syntax normal | reverse | inherit
examples setting box direction .example { /* bottom-to-top layout */ -moz-box-direction: reverse; /* mozilla */ -webkit-box-direction: reverse; /* webkit */ box-direction: reverse; /* as specified */ } specifications not part of any standard.
box-flex-group - CSS: Cascading Style Sheets
formal definition initial value1applies toin-flow children of box elementsinheritednocomputed valueas specifiedanimation typediscrete formal syntax <integer>
examples simple usage example in the original flexbox spec, box-flex-group could be used to assign flex children to different groups to distribute flexible space between: article:nth-child(1) { -webkit-box-flex-group: 1; } article:nth-child(2) { -webkit-box-flex-group: 2; } this was only ever supported in webkit-based browsers, with a prefix, and in subsequent versions of the spec this functional...
box-flex - CSS: Cascading Style Sheets
formal definition initial value0applies toelements that are direct children of an element with a css display value of -moz-box or -moz-inline-box or -webkit-box or -webkit-inline-boxinheritednocomputed valueas specifiedanimation typediscrete formal syntax <number>
examples setting box-flex <!doctype html> <html> <head> <title>-moz-box-flex example</title> <style> div.example { display: -moz-box; display: -webkit-box; border: 1px solid black; width: 100%; } div.example > p:nth-child(1) { -moz-box-flex: 1; /* mozilla */ -webkit-box-flex: 1; /* webkit */ border: 1px solid bl...
box-lines - CSS: Cascading Style Sheets
formal definition initial valuesingleapplies tobox elementsinheritednocomputed valueas specifiedanimation typediscrete formal syntax single | multiple
examples simple usage example in the original version of the spec, box-lines allowed you to specify that you wanted your flex container's children to wrap onto multiple lines.
box-ordinal-group - CSS: Cascading Style Sheets
formal definition initial value1applies tochildren of box elementsinheritednocomputed valueas specifiedanimation typediscrete formal syntax <integer>
examples basic usage example in an older version of the spec, box-ordinal-group was included to allow you to change the display order of flex children inside a flex container: article:nth-child(1) { -webkit-box-ordinal-group: 2 -moz-box-ordinal-group: 2 box-ordinal-group: 2 } article:nth-child(2) { -webkit-box-ordinal-group: 1 -moz-box-ordinal-group: 1 box-ordinal-group: 1 } the modern fl...
box-orient - CSS: Cascading Style Sheets
formal definition initial valueinline-axis (horizontal in xul)applies toelements with a css display value of box or inline-boxinheritednocomputed valueas specifiedanimation typediscrete formal syntax horizontal | vertical | inline-axis | block-axis | inherit
examples setting horizontal box orientation here, he box-orient property will cause the two <p> sections in the example to display in the same line.
box-pack - CSS: Cascading Style Sheets
formal definition initial valuestartapplies toelements with a css display value of -moz-box, -moz-inline-box, -webkit-box or -webkit-inline-boxinheritednocomputed valueas specifiedanimation typediscrete formal syntax start | center | end | justify
examples div.example { border-style: solid; display: -moz-box; /* mozilla */ display: -webkit-box; /* webkit */ /* make this box taller than the children, so there is room for the box-pack */ height: 300px; /* make this box wide enough to show the contents are centered horizontally */ width: 300px; /* children should be oriented vertically */ -moz-box-orient: vertical; /* m...
break-after - CSS: Cascading Style Sheets
formal definition initial valueautoapplies toblock-level elementsinheritednocomputed valueas specifiedanimation typediscrete formal syntax auto | avoid | always | all | avoid-page | page | left | right | recto | verso | avoid-column | column | avoid-region | region
examples breaking into neat columns in the following example we have a container that contains an <h1> spanning all columns (achieved using column-span: all) and a series of <h2>s and paragraphs laid out in multiple columns using column-width: 200px.
break-before - CSS: Cascading Style Sheets
formal definition initial valueautoapplies toblock-level elementsinheritednocomputed valueas specifiedanimation typediscrete formal syntax auto | avoid | always | all | avoid-page | page | left | right | recto | verso | avoid-column | column | avoid-region | region
examples breaking into neat columns in the following example we have a container that contains an <h1> spanning all columns (achieved using column-span: all) and a series of <h2>s and paragraphs laid out in multiple columns using column-width: 200px.
break-inside - CSS: Cascading Style Sheets
a subset of values should be aliased as follows: page-break-inside break-inside auto auto avoid avoid formal definition initial valueautoapplies toblock-level elementsinheritednocomputed valueas specifiedanimation typediscrete formal syntax auto | avoid | avoid-page | avoid-column | avoid-region
examples avoiding breaking inside a figure in the following example we have a container that contains an <h1> spanning all columns (achieved using column-span: all) and a series of paragraphs laid out in multiple columns using column-width: 200px.
clip - CSS: Cascading Style Sheets
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: 536px; height: 350px; } #top-left, #middle, #bottom-right { position: absolute; top: 0; } #top-left { left: 360px; clip: rect(0 175px 113px 0); } #middle { left: 280px; clip: rect(119px 255px 229px 80px); } #bottom-right { left: 200px; clip: rect(235px 335px 345px 160px); } html <p ...
color-adjust - CSS: Cascading Style Sheets
formal definition initial valueeconomyapplies toall elementsinheritedyescomputed valueas specifiedanimation typediscrete formal syntax economy | exact
examples preserving low contrast in this example, a box is shown which uses a background-image and a translucent linear-gradient() function atop a black background color to have a dark blue gradient behind medium red text.
column-span - CSS: Cascading Style Sheets
formal definition initial valuenoneapplies toin-flow block-level elementsinheritednocomputed valueas specifiedanimation typediscrete formal syntax none | all
examples making a heading span columns in this example, the heading is made to span across all the columns of the article.
contain - CSS: Cascading Style Sheets
formal definition initial valuenoneapplies toall elementsinheritednocomputed valueas specifiedanimation typediscrete formal syntax none | strict | content | [ size | layout | style | paint ]
examples simple layout the markup below consists of a number of articles, each with content: <h1>my blog</h1> <article> <h2>heading of a nice article</h2> <p>content here.</p> </article> <article> <h2>another heading of another article</h2> <img src="graphic.jpg" alt="photo"> <p>more content here.</p> </article> each <article> and <img> is given a border, and the images are floated: img { ...
content - CSS: Cascading Style Sheets
ge><hue> = <number> | <angle><linear-color-stop> = <color> <color-stop-length>?<linear-color-hint> = <length-percentage><length-percentage> = <length> | <percentage><angular-color-stop> = <color> && <color-stop-angle>?<angular-color-hint> = <angle-percentage>where <color-stop-length> = <length-percentage>{1,2}<color-stop-angle> = <angle-percentage>{1,2}<angle-percentage> = <angle> | <percentage>
examples headings and quotes this example inserts quotation marks around quotes, and adds the word "chapter" before headings.
counter-set - CSS: Cascading Style Sheets
]+ | none
examples setting named counters h1 { counter-set: chapter section 1 page; /* sets the chapter and page counters to 0, and the section counter to 1 */ } specifications specification status comment css lists module level 3the definition of 'counter-set' in that specification.
counter() - CSS: Cascading Style Sheets
)where <counter-style> = <counter-style-name> | symbols()where <counter-style-name> = <custom-ident>
examples default value compared to upper roman html <ol> <li></li> <li></li> <li></li> </ol> css ol { counter-reset: listcounter; } li { counter-increment: listcounter; } li::after { content: "[" counter(listcounter) "] == [" counter(listcounter, upper-roman) "]"; } result decimal-leading-zero compared to lower-alpha html <ol> <li></li> <li></li> <li></li> </ol>...
counters() - CSS: Cascading Style Sheets
)where <counter-style> = <counter-style-name> | symbols()where <counter-style-name> = <custom-ident>
examples default value compared to upper roman html <ol> <li> <ol> <li></li> <li></li> <li></li> </ol> </li> <li></li> <li></li> <li> <ol> <li></li> <li> <ol> <li></li> <li></li> <li></li> </ol> </li> </ol> </li> </ol> css ol { counter-reset: listcounter;...
cross-fade() - CSS: Cascading Style Sheets
, <angular-color-stop>where <linear-color-stop> = <color> <color-stop-length>?<linear-color-hint> = <length-percentage><length-percentage> = <length> | <percentage><angular-color-stop> = <color> && <color-stop-angle>?<angular-color-hint> = <angle-percentage>where <color-stop-length> = <length-percentage>{1,2}<color-stop-angle> = <angle-percentage>{1,2}<angle-percentage> = <angle> | <percentage>
examples older syntax for cross-fade html <div class="crossfade"></div> css .crossfade { width: 300px; height: 300px; background-image: -webkit-cross-fade( url('https://mdn.mozillademos.org/files/8543/br.png'), url('https://mdn.mozillademos.org/files/8545/tr.png'), 75%); background-image: cross-fade( url('https://mdn.mozillademos.org/files/8543/br.png')...
<custom-ident> - CSS: Cascading Style Sheets
examples valid identifiers nono79 a mix of alphanumeric characters and numbers ground-level a mix of alphanumeric characters and a dash -test a dash followed by alphanumeric characters _internal an underscore followed by alphanumeric characters \22 toto a unicode character followed by a sequence of alphanumeric characters bili\.bob a correctly escaped...
<dimension> - CSS: Cascading Style Sheets
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.
<display-box> - CSS: Cascading Style Sheets
more accessible markup with display: contents | hidde de vries display: contents is not a css reset | adrian roselli
examples in this first example, the paragraph with a class of secret is set to display: none; the box and any content is now not rendered.
<display-listitem> - CSS: Cascading Style Sheets
examples html <div class="fake-list">i will display as a list item</div> css .fake-list { display: list-item; list-style-position: inside; } result specifications specification status css display module level 3the definition of 'display-listitem' in that specification.
<display-outside> - CSS: Cascading Style Sheets
examples in the following example, span elements (normally displayed as inline elements) are set to display: block and so break onto new lines and expand to fill their container in the inline dimension.
env() - CSS: Cascading Style Sheets
)
examples the below example makes use of the optional second parameter of env(), which allows you to provide a fallback value in case the environment variable is not available.
<filter-function> - CSS: Cascading Style Sheets
examples filter function comparison this example provides a simple graphic, along with a select menu to allow you to choose between the different types of filter function, and a slider to allow you to vary the values used inside the filter function.
<flex> - CSS: Cascading Style Sheets
examples 1fr /* using an integer value */ 2.5fr /* using a float value */ specifications specification status comment css grid layoutthe definition of '<flex>' in that specification.
font-language-override - CSS: Cascading Style Sheets
it also applies to ::first-letter and ::first-line.inheritedyescomputed valueas specifiedanimation typediscrete formal syntax normal | <string>
examples using danish glyphs html <p class="para1">default language setting.</p> <p class="para2">this is a string with the <code>font-language-override</code> set to danish.</p> css p.para1 { font-language-override: normal; } p.para2 { font-language-override: "dan"; } result specifications specification status comment css fonts module level 4the definition of '...
font-size-adjust - CSS: Cascading Style Sheets
it also applies to ::first-letter and ::first-line.inheritedyescomputed valueas specifiedanimation typea number formal syntax none | <number>
examples adjusting lower-case letter sizes html <p class="times">this text uses the times font (10px), which is hard to read in small sizes.</p> <p class="verdana">this text uses the verdana font (10px), which has relatively large lowercase letters.</p> <p class="adjtimes">this is the 10px times, but now adjusted to the same aspect ratio as the verdana.</p> css .times { font-family: times, serif; ...
font-smooth - CSS: Cascading Style Sheets
formal definition initial valueautoapplies toall elementsinheritedyescomputed valueas specifiedanimation typediscrete formal syntax auto | never | always | <absolute-size> | <length>where <absolute-size> = xx-small | x-small | small | medium | large | x-large | xx-large | xxx-large
examples basic usage example the following example shows the safari/chromium and firefox equivalents that turn on font-smoothing on macos.
font-stretch - CSS: Cascading Style Sheets
it also applies to ::first-letter and ::first-line.inheritedyescomputed valueas specifiedanimation typea font stretch formal syntax <font-stretch-absolute>where <font-stretch-absolute> = normal | ultra-condensed | extra-condensed | condensed | semi-condensed | semi-expanded | expanded | extra-expanded | ultra-expanded | <percentage>
examples setting font stretch percentages note that this example will only work in browsers that support <percentage> values.
font-variant-alternates - CSS: Cascading Style Sheets
st-letter and ::first-line.inheritedyescomputed valueas specifiedanimation typediscrete formal syntax normal | [ stylistic( <feature-value-name> ) | historical-forms | styleset( <feature-value-name># ) | character-variant( <feature-value-name># ) | swash( <feature-value-name> ) | ornaments( <feature-value-name> ) | annotation( <feature-value-name> ) ]where <feature-value-name> = <custom-ident>
examples html <p>firefox rocks!</p> <p class="variant">firefox rocks!</p> css @font-feature-values "leitura display swashes" { @swash { fancy: 1 } } p { font-size: 1.5rem; } .variant { font-family: leitura display swashes; font-variant-alternates: swash(fancy); } result note: you need to install the opentype font leitura display swashes for this example to work.
font-variant-east-asian - CSS: Cascading Style Sheets
it also applies to ::first-letter and ::first-line.inheritedyescomputed valueas specifiedanimation typediscrete formal syntax normal | [ <east-asian-variant-values> || <east-asian-width-values> || ruby ]where <east-asian-variant-values> = [ jis78 | jis83 | jis90 | jis04 | simplified | traditional ]<east-asian-width-values> = [ full-width | proportional-width ]
examples setting east asian glyph variants this example require font "yu gothic" installed in your os, other fonts may not support opentype features.
font-variant-position - CSS: Cascading Style Sheets
it also applies to ::first-letter and ::first-line.inheritedyescomputed valueas specifiedanimation typediscrete formal syntax normal | sub | super
examples setting superscript and subscript forms html <p class="normal">normal!</p> <p class="super">super!</p> <p class="sub">sub!</p> css p { display: inline; } .normal { font-variant-position: normal; } .super { font-variant-position: super; } .sub { font-variant-position: sub; } result specifications specification status comment css fonts module level...
<frequency-percentage> - CSS: Cascading Style Sheets
examples valid percentage values 90% positive percentage +90% positive percentage with leading + -90% negative percentage — not valid for all properties that use percentages invalid percentage values 90 % no space is allowed between the number and the unit valid frequency values 12hz positive integer 4.3hz non-integer 14khz the unit is case-insensitive, though non-si capitalization is no...
hanging-punctuation - CSS: Cascading Style Sheets
formal definition initial valuenoneapplies toall elementsinheritedyescomputed valueas specifiedanimation typediscrete formal syntax none | [ first | [ force-end | allow-end ] | last ]
examples setting opening and closing quotes to hang html <p>“lorem ipsum dolor sit amet, consectetur adipiscing elit.
ident - CSS: Cascading Style Sheets
examples valid identifiers nono79 a mix of alphanumeric characters and numbers ground-level a mix of alphanumeric characters and a dash -test a dash followed by alphanumeric characters --toto a custom-property like identifier _internal an underscore followed by alphanumeric characters \22 toto a unicode character followed by a sequence of alphanumeric characters bili\.bob a ...
image-orientation - CSS: Cascading Style Sheets
flip ]
examples orienting image from image data 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 ...
image-rendering - CSS: Cascading Style Sheets
formal definition initial valueautoapplies toall elementsinheritedyescomputed valueas specifiedanimation typediscrete formal syntax auto | crisp-edges | pixelated
examples setting image scaling algorithms in practical use, the pixelated and crisp-edges rules can be combined to provide some fallback for each other.
image-set() - CSS: Cascading Style Sheets
examples background-image: image-set( "cat.png" 1x, "cat-2x.png" 2x, "cat-print.png" 600dpi); this example shows how to use image-set() to provide two alternative background-image options, chosen depending on the resolution needed: a normal version and a high-resolution version.
<image> - CSS: Cascading Style Sheets
mdn understanding wcag, guideline 1.1 explanations understanding success criterion 1.1.1 | w3c understanding wcag 2.0
examples valid images url(test.jpg) /* a <url>, as long as test.jpg is an actual image */ linear-gradient(blue, red) /* a <gradient> */ element(#realid) /* a part of the webpage, referenced with the element() function, if "realid" is an existing id on the page */ image(ltr 'arrow.png#xywh=0,0,16,16', red) /* a section 1...
image() - CSS: Cascading Style Sheets
examples directionally-sensitive images <ul> <li dir="ltr">bullet is a right facing arrow on the left</li> <li dir="rtl">bullet is the same arrow, flipped to point left.</li> </ul> ul { list-style-image: image(ltr 'https://mdn.mozillademos.org/files/16412/rightarrow.png'); } in the left-to-right list items — those with dir="ltr" set on the element itself or inheriting the directionality from a...
ime-mode - CSS: Cascading Style Sheets
formal definition initial valueautoapplies totext fieldsinheritednocomputed valueas specifiedanimation typediscrete formal syntax auto | normal | active | inactive | disabled
examples disabling input method support this example disables input method support for a form field.
inherit - CSS: Cascading Style Sheets
examples exclude selected elements from a rule /* make second-level headers green */ h2 { color: green; } /* ...but leave those in the sidebar alone so they use their parent's color */ #sidebar h2 { color: inherit; } in this example the h2 elements inside the sidebar might be different colors.
initial-letter-align - CSS: Cascading Style Sheets
formal definition initial valueautoapplies to::first-letter pseudo-elements and inline-level first child of a block containerinheritednocomputed valueas specifiedanimation typediscrete formal syntax [ auto | alphabetic | hanging | ideographic ]
examples aligning initial letter html <p class="auto ">initial letter - auto</p> <p class="alphabetic">initial letter - alphabetic</p> <p class="hanging">initial letter - hanging</p> <p class="ideographic">initial letter - ideographic</p> css .auto { -webkit-initial-letter-align: auto; initial-letter-align: auto; } .alphabetic { -webkit-initial-letter-align: alphabetic; initial-letter-align...
initial-letter - CSS: Cascading Style Sheets
]
examples setting initial letter size html <p class="normal">initial letter is normal</p> <p class="onefive">initial letter occupies 1.5 lines</p> <p class="three">initial letter occupies 3 lines</p> css .normal { -webkit-initial-letter: normal; initial-letter: normal; } .onefive { -webkit-initial-letter: 1.5; initial-letter: 1.5; } .three { -webkit-initial-letter: 3.0; initial-letter: 3...
initial - CSS: Cascading Style Sheets
examples using initial to reset color for an element html <p> <span>this text is red.</span> <em>this text is in the initial color (typically black).</em> <span>this is red again.</span> </p> css p { color: red; } em { color: initial; } result specifications specification status comment css cascading and inheritance level 4the definition of 'initial' in that spec...
inset-block-end - CSS: Cascading Style Sheets
formal definition initial valueautoapplies topositioned elementsinheritednopercentageslogical-height of containing blockcomputed valuesame as box offsets: top, right, bottom, left properties except that directions are logicalanimation typea length, percentage or calc(); formal syntax <'top'>
examples setting block end offset html <div> <p class="exampletext">example text</p> </div> css div { background-color: yellow; width: 120px; height: 120px; } .exampletext { writing-mode: vertical-rl; position: relative; inset-block-end: 20px; background-color: #c8c800; } result specifications specification status comment css logical properties and v...
inset-block-start - CSS: Cascading Style Sheets
formal definition initial valueautoapplies topositioned elementsinheritednopercentageslogical-height of containing blockcomputed valuesame as box offsets: top, right, bottom, left properties except that directions are logicalanimation typea length, percentage or calc(); formal syntax <'top'>
examples setting block start offset html <div> <p class="exampletext">example text</p> </div> css div { background-color: yellow; width: 120px; height: 120px; } .exampletext { writing-mode: vertical-lr; position: relative; inset-block-start: 20px; background-color: #c8c800; } specifications specification status comment css logical properties and value...
inset-block - CSS: Cascading Style Sheets
formal definition initial valueautoapplies topositioned elementsinheritednopercentageslogical-height of containing blockcomputed valuesame as box offsets: top, right, bottom, left properties except that directions are logicalanimation typea length, percentage or calc(); formal syntax <'top'>{1,2}
examples setting block start and end offsets html <div> <p class="exampletext">example text</p> </div> css div { background-color: yellow; width: 120px; height: 120px; } .exampletext { writing-mode: vertical-lr; position: relative; inset-block: 20px 50px; background-color: #c8c800; } result specifications specification status comment css logical prop...
inset-inline-end - CSS: Cascading Style Sheets
formal definition initial valueautoapplies topositioned elementsinheritednopercentageslogical-width of containing blockcomputed valuesame as box offsets: top, right, bottom, left properties except that directions are logicalanimation typea length, percentage or calc(); formal syntax <'top'>
examples setting inline end offset html <div> <p class="exampletext">example text</p> </div> css div { background-color: yellow; width: 120px; height: 120px; } .exampletext { writing-mode: vertical-rl; position: relative; inset-inline-end: 20px; background-color: #c8c800; } result specifications specification status comment css logical properties and...
inset-inline-start - CSS: Cascading Style Sheets
formal definition initial valueautoapplies topositioned elementsinheritednopercentageslogical-width of containing blockcomputed valuesame as box offsets: top, right, bottom, left properties except that directions are logicalanimation typea length, percentage or calc(); formal syntax <'top'>
examples setting inline start offset html <div> <p class="exampletext">example text</p> </div> css div { background-color: yellow; width: 120px; height: 120px; } .exampletext { writing-mode: vertical-lr; position: relative; inset-inline-start: 20px; background-color: #c8c800; } result specifications specification status comment css logical properties...
inset-inline - CSS: Cascading Style Sheets
formal definition initial valueautoapplies topositioned elementsinheritednopercentageslogical-width of containing blockcomputed valuesame as box offsets: top, right, bottom, left properties except that directions are logicalanimation typea length, percentage or calc(); formal syntax <'top'>{1,2}
examples setting inline start and end offsets html <div> <p class="exampletext">example text</p> </div> css div { background-color: yellow; width: 120px; height: 120px; } .exampletext { writing-mode: vertical-lr; position: relative; inset-inline: 20px 50px; background-color: #c8c800; } result specifications specification status comment css logical pr...
inset - CSS: Cascading Style Sheets
formal definition initial valueautoapplies topositioned elementsinheritednopercentageslogical-height of containing blockcomputed valuesame as box offsets: top, right, bottom, left properties except that directions are logicalanimation typea length, percentage or calc(); formal syntax <'top'>{1,4}
examples setting offsets for an element html <div> <span class="exampletext">example text</span> </div> css div { background-color: yellow; width: 150px; height: 120px; position: relative; } .exampletext { writing-mode: sideways-rl; position: absolute; inset: 20px 40px 30px 10px; background-color: #c8c800; } result specifications specification status comment ...
<integer> - CSS: Cascading Style Sheets
examples valid integers 12 positive integer (without a leading + sign) +123 positive integer (with a leading + sign) -456 negative integer 0 zero +0 zero, with a leading + -0 zero, with a leading - invalid integers 12.0 this is a <number>, not an <integer>, though it represents an integer.
line-break - CSS: Cascading Style Sheets
formal definition initial valueautoapplies toall elementsinheritedyescomputed valueas specifiedanimation typediscrete formal syntax auto | loose | normal | strict | anywhere
examples setting text wrapping see whether the text is wrapped before "々", "ぁ" and "。".
line-height-step - CSS: Cascading Style Sheets
formal definition initial value0applies toblock containersinheritedyescomputed valueabsolute <length>animation typediscrete formal syntax <length>
examples setting step unit for line box height in the following example, the height of line box in each paragraph is rounded up to the step unit.
margin-block - CSS: Cascading Style Sheets
formal definition initial value0applies tosame as margininheritednopercentagesdepends on layout modelcomputed valueif specified as a length, the corresponding absolute length; if specified as a percentage, the specified value; otherwise, autoanimation typediscrete formal syntax <'margin-left'>{1,2}
examples setting block start and end margins html <div> <p class="exampletext">example text</p> </div> css div { background-color: yellow; width: 120px; height: 120px; } .exampletext { writing-mode: vertical-rl; margin-block: 20px 40px; background-color: #c8c800; } result specifications specification status comment css logical properties and values lev...
margin-inline - CSS: Cascading Style Sheets
formal definition initial value0applies tosame as margininheritednopercentagesdepends on layout modelcomputed valueif specified as a length, the corresponding absolute length; if specified as a percentage, the specified value; otherwise, autoanimation typediscrete formal syntax <'margin-left'>{1,2}
examples setting inline start and end margins html <div> <p class="exampletext">example text</p> </div> css div { background-color: yellow; width: 120px; height: 120px; } .exampletext { writing-mode: vertical-rl; margin-inline: 20px 40px; background-color: #c8c800; } result specifications specification status comment css logical properties and values l...
margin-trim - CSS: Cascading Style Sheets
it also applies to ::first-letter and ::first-line.inheritednocomputed valueas specifiedanimation typediscrete formal syntax none | in-flow | all
examples basic usage once support is implemented for this property, it will probably work like so: when you've got a container with some inline children and you want to put a margin between each child but not have it interfere with the spacing at the end of the row, you might do something like this: article { background-color: red; margin: 20px; padding: 20px; display: inline-block; } article...
mask-border-mode - CSS: Cascading Style Sheets
formal definition initial valuealphaapplies toall elements; in svg, it applies to container elements excluding the defs element and all graphics elementsinheritednocomputed valueas specifiedanimation typediscrete formal syntax luminance | alpha
examples basic usage this property doesn't yet seem to have support anywhere.
mask-border-outset - CSS: Cascading Style Sheets
formal definition initial value0applies toall elements; in svg, it applies to container elements excluding the defs element and all graphics elementsinheritednocomputed valueas specified, but with relative lengths converted into absolute lengthsanimation typediscrete formal syntax [ <length> | <number> ]{1,4}
examples basic usage this property doesn't appear to be supported anywhere yet.
mask-border-repeat - CSS: Cascading Style Sheets
formal definition initial valuestretchapplies toall elements; in svg, it applies to container elements excluding the defs element and all graphics elementsinheritednocomputed valueas specifiedanimation typediscrete formal syntax [ stretch | repeat | round | space ]{1,2}
examples basic usage this property doesn't appear to be supported anywhere yet.
mask-border-slice - CSS: Cascading Style Sheets
formal definition initial value0applies toall elements; in svg, it applies to container elements excluding the defs element and all graphics elementsinheritednopercentagesrefer to size of the mask border imagecomputed valueas specifiedanimation typediscrete formal syntax <number-percentage>{1,4} fill?where <number-percentage> = <number> | <percentage>
examples basic usage this property doesn't appear to be supported anywhere yet.
mask-border-source - CSS: Cascading Style Sheets
ge><hue> = <number> | <angle><linear-color-stop> = <color> <color-stop-length>?<linear-color-hint> = <length-percentage><length-percentage> = <length> | <percentage><angular-color-stop> = <color> && <color-stop-angle>?<angular-color-hint> = <angle-percentage>where <color-stop-length> = <length-percentage>{1,2}<color-stop-angle> = <angle-percentage>{1,2}<angle-percentage> = <angle> | <percentage>
examples basic usage this property doesn't appear to be supported anywhere yet.
mask-border-width - CSS: Cascading Style Sheets
ements; in svg, it applies to container elements excluding the defs element and all graphics elementsinheritednopercentagesrelative to width/height of the mask border image areacomputed valueas specified, but with relative lengths converted into absolute lengthsanimation typediscrete formal syntax [ <length-percentage> | <number> | auto ]{1,4}where <length-percentage> = <length> | <percentage>
examples basic usage this property doesn't appear to be supported anywhere yet.
mask-border - CSS: Cascading Style Sheets
| <'mask-border-repeat'> | <'mask-border-mode'>
examples setting a bitmap-based mask border in this example, we will mask an element's border with a diamond pattern.
mask-clip - CSS: Cascading Style Sheets
al valueborder-boxapplies toall elements; in svg, it applies to container elements excluding the defs element and all graphics elementsinheritednocomputed valueas specifiedanimation typediscrete formal syntax [ <geometry-box> | no-clip ]#where <geometry-box> = <shape-box> | fill-box | stroke-box | view-boxwhere <shape-box> = <box> | margin-boxwhere <box> = border-box | padding-box | content-box
examples clipping a mask to the border box css #masked { width: 100px; height: 100px; background-color: #8cffa0; margin: 20px; border: 20px solid #8ca0ff; padding: 20px; mask-image: url(https://mdn.mozillademos.org/files/12668/mdn.svg); mask-size: 100% 100%; mask-clip: border-box; /* can be changed in the live sample */ } html <div id="masked"> </div> <select id="clipbox"> <opti...
mask-composite - CSS: Cascading Style Sheets
formal definition initial valueaddapplies toall elements; in svg, it applies to container elements excluding the defs element and all graphics elementsinheritednocomputed valueas specifiedanimation typediscrete formal syntax <compositing-operator>#where <compositing-operator> = add | subtract | intersect | exclude
examples compositing mask layers with addition css #masked { width: 100px; height: 100px; background-color: #8cffa0; mask-image: url(https://mdn.mozillademos.org/files/12668/mdn.svg), url(https://mdn.mozillademos.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="composit...
mask-image - CSS: Cascading Style Sheets
ge><hue> = <number> | <angle><linear-color-stop> = <color> <color-stop-length>?<linear-color-hint> = <length-percentage><length-percentage> = <length> | <percentage><angular-color-stop> = <color> && <color-stop-angle>?<angular-color-hint> = <angle-percentage>where <color-stop-length> = <length-percentage>{1,2}<color-stop-angle> = <angle-percentage>{1,2}<angle-percentage> = <angle> | <percentage>
examples setting a mask image with a url html <div id="masked"></div> css #masked { width: 100px; height: 100px; background-color: #8cffa0; -webkit-mask-image: url(https://mdn.mozillademos.org/files/12676/star.svg); mask-image: url(https://mdn.mozillademos.org/files/12676/star.svg); } result specifications specification status comment css masking module leve...
mask-mode - CSS: Cascading Style Sheets
formal definition initial valuematch-sourceapplies toall elements; in svg, it applies to container elements excluding the defs element and all graphics elementsinheritednocomputed valueas specifiedanimation typediscrete formal syntax <masking-mode>#where <masking-mode> = alpha | luminance | match-source
examples using alpha mask mode css #masked { width: 227px; height: 200px; background: blue linear-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> <opt...
mask-origin - CSS: Cascading Style Sheets
nition initial valueborder-boxapplies toall elements; in svg, it applies to container elements excluding the defs element and all graphics elementsinheritednocomputed valueas specifiedanimation typediscrete formal syntax <geometry-box>#where <geometry-box> = <shape-box> | fill-box | stroke-box | view-boxwhere <shape-box> = <box> | margin-boxwhere <box> = border-box | padding-box | content-box
examples setting mask origin to border-box css #masked { width: 100px; height: 100px; margin: 10px; border: 10px solid blue; background-color: #8cffa0; padding: 10px; mask-image: url(https://mdn.mozillademos.org/files/12676/star.svg); mask-origin: border-box; /* can be changed in the live sample */ } html <div id="masked"> </div> <select id="origin"> <option value="content-box">co...
mask-position - CSS: Cascading Style Sheets
| [ [ left | right ] <length-percentage> ] && [ [ top | bottom ] <length-percentage> ] ]where <length-percentage> = <length> | <percentage>
examples setting mask position css #wrapper { border: 1px solid black; width: 250px; height: 250px; } #masked { width: 250px; height: 250px; background: blue linear-gradient(red, blue); mask-image: url(https://mdn.mozillademos.org/files/12676/star.svg); mask-repeat: no-repeat; mask-position: top right; /* can be changed in the live sample */ margin-bottom: 10px; } html <div id=...
mask-repeat - CSS: Cascading Style Sheets
formal definition initial valueno-repeatapplies toall elements; in svg, it applies to container elements excluding the defs element and all graphics elementsinheritednocomputed valueconsists of two keywords, one per dimensionanimation typediscrete formal syntax <repeat-style>#where <repeat-style> = repeat-x | repeat-y | [ repeat | space | round | no-repeat ]{1,2}
examples setting repeat for a single mask css #masked { width: 250px; height: 250px; background: blue linear-gradient(red, blue); mask-image: url(https://mdn.mozillademos.org/files/12676/star.svg); mask-repeat: repeat; /* can be changed in the live sample */ margin-bottom: 10px; } html content <div id="masked"> </div> <select id="repetition"> <option value="repeat-x">repeat-x</option>...
mask-size - CSS: Cascading Style Sheets
lies to container elements excluding the defs element and all graphics elementsinheritednocomputed valueas specified, but with relative lengths converted into absolute lengthsanimation typerepeatable list of simple list of length, percentage, or calc formal syntax <bg-size>#where <bg-size> = [ <length-percentage> | auto ]{1,2} | cover | containwhere <length-percentage> = <length> | <percentage>
examples setting mask size as a percentage css #masked { width: 200px; height: 200px; background: blue linear-gradient(red, blue); -webkit-mask-image: url(https://mdn.mozillademos.org/files/12668/mdn.svg); mask-image: url(https://mdn.mozillademos.org/files/12668/mdn.svg); -webkit-mask-size: 50%; mask-size: 50%; /* can be changed in the live sample */ margin-bottom: 10px; } html <div...
mask-type - CSS: Cascading Style Sheets
formal definition initial valueluminanceapplies to<mask> elementsinheritednocomputed valueas specifiedanimation typediscrete formal syntax luminance | alpha
examples setting an alpha mask html <div class="redsquare"></div> <svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="0" height="0"> <defs> <mask id="m" maskcontentunits="objectboundingbox" style="mask-type:alpha"> <rect x=".1" y=".1" width=".8" height=".8" fill="red" fill-opacity="0.7"/> </mask> </defs> </svg> c...
mask - CSS: Cascading Style Sheets
op>where <alpha-value> = <number> | <percentage><hue> = <number> | <angle><linear-color-stop> = <color> <color-stop-length>?<linear-color-hint> = <length-percentage><angular-color-stop> = <color> && <color-stop-angle>?<angular-color-hint> = <angle-percentage>where <color-stop-length> = <length-percentage>{1,2}<color-stop-angle> = <angle-percentage>{1,2}<angle-percentage> = <angle> | <percentage>
examples masking an image .target { mask: url(#c1) luminance; } .anothertarget { mask: url(resources.svg#c1) 50px 30px/10px 10px repeat-x exclude; } specifications specification status comment css masking module level 1the definition of 'mask' in that specification.
offset-anchor - CSS: Cascading Style Sheets
| [ [ left | right ] <length-percentage> ] && [ [ top | bottom ] <length-percentage> ] ]where <length-percentage> = <length> | <percentage>
examples setting various offset-anchor values in the following example, we have three <div> elements nested in <section> elements.
offset-distance - CSS: Cascading Style Sheets
formal definition initial value0applies totransformable elementsinheritednopercentagesrefer to the total path lengthcomputed valuefor <length> the absolute value, otherwise a percentageanimation typea length, percentage or calc(); formal syntax <length-percentage>where <length-percentage> = <length> | <percentage>
examples using offset-distance in an animation the motion aspect in css motion path typically comes from animating the offset-distance property.
offset-path - CSS: Cascading Style Sheets
| [ [ left | right ] <length-percentage> ] && [ [ top | bottom ] <length-percentage> ] ]<box> = border-box | padding-box | content-box
examples animating an element with offset-path the offset-path properties in the css code sample defines a motion path that is identical to the <path> element in the svg.
offset-position - CSS: Cascading Style Sheets
| [ [ left | right ] <length-percentage> ] && [ [ top | bottom ] <length-percentage> ] ]where <length-percentage> = <length> | <percentage>
examples setting initial offset position <div id="motion-demo"></div> #motion-demo { offset-path: path('m20,20 c20,100 200,0 200,100'); offset-position: left top; animation: move 3000ms infinite alternate ease-in-out; width: 40px; height: 40px; background: cyan; } @keyframes move { 0% { offset-distance: 0%; } 100% { offset-distance: 100%; } } specifications spec...
offset-rotate - CSS: Cascading Style Sheets
formal definition initial valueautoapplies totransformable elementsinheritednocomputed valueas specifiedanimation typeas <angle>, <basic-shape> or <path()> formal syntax [ auto | reverse ] | <angle>
examples setting element orientation along its offset path html <div></div> <div></div> <div></div> css div { width: 40px; height: 40px; background: #2bc4a2; margin: 20px; clip-path: polygon(0% 0%, 70% 0%, 100% 50%, 70% 100%, 0% 100%, 30% 50%); animation: move 5000ms infinite alternate ease-in-out; offset-path: path('m20,20 c20,50 180,-10 180,20'); } div:nth-child(1) { offset-rotate:...
offset - CSS: Cascading Style Sheets
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 ...
orphans - CSS: Cascading Style Sheets
formal definition initial value2applies toblock container elementsinheritedyescomputed valueas specifiedanimation typediscrete formal syntax <integer>
examples setting a minimum orphan size of three lines html <div> <p>this is the first paragraph containing some text.</p> <p>this is the second paragraph containing some more text than the first one.
overflow-anchor - CSS: Cascading Style Sheets
formal definition initial valueautoapplies toall elementsinheritednocomputed valueas specifiedanimation typediscrete formal syntax auto | none
examples prevent scroll anchoring to prevent scroll anchoring in a document, use the overflow-anchor property.
overflow-block - CSS: Cascading Style Sheets
formal definition initial valueautoapplies toblock-containers, flex containers, and grid containersinheritednocomputed valueas specified, except with visible/clip computing to auto/hidden respectively if one of overflow-x or overflow-y is neither visible nor clipanimation typediscrete formal syntax visible | hidden | clip | scroll | auto
examples html <ul> <li><code>overflow-block:hidden</code> — hides the text outside the box <div id="div1"> lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
overflow-inline - CSS: Cascading Style Sheets
formal definition initial valueautoapplies toblock-containers, flex containers, and grid containersinheritednocomputed valueas specified, except with visible/clip computing to auto/hidden respectively if one of overflow-x or overflow-y is neither visible nor clipanimation typediscrete formal syntax visible | hidden | clip | scroll | auto
examples setting inline overflow behavior html <ul> <li><code>overflow-inline:hidden</code> — hides the text outside the box <div id="div1"> abcdefghijklmopqrstuvwxyzabcdefghijklmopqrstuvwxyz </div> </li> <li><code>overflow-inline:scroll</code> — always adds a scrollbar <div id="div2"> abcdefghijklmopqrstuvwxyzabcdefghijklmopqrstuvwxyz </div> </li> <li><code>...
overscroll-behavior-block - CSS: Cascading Style Sheets
formal definition initial valueautoapplies tonon-replaced block-level elements and non-replaced inline-block elementsinheritednocomputed valueas specifiedanimation typediscrete formal syntax contain | none | auto
examples preventing block overscrolling in this demo we have two block-level boxes, one inside the other.
overscroll-behavior-inline - CSS: Cascading Style Sheets
formal definition initial valueautoapplies tonon-replaced block-level elements and non-replaced inline-block elementsinheritednocomputed valueas specifiedanimation typediscrete formal syntax contain | none | auto
examples preventing inline overscrolling in this demo we have two block-level boxes, one inside the other.
overscroll-behavior-x - CSS: Cascading Style Sheets
formal definition initial valueautoapplies tonon-replaced block-level elements and non-replaced inline-block elementsinheritednocomputed valueas specifiedanimation typediscrete formal syntax contain | none | auto
examples preventing an underlying element from scrolling horizontally in our simple overscroll-behavior-x example (see source code also), we have two block-level boxes, one inside the other.
overscroll-behavior-y - CSS: Cascading Style Sheets
formal definition initial valueautoapplies tonon-replaced block-level elements and non-replaced inline-block elementsinheritednocomputed valueas specifiedanimation typediscrete formal syntax contain | none | auto
examples preventing an underlying element from scrolling vertically .messages { height: 220px; overflow: auto; overscroll-behavior-y: contain; } see overscroll-behavior for a full example and explanation.
overscroll-behavior - CSS: Cascading Style Sheets
formal definition initial valueautoapplies tonon-replaced block-level elements and non-replaced inline-block elementsinheritednocomputed valueas specifiedanimation typediscrete formal syntax [ contain | none | auto ]{1,2}
examples preventing an underlying element from scrolling in our overscroll-behavior example (see the source code also), we present a full-page list of fake contacts, and a dialog box containing a chat window.
padding-block - CSS: Cascading Style Sheets
formal definition initial value0applies toall elementsinheritednopercentageslogical-width of containing blockcomputed valueas <length>animation typediscrete formal syntax <'padding-left'>{1,2}
examples setting block padding for vertical text html <div> <p class="exampletext">example text</p> </div> css div { background-color: yellow; width: 120px; height: 120px; } .exampletext { writing-mode: vertical-rl; padding-block: 20px 40px; background-color: #c8c800; } result specifications specification status comment css logical properties and value...
padding-inline - CSS: Cascading Style Sheets
formal definition initial value0applies toall elementsinheritednopercentageslogical-width of containing blockcomputed valueas <length>animation typediscrete formal syntax <'padding-left'>{1,2}
examples setting inline padding for vertical text html <div> <p class="exampletext">example text</p> </div> css div { background-color: yellow; width: 120px; height: 120px; } .exampletext { writing-mode: vertical-rl; padding-inline: 20px 40px; background-color: #c8c800; } result specifications specification status comment css logical properties and val...
page-break-after - CSS: Cascading Style Sheets
user agents may also apply it to other elements like table-row elements.inheritednocomputed valueas specifiedanimation typediscrete formal syntax auto | always | avoid | left | right | recto | verso
examples setting a page break after footnotes /* move to a new page after footnotes */ div.footnotes { page-break-after: always; } specifications specification status comment css logical properties and values level 1the definition of 'recto and verso' in that specification.
page-break-before - CSS: Cascading Style Sheets
user agents may also apply it to other elements like table-row elements.inheritednocomputed valueas specifiedanimation typediscrete formal syntax auto | always | avoid | left | right | recto | verso
examples avoid a page break before the dic /* avoid page break before the div */ div.note { page-break-before: avoid; } specifications specification status comment css logical properties and values level 1the definition of 'recto and verso' in that specification.
page-break-inside - CSS: Cascading Style Sheets
user agents may also apply it to other elements like table-row elements.inheritednocomputed valueas specifiedanimation typediscrete formal syntax auto | avoid
examples avoiding page breaks inside elements html <div class="page"> <p>this is the first paragraph.</p> <section class="list"> <span>a list</span> <ol> <li>one</li> <!-- <li>two</li> --> </ol> </section> <ul> <li>one</li> <!-- <li>two</li> --> </ul> <p>this is the second paragraph.</p> <p>this is the third paragraph, it contains more text.</p> <p>this i...
paint-order - CSS: Cascading Style Sheets
formal definition initial valuenormalapplies totext elementsinheritedyescomputed valueas specifiedanimation typediscrete formal syntax normal | [ fill | stroke | markers ]
examples reversing the paint order of stroke and fill svg <svg xmlns="http://www.w3.org/2000/svg" width="400" height="200"> <text x="10" y="75">stroke in front</text> <text x="10" y="150" class="stroke-behind">stroke behind</text> </svg> css text { font-family: sans-serif; font-size: 50px; font-weight: bold; fill: black; stroke: red; stroke-width: 4px; } .stroke-behind { paint-orde...
<percentage> - CSS: Cascading Style Sheets
examples width and margin-left <div style="background-color:navy;"> <div style="width:50%; margin-left:20%; background-color:chartreuse;"> width: 50%, left margin: 20% </div> <div style="width:30%; margin-left:60%; background-color:pink;"> width: 30%, left margin: 60% </div> </div> the above html will output: font-size <div style="font-size:18px;"> <p>full-size text (18px)</p> ...
<position> - CSS: Cascading Style Sheets
examples valid positions center left center top right 8.5% bottom 12vmin right -6px 10% 20% 8rem 14px invalid positions left right bottom top 10px 15px 20px 15px specifications specification status comment css values and units module level 3the definition of '<position>' in that specification.
rotate - CSS: Cascading Style Sheets
formal definition initial valuenoneapplies totransformable elementsinheritednocomputed valueas specifiedanimation typea transformcreates stacking contextyes formal syntax none | <angle> | [ x | y | z | <number>{3} ] && <angle>
examples rotate an element on hover html <div> <p class="rotate">rotation</p> </div> css * { box-sizing: border-box; } html { font-family: sans-serif; } div { width: 150px; margin: 0 auto; } p { padding: 10px 5px; border: 3px solid black; border-radius: 20px; width: 150px; font-size: 1.2rem; text-align: center; } .rotate { transition: rotate 1s; } div:hover .rotate { ...
ruby-align - CSS: Cascading Style Sheets
formal definition initial valuespace-aroundapplies toruby bases, ruby annotations, ruby base containers, ruby annotation containersinheritedyescomputed valueas specifiedanimation typediscrete formal syntax start | center | space-between | space-around
examples ruby aligned at the start of the base text html <ruby> <rb>this is a long text to check</rb> <rp>(</rp><rt>short ruby</rt><rp>)</rp> </ruby> css ruby { ruby-align: start; } result ruby aligned at the center of the base text html <ruby> <rb>this is a long text to check</rb> <rp>(</rp><rt>short ruby</rt><rp>)</rp> </ruby> css ruby { ruby-align: center; } result ...
ruby-position - CSS: Cascading Style Sheets
formal definition initial valueoverapplies toruby annotations containersinheritedyescomputed valueas specifiedanimation typediscrete formal syntax over | under | inter-character
examples ruby positioned over the text html <ruby> <rb>超電磁砲</rb> <rp>(</rp><rt>レールガン</rt><rp>)</rp> </ruby> css ruby { ruby-position:over; } result ruby positioned under the text html <ruby> <rb>超電磁砲</rb> <rp>(</rp><rt>レールガン</rt><rp>)</rp> </ruby> css ruby { ruby-position:under; } result specifications specification ...
scale - CSS: Cascading Style Sheets
formal definition initial valuenoneapplies totransformable elementsinheritednocomputed valueas specifiedanimation typea transformcreates stacking contextyes formal syntax none | <number>{1,3}
examples scaling an element on hover html <div> <p class="scale">scaling</p> </div> css * { box-sizing: border-box; } html { font-family: sans-serif; } div { width: 150px; margin: 0 auto; } p { padding: 10px 5px; border: 3px solid black; border-radius: 20px; width: 150px; font-size: 1.2rem; text-align: center; } .scale { transition: scale 1s; } div:hover .scale { scale:...
scroll-margin-inline - CSS: Cascading Style Sheets
formal definition initial value0applies toall elementsinheritednocomputed valueas specifiedanimation typeby computed value type formal syntax <length>{1,2}
examples simple demonstration this example implements something very similar to the interactive example above, except that here we'll explain to you how it's implemented.
scroll-snap-coordinate - CSS: Cascading Style Sheets
| [ [ left | right ] <length-percentage> ] && [ [ top | bottom ] <length-percentage> ] ]where <length-percentage> = <length> | <percentage>
examples setting scroll snap coordinates html <div id="container"> <div> <p>at coordinate (0, 0)</p> <div class="scrollcontainer coordinate0"> <div>1</div> <div>2</div> <div>3</div> </div> </div> <div> <p>at coordinate (25, 0)</p> <div class="scrollcontainer coordinate25"> <div>1</div> <div>2</div> <div>3</div> </div> </div> <div> ...
scroll-snap-destination - CSS: Cascading Style Sheets
| [ [ left | right ] <length-percentage> ] && [ [ top | bottom ] <length-percentage> ] ]where <length-percentage> = <length> | <percentage>
examples setting scroll snap destination html <div id="container"> <div> <p>at coordinate (0, 0)</p> <div class="scrollcontainer destination0"> <div>1</div> <div>2</div> <div>3</div> </div> </div> <div> <p>at coordinate (25, 0)</p> <div class="scrollcontainer destination25"> <div>1</div> <div>2</div> <div>3</div> </div> </div> <div...
scroll-snap-points-x - CSS: Cascading Style Sheets
formal definition initial valuenoneapplies toscroll containersinheritednopercentagesrelative to same axis of the padding-box of the scroll containercomputed valueas specified, but with relative lengths converted into absolute lengthsanimation typediscrete formal syntax none | repeat( <length-percentage> )where <length-percentage> = <length> | <percentage>
examples setting horizontal scroll snap points html <div id="container"> <div>1</div> <div>2</div> <div>3</div> </div> css #container { width: 200px; overflow: auto; white-space: nowrap; scroll-snap-points-x: repeat(100%); scroll-snap-type: mandatory; font-size: 0; } #container > div { width: 200px; height: 200px; display: inline-block; line-height: 200px; text-align: cen...
scroll-snap-points-y - CSS: Cascading Style Sheets
formal definition initial valuenoneapplies toscroll containersinheritednopercentagesrelative to same axis of the padding-box of the scroll containercomputed valueas specified, but with relative lengths converted into absolute lengthsanimation typediscrete formal syntax none | repeat( <length-percentage> )where <length-percentage> = <length> | <percentage>
examples setting vertical scroll snap points html <div id="container"> <div>1</div> <div>2</div> <div>3</div> </div> css #container { height: 200px; width: 220px; overflow-x: hidden; overflow-y: auto; scroll-snap-points-y: repeat(200px); scroll-snap-type: mandatory; font-size: 0; } #container > div { width: 200px; height: 200px; display: inline-block; line-height: 200px; ...
scroll-snap-stop - CSS: Cascading Style Sheets
formal definition initial valuenormalapplies toall elementsinheritednocomputed valueas specifiedanimation typediscrete formal syntax normal | always
examples snapping in different axes this example is duplicated from scroll-snap-type with minor variances.
scrollbar-color - CSS: Cascading Style Sheets
)where <alpha-value> = <number> | <percentage><hue> = <number> | <angle>
examples coloring overflow scrollbars css .scroller { width: 300px; height: 100px; overflow-y: scroll; scrollbar-color: rebeccapurple green; } html <div class="scroller">veggies es bonus vobis, proinde vos postulo essum magis kohlrabi welsh onion daikon amaranth tatsoi tomatillo melon azuki bean garlic.
scrollbar-width - CSS: Cascading Style Sheets
mdn understanding wcag, guideline 2.1 explanations mdn understanding wcag, guideline 2.5 explanations understanding success criterion 2.1.1 | w3c understanding wcag 2.1 understanding success criterion 2.5.5 | w3c understanding wcag 2.1 formal definition initial valueautoapplies toscrolling boxesinheritednocomputed valueas specifiedanimation typediscrete formal syntax auto | thin | none
examples sizing overflow scrollbars css .scroller { width: 300px; height: 100px; overflow-y: scroll; scrollbar-width: thin; } html <div class="scroller">veggies es bonus vobis, proinde vos postulo essum magis kohlrabi welsh onion daikon amaranth tatsoi tomatillo melon azuki bean garlic.
Specified value - CSS: Cascading Style Sheets
examples html <p>my specified color is given explicitly in the css.</p> <div>the specified values of all my properties default to their initial values, because none of them are given in the css.</div> <div class="fun"> <p>the specified value of my font family is not given explicitly in the css, so it is inherited from my parent.
<string> - CSS: Cascading Style Sheets
examples /* simple strings */ "this string is demarcated by double quotes." 'this string is demarcated by single quotes.' /* character escaping */ "this is a string with \" an escaped double quote." "this string also has \22 an escaped double quote." 'this is a string with \' an escaped single quote.' 'this string also has \27 an escaped single quote.' "this is a string with \\ an escaped backslash." /...
symbols() - CSS: Cascading Style Sheets
examples html <ol> <li>one</li> <li>two</li> <li>three</li> <li>four</li> <li>five</li> </ol> css ol { list-style: symbols(cyclic "*" "†" "‡"); } result specifications specification status comment css counter styles level 3the definition of 'symbols()' in that specification.
tab-size - CSS: Cascading Style Sheets
formal definition initial value8applies toblock containersinheritedyescomputed valuethe specified integer or an absolute lengthanimation typea length formal syntax <integer> | <length>
examples expanding by character count pre { tab-size: 4; /* set tab size to 4 characters wide */ } collapse tabs pre { tab-size: 0; /* remove indentation */ } comparing to the default size this example compares a default tab size with a custom tab size.
text-decoration-skip - CSS: Cascading Style Sheets
formal definition initial valueobjectsapplies toall elementsinheritedyescomputed valueas specifiedanimation typediscrete formal syntax none | [ objects | [ spaces | [ leading-spaces | trailing-spaces ] ] | edges | box-decoration ]
examples skipping edges html <p>hey, grab a cup of <em>coffee!</em></p> css p { margin: 0; font-size: 3em; text-decoration: underline; text-decoration-skip: edges; } result specifications specification status comment css text decoration module level 4the definition of 'text-decoration-skip' in that specification.
text-decoration-thickness - CSS: Cascading Style Sheets
it also applies to ::first-letter and ::first-line.inheritednopercentagesrefer to the font size of the element itselfcomputed valueas specifiedanimation typeby computed value type formal syntax auto | from-font | <length> | <percentage>
examples varying thickness html <p class="thin">here's some text with a 1px red underline.</p> <p class="thick">this one has a 5px red underline.</p> <p class="shorthand">this uses the equivalent shorthand.</p> css .thin { text-decoration-line: underline; text-decoration-style: solid; text-decoration-color: red; text-decoration-thickness: 1px; } .thick { text-decoration-line: underline; ...
text-emphasis-color - CSS: Cascading Style Sheets
)where <alpha-value> = <number> | <percentage><hue> = <number> | <angle>
examples emphasis with a color and custom character css em { text-emphasis-color: green; text-emphasis-style: "*"; } html <p>here's an example:</p> <em>this has emphasis marks!</em> result specifications specification status comment css text decoration module level 3the definition of 'text-emphasis' in that specification.
text-emphasis-position - CSS: Cascading Style Sheets
formal definition initial valueover rightapplies toall elementsinheritednocomputed valueas specifiedanimation typediscrete formal syntax [ over | under ] && [ right | left ]
examples preferring ruby over emphasis marks some editors prefer to hide emphasis marks when they conflict with ruby.
text-emphasis-style - CSS: Cascading Style Sheets
formal definition initial valuenoneapplies toall elementsinheritednocomputed valueas specifiedanimation typediscrete formal syntax none | [ [ filled | open ] | [ dot | circle | double-circle | triangle | sesame ] ] | <string>
examples h2 { text-emphasis-style: sesame; } specifications specification status comment css text decoration module level 3the definition of 'text-emphasis' in that specification.
text-justify - CSS: Cascading Style Sheets
formal definition initial valueautoapplies toinline-level and table-cell elementsinheritedyescomputed valueas specifiedanimation typediscrete formal syntax auto | inter-character | inter-word | none
examples <p class="none"><code>text-justify: none</code> —<br>lorem ipsum dolor sit amet, consectetur adipiscing elit.
text-rendering - CSS: Cascading Style Sheets
formal definition initial valueautoapplies totext elementsinheritedyescomputed valueas specifiedanimation typediscrete formal syntax auto | optimizespeed | optimizelegibility | geometricprecision
examples automatic application of optimizelegibility this demonstrates how optimizelegibility is used by browsers automatically when the font-size is smaller than 20px.
text-size-adjust - CSS: Cascading Style Sheets
formal definition initial valueauto for smartphone browsers supporting inflation, none in other cases (and then not modifiable).applies toall elementsinheritedyespercentagesyes, refer to the corresponding size of the text fontcomputed valueas specifiedanimation typediscrete formal syntax none | auto | <percentage>
examples basic disabling usage as hinted at above, on a properly designed responsive site the text-size-adjust behavior is not needed, so developers can elect to turn it off by specifying a vlaue of none: p { -webkit-text-size-adjust: none; text-size-adjust: none; } specifications specification status comment css mobile text size adjustment module level 1the definition...
text-underline-offset - CSS: Cascading Style Sheets
it also applies to ::first-letter and ::first-line.inheritedyespercentagesrefer to the font size of the element itselfcomputed valueas specifiedanimation typeby computed value type formal syntax auto | <length> | <percentage>
examples <p class="oneline">here's some text with an offset wavy red underline!</p> <br> <p class="twolines">this text has lines both above and below it.
touch-action - CSS: Cascading Style Sheets
anding success criterion 1.4.4 | understanding wcag 2.0 formal definition initial valueautoapplies toall elements except: non-replaced inline elements, table rows, row groups, table columns, and column groupsinheritednocomputed valueas specifiedanimation typediscrete formal syntax auto | none | [ [ pan-x | pan-left | pan-right ] | [ pan-y | pan-up | pan-down ] | pinch-zoom ] | manipulation
examples disabling all gestures the most common usage is to disable all gestures on an element (and its non-scrollable descendants) that provides its own dragging and zooming behavior – such as a map or game surface.
transform-box - CSS: Cascading Style Sheets
formal definition initial valueview-boxapplies totransformable elementsinheritednocomputed valueas specifiedanimation typediscrete formal syntax content-box | border-box | fill-box | stroke-box | view-box
examples svg transform-origin scoping in this example we have an svg: <svg id="svg" xmlns="http://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> <...
matrix() - CSS: Cascading Style Sheets
cartesian coordinates on ℝ2 homogeneous coordinates on ℝℙ2 cartesian coordinates on ℝ3 homogeneous coordinates on ℝℙ3 ac bd actxbdty001 actxbdty001 ac0txbd0ty00100001 [a b c d tx ty] the values represent the following functions: matrix( scalex(), skewy(), skewx(), scaley(), translatex(), translatey() )
examples html <div>normal</div> <div class="changed">changed</div> css div { width: 80px; height: 80px; background-color: skyblue; } .changed { transform: matrix(1, 2, -1, 1, 80, 80); background-color: pink; } result specifications specification status comment css transforms level 1the definition of 'matrix()' in that specification.
matrix3d() - CSS: Cascading Style Sheets
a1a2a3a4b1b2b3b4c1c2c3c4d1d2d3d4
examples cube squashing example the following example shows a 3d cube created from dom elements and transforms, which can be hovered/focused to apply a matrix3d() transform to it.
rotate() - CSS: Cascading Style Sheets
cartesian coordinates on ℝ2 homogeneous coordinates on ℝℙ2 cartesian coordinates on ℝ3 homogeneous coordinates on ℝℙ3 cos(a)-sin(a) sin(a)cos(a) cos(a)-sin(a)0sin(a)cos(a)0001 cos(a)-sin(a)0sin(a)cos(a)0001 cos(a)-sin(a)00sin(a)cos(a)0000100001 [cos(a) sin(a) -sin(a) cos(a) 0 0]
examples basic example html <div>normal</div> <div class="rotated">rotated</div> css div { width: 80px; height: 80px; background-color: skyblue; } .rotated { transform: rotate(45deg); /* equal to rotatez(45deg) */ background-color: pink; } result combining rotation with another transformation if you want apply multiple transformations to an element, be careful about the order in whic...
scale() - CSS: Cascading Style Sheets
find out more: mdn understanding wcag, guideline 2.3 explanations 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">...
scaleX() - CSS: Cascading Style Sheets
cartesian coordinates on ℝ2 homogeneous coordinates on ℝℙ2 cartesian coordinates on ℝ3 homogeneous coordinates on ℝℙ3 s0 01 s00010001 s00010001 s000010000100001 [s 0 0 1 0 0]
examples html <div>normal</div> <div class="scaled">scaled</div> css div { width: 80px; height: 80px; background-color: skyblue; } .scaled { transform: scalex(0.6); background-color: pink; } result specifications specification status comment css transforms level 1the definition of 'scalex()' in that specification.
scaleY() - CSS: Cascading Style Sheets
cartesian coordinates on ℝ2 homogeneous coordinates on ℝℙ2 cartesian coordinates on ℝ3 homogeneous coordinates on ℝℙ3 10 0s 1000s0001 1000s0001 10000s0000100001 [1 0 0 s 0 0]
examples html <div>normal</div> <div class="scaled">scaled</div> css div { width: 80px; height: 80px; background-color: skyblue; } .scaled { transform: scaley(0.6); background-color: pink; } result specifications specification status comment css transforms level 1the definition of 'scaley()' in that specification.
translate() - CSS: Cascading Style Sheets
10tx01ty001 10tx01ty001 100tx010ty00100001 [1 0 0 1 tx ty] formal syntax translate(<length-percentage> , <length-percentage>?)
examples using a single-axis translation html <div>static</div> <div class="moved">moved</div> <div>static</div> css div { width: 60px; height: 60px; background-color: skyblue; } .moved { transform: translate(10px); /* equal to: translatex(10px) or translate(10px, 0) */ background-color: pink; } result combining y-axis and x-axis translation html <div>static</div> <div class="moved"...
translateX() - CSS: Cascading Style Sheets
10t010001 10t010001 100t010000100001 [1 0 0 1 t 0] formal syntax translatex(<length-percentage>)
examples html <div>static</div> <div class="moved">moved</div> <div>static</div> css div { width: 60px; height: 60px; background-color: skyblue; } .moved { transform: translatex(10px); /* equal to translate(10px) */ background-color: pink; } result specifications specification status comment css transforms level 1the definition of 'translatex()' in that spe...
translateY() - CSS: Cascading Style Sheets
10001t001 10001t001 1000010t00100001 [1 0 0 1 0 t] formal syntax translatey(<length-percentage>)
examples html <div>static</div> <div class="moved">moved</div> <div>static</div> css div { width: 60px; height: 60px; background-color: skyblue; } .moved { transform: translatey(10px); background-color: pink; } result specifications specification status comment css transforms level 1the definition of 'translatey()' in that specification.
<transform-function> - CSS: Cascading Style Sheets
examples transform function comparison the following example provides a 3d cube created from dom elements and transforms, and a select menu allowing you to choose different transform functions to transform the cube with, so you can compare the effects of the different types.
translate - CSS: Cascading Style Sheets
]?where <length-percentage> = <length> | <percentage>
examples html <div> <p class="translate">translation</p> </div> css * { box-sizing: border-box; } html { font-family: sans-serif; } div { width: 150px; margin: 0 auto; } p { padding: 10px 5px; border: 3px solid black; border-radius: 20px; width: 150px; font-size: 1.2rem; text-align: center; } .translate { transition: translate 1s; } div:hover .translate { translate: 200p...
unicode-bidi - CSS: Cascading Style Sheets
formal definition initial valuenormalapplies toall elements, though some values have no effect on non-inline elementsinheritednocomputed valueas specifiedanimation typediscrete formal syntax normal | embed | isolate | bidi-override | isolate-override | plaintext
examples css .bible-quote { direction: rtl; unicode-bidi: embed; } html <div class="bible-quote"> a line of text </div> <div> another line of text </div> result specifications specification status comment css writing modes module level 3the definition of 'unicode-bidi' in that specification.
unset - CSS: Cascading Style Sheets
examples color html <p>this text is red.</p> <div class="foo"> <p>this text is also red.</p> </div> <div class="bar"> <p>this text is green (default inherited value).</p> </div> css .foo { color: blue; } .bar { color: green; } p { color: red; } .bar p { color: unset; } result border html <p>this text has a red border.</p> <div> <p>this text has a red border.</p> </div> <div cla...
url() - CSS: Cascading Style Sheets
formal syntax url( <string> <url-modifier>* )
examples content property html <ul> <li>item 1</li> <li>item 2</li> <li>item 3</li> </ul> css li::after { content: ' - ' url(https://mdn.mozillademos.org/files/16761/star.gif); } result data-uri html <div class="background"></div> css .background { height: 100vh; } .background { background: yellow; background: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg'...
<url> - CSS: Cascading Style Sheets
<a_css_property>: url("http://mysite.example.com/mycursor.png") <a_css_property>: url('http://mysite.example.com/mycursor.png') <a_css_property>: url(http://mysite.example.com/mycursor.png)
examples .topbanner { background: url("topbanner.png") #00d no-repeat fixed; } ul { list-style: square url(http://www.example.com/redball.png); } specifications specification status comment css values and units module level 4the definition of '<url>' in that specification.
user-modify - CSS: Cascading Style Sheets
examples html <div class="readwrite">the user is able to change this text.</div> css .readwrite { -moz-user-modify: read-write; -webkit-user-modify: read-write; } specifications not part of any standard.
user-select - CSS: Cascading Style Sheets
formal definition initial valueautoapplies toall elementsinheritednocomputed valueas specifiedanimation typediscrete formal syntax auto | text | none | contain | all
examples html <p>you should be able to select this text.</p> <p class="unselectable">hey, you can't select this text!</p> <p class="all">clicking once will select all of this text.</p> css .unselectable { -moz-user-select: none; -webkit-user-select: none; -ms-user-select: none; user-select: none; } .all { -moz-user-select: all; -webkit-user-select: all; -ms-user-select: all; user-sel...
widows - CSS: Cascading Style Sheets
formal definition initial value2applies toblock container elementsinheritedyescomputed valueas specifiedanimation typediscrete formal syntax <integer>
examples controlling column widows html <div> <p>this is the first paragraph containing some text.</p> <p>this is the second paragraph containing some more text than the first one.
will-change - CSS: Cascading Style Sheets
.slide { will-change: transform; } formal definition initial valueautoapplies toall elementsinheritednocomputed valueas specifiedanimation typediscrete formal syntax auto | <animateable-feature>#where <animateable-feature> = scroll-position | contents | <custom-ident>
examples via script this is an example showing how to apply the will-change property through scripting, which is probably what you should be doing in most cases.
zoom - CSS: Cascading Style Sheets
formal definition initial valuenormalapplies toall elementsinheritednocomputed valueas specifiedanimation typean integer formal syntax normal | reset | <number> | <percentage>
examples first example html <p class="small">small</p> <p class="normal">normal</p> <p class="big">big</p> css p.small { zoom: 75%; } p.normal { zoom: normal; } p.big { zoom: 2.5; } p { display: inline-block; } p:hover { zoom: reset; } result second example html <div id="a" class="circle"></div> <div id="b" class="circle"></div> <div id="c" class="circle"></div> css div.circle { ...
Ajax - Developer guides
documentation getting started this article guides you through the ajax basics and gives you two simple hands-on
examples to get you started.
Setting up adaptive streaming media sources - Developer guides
ing overview mpeg-dash overview and references dynamic adaptive streaming over http dataset mpeg-dash and streaming reference and resources (msdn) dash adaptive streaming for html 5 video dynamic adaptive streaming over http: from content creation to consumption mpeg-dash tools dashencoder mp4box dash.js wiki dash.js google group akamai dash diagnostic player adaptive streaming
examples itec – dynamic adaptive streaming over http mpeg dash media source demo ...
Mutation events - Developer guides
mutation events list the following is a list of all mutation events, as defined in dom level 3 events specification: domattrmodified domattributenamechanged domcharacterdatamodified domelementnamechanged domnodeinserted domnodeinsertedintodocument domnoderemoved domnoderemovedfromdocument domsubtreemodified mutation observers alternatives
examples domnoderemovedfromdocument var isdescendant = function (desc, root) { return !!desc && (desc === root || isdescendant(desc.parentnode, root)); }; var onremove = function (element, callback) { var observer = new mutationobserver(function (mutations) { _.foreach(mutations, function (mutation) { _.foreach(mutation.removednodes, function (removed) { if (...
HTML5 - Developer guides
html5 reference guide quick-reference html5 sheet containing markup generators, code
examples and web developer tools.
Developer guides
this article provides recommendations for managing user input and implementing controls in open web apps, along with faqs, real-world
examples, and links to further information for anyone needing more detailed information on the underlying technologies.
HTML attribute: multiple - HTML: Hypertext Markup Language
examples email input <label for="emails">who do you want to email?</label> <input type="email" multiple name="emails" id="emails" list="drawfemails" required size="64"> <datalist id="drawfemails"> <option value="grumpy@woodworkers.com">grumpy</option> <option value="happy@woodworkers.com">happy</option> <option value="sleepy@woodworkers.com">sleepy</option> <option value="bashful@woodworkers.co...
HTML attribute: pattern - HTML: Hypertext Markup Language
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-d...
HTML attribute: readonly - HTML: Hypertext Markup Language
adonly="readonly"/> <label>date</label> </div> <div class="group"> <input type="email" value="some value" readonly="readonly"/> <label>email</label> </div> <div class="group"> <input type="password" value="some value" readonly="readonly"/> <label>password</label> </div> <div class="group"> <textarea readonly="readonly">some value</textarea> <label>message</label> </div> result
examples <fieldset> <legend>checkboxes buttons</legend> <p><label> <input type="checkbox" name="chbox" value="regular"> regular </label></p> <p><label> <input type="checkbox" name="chbox" value="readonly" readonly> readonly </label></p> <p><label> <input type="checkbox" name="chbox" value="disabled" disabled> disabled </label></p> </fieldset> <fieldset> <legend>radio buttons<...
<base>: The Document Base URL element - HTML: Hypertext Markup Language
for example: <meta property="og:image" content="https://example.com/thumbnail.jpg">
examples <base href="https://www.example.com/"> <base target="_blank"> <base target="_top" href="https://example.com/"> specifications specification status comment html living standardthe definition of '<base>' in that specification.
<marquee>: The Marquee element (Obsolete) - HTML: Hypertext Markup Language
examples <marquee>this text will scroll from right to left</marquee> <marquee direction="up">this text will scroll from bottom to top</marquee> <marquee direction="down" width="250" height="200" behavior="alternate" style="border:solid"> <marquee behavior="alternate"> this text will bounce </marquee> </marquee> specifications specification status comment html liv...
<menu> - HTML: Hypertext Markup Language
examples context menu html <!-- a <div> element with a context menu --> <div contextmenu="popup-menu"> right-click to see the adjusted context menu </div> <menu type="context" id="popup-menu"> <menuitem>action</menuitem> <menuitem>another action</menuitem> <hr/> <menuitem>separated action</menuitem> </menu> css div { width: 300px; height: 80px; background-color: lightgreen; } r...
<noscript> - HTML: Hypertext Markup Language
examples <noscript> <!-- anchor linking to external file --> <a href="https://www.mozilla.com/">external link</a> </noscript> <p>rocks!</p> result with scripting enabled rocks!
<slot> - HTML: Hypertext Markup Language
examples <template id="element-details-template"> <style> details {font-family: "open sans light", helvetica, arial, sans-serif } .name {font-weight: bold; color: #217ac0; font-size: 120% } h4 { margin: 10px 0 -8px 0; background: #217ac0; color: white; padding: 2px 6px; border: 1px solid #cee9f9; border-radius: 4px; } .attributes { margin-left: 22...
dir - HTML: Hypertext Markup Language
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
id - HTML: Hypertext Markup Language
if you'd like to contribute to the interactive
examples project, please clone https://github.com/mdn/interactive-
examples and send us a pull request.
Identifying resources on the Web - HTTP
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 ...
Accept-CH-Lifetime - HTTP
syntax accept-ch-lifetime: <age>
examples accept-ch: viewport-width, dpr accept-ch-lifetime: 86400 ...
Accept-CH - HTTP
syntax accept-ch: <list of client hints>
examples accept-ch: dpr, viewport-width accept-ch: width accept-ch-lifetime: 86400 vary: dpr, viewport-width, width note: remember to vary the response based on the accepted client hints.
Accept-Charset - HTTP
examples accept-charset: iso-8859-1 accept-charset: utf-8, iso-8859-1;q=0.5 accept-charset: utf-8, iso-8859-1;q=0.5, *;q=0.1 specifications specification title rfc 7231, section 5.3.3: accept-charset hypertext transfer protocol (http/1.1): semantics and context ...
Accept-Encoding - HTTP
examples accept-encoding: gzip accept-encoding: gzip, compress, br accept-encoding: br;q=1.0, gzip;q=0.8, *;q=0.1 specifications specification title rfc 7231, section 5.3.4: accept-encoding hypertext transfer protocol (http/1.1): semantics and context ...
Accept-Language - HTTP
examples accept-language: de accept-language: de-ch accept-language: en-us,en;q=0.5 specifications specification title rfc 7231, section 5.3.5: accept-language hypertext transfer protocol (http/1.1): semantics and context bcp 47 tags for the identification of language ...
Accept-Patch - HTTP
header type response header forbidden header name yes syntax accept-patch: application/example, text/example accept-patch: text/example;charset=utf-8 accept-patch: application/merge-patch+json directives none
examples accept-patch: application/example, text/example accept-patch: text/example;charset=utf-8 accept-patch: application/merge-patch+json specifications specification title rfc 5789, section 3.1: accept-patch http patch ...
Accept-Ranges - HTTP
examples accept-ranges: bytes specifications specification title rfc 7233, section 2.3: accept-ranges hypertext transfer protocol (http/1.1): range requests ...
Accept - HTTP
examples accept: text/html accept: image/* // general default accept: */* // default for navigation requests accept: text/html, application/xhtml+xml, application/xml;q=0.9, */*;q=0.8 specifications specification title rfc 7231, section 5.3.2: accept hypertext transfer protocol (http/1.1): semantics and context ...
Access-Control-Allow-Credentials - HTTP
examples allow credentials: access-control-allow-credentials: true using xhr with credentials: var xhr = new xmlhttprequest(); xhr.open('get', 'http://example.com/', true); xhr.withcredentials = true; xhr.send(null); using fetch with credentials: fetch(url, { credentials: 'include' }) specifications specification status comment fetchthe definition of 'access-control-a...
Access-Control-Allow-Methods - HTTP
examples access-control-allow-methods: post, get, options access-control-allow-methods: * specifications specification status comment fetchthe definition of 'access-control-allow-methods' in that specification.
Access-Control-Allow-Origin - HTTP
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-...
Access-Control-Expose-Headers - HTTP
examples to expose a non-cors-safelisted request header, you can specify: access-control-expose-headers: content-length to additionally expose a custom header, like x-kuma-revision, you can specify multiple headers separated by a comma: access-control-expose-headers: content-length, x-kuma-revision in requests without credentials, you can also use a wildcard value: access-control-expose-headers: * ...
Access-Control-Max-Age - HTTP
examples cache results of a preflight request for 10 minutes: access-control-max-age: 600 specifications specification status comment fetchthe definition of 'access-control-max-age' in that specification.
Access-Control-Request-Headers - HTTP
examples access-control-request-headers: x-pingother, content-type specifications specification status comment fetchthe definition of 'access-control-request-headers' in that specification.
Access-Control-Request-Method - HTTP
examples access-control-request-method: post specifications specification status comment fetchthe definition of 'access-control-request-method' in that specification.
Age - HTTP
examples age: 24 specifications specification title rfc 7234, section 5.1: age hypertext transfer protocol (http/1.1): caching ...
Allow - HTTP
examples allow: get, post, head specifications specification title rfc 7231, section 7.4.1: allow hypertext transfer protocol (http/1.1): semantics and content ...
Alt-Svc - HTTP
examples include h2 for http/2 and h3-25 for draft 25 of the http/3 protocol.
Authorization - HTTP
examples authorization: basic ywxhzgrpbjpvcgvuc2vzyw1l see also http authentication for
examples on how to configure apache or nginx servers to password protect your site with http basic authentication.
Cache-Control - HTTP
examples preventing caching to disable caching of a resource, you can send the following response header: good: cache-control: no-store bad: cache-control: private,no-cache,no-store,max-age=0,must-revalidate,pre-check=0,post-check=0 caching static assets for the files in the application that will not change, you can usually add aggressive caching by sending the response header below.
Clear-Site-Data - HTTP
examples sign out of web site if a user signs out of your website or service, you might want to remove locally stored data.
Content-Disposition - HTTP
examples a response triggering the "save as" dialog: 200 ok content-type: text/html; charset=utf-8 content-disposition: attachment; filename="cool.html" content-length: 21 <html>save me!</html> this simple html file will be saved as a regular download rather than displayed in the browser.
Content-Encoding - HTTP
examples compressing with gzip on the client side, you can advertise a list of compression schemes that will be sent along in an http request.
Content-Language - HTTP
examples indicating the language a document is written in the global lang attribute is used on html elements to indicate the language of an entire html document or parts of it.
Content-Range - HTTP
examples content-range: bytes 200-1000/67589 specifications specification title rfc 7233, section 4.2: content-range hypertext transfer protocol (http/1.1): range requests ...
CSP: block-all-mixed-content - HTTP
syntax content-security-policy: block-all-mixed-content;
examples content-security-policy: block-all-mixed-content; <meta http-equiv="content-security-policy" content="block-all-mixed-content"> to disallow http assets on a more granular level, you can also set individual directives to https:.
CSP: plugin-types - HTTP
examples disallowing plugins to disallow all plugins, the object-src directive should be set to 'none' which will disallow plugins.
CSP: prefetch-src - HTTP
examples: http://*.example.com: matches all attempts to load from any subdomain of example.com using the http: url scheme.
CSP: referrer - HTTP
examples content-security-policy: referrer "none"; specifications not part of any specification.
CSP: report-to - HTTP
syntax content-security-policy: report-to <json-field-value>;
examples see content-security-policy-report-only for more information and
examples.
CSP: require-sri-for - HTTP
examples if you set your site to require sri for script and styles using this directive: content-security-policy: require-sri-for script style <script> elements like the following will be loaded as they use a valid integrity attribute.
CSP: sandbox - HTTP
examples content-security-policy: sandbox allow-scripts; specifications specification status comment content security policy level 3the definition of 'sandbox' in that specification.
CSP: trusted-types - HTTP
'allow-duplicates' allows for creating policies with a name that was already used
examples todo polyfill a polyfill for trusted types is available on github.
CSP: upgrade-insecure-requests - HTTP
syntax content-security-policy: upgrade-insecure-requests;
examples // header content-security-policy: upgrade-insecure-requests; // meta tag <meta http-equiv="content-security-policy" content="upgrade-insecure-requests"> with the above header set on a domain example.com that wants to migrate from http to https, non-navigational insecure resource requests are automatically upgraded (first-party as well as third-party requests).
Content-Type - HTTP
examples content-type in html forms in a post request, resulting from an html form submission, the content-type of the request is specified by the enctype attribute on the <form> element.
Cookie - HTTP
examples cookie: phpsessid=298zf09hf012fh2; csrftoken=u32t4o3tb3gg43; _gat=1 specifications specification title rfc 6265, section 5.4: cookie http state management mechanism ...
Cookie2 - HTTP
header type request header forbidden header name yes
examples cookie2: $version="1" specifications specification title rfc 2965: cookie2 historic specification of http state management mechanism, obsoleted by rfc 6265 ...
Cross-Origin-Embedder-Policy - HTTP
examples certain features depend on cross-origin isolation you can only access certain features like sharedarraybuffer objects or performance.now() with unthrottled timers, if your document has a coep header with the value require-corp value set.
Cross-Origin-Opener-Policy - HTTP
examples certain features depend on cross-origin isolation certain features like sharedarraybuffer objects or performance.now() with unthrottled timers are only available if your document has a coop header with the value same-origin value set.
Cross-Origin-Resource-Policy - HTTP
header type response header forbidden header name no syntax cross-origin-resource-policy: same-site | same-origin | cross-origin
examples the response header below will cause compatible user agents to disallow cross-origin no-cors requests: cross-origin-resource-policy: same-origin for more
examples, see https://resourcepolicy.fyi/.
DNT - HTTP
examples reading do not track status from javascript the user's dnt preference can also be read from javascript using the navigator.donottrack property: navigator.donottrack; // "0" or "1" specifications specification status comment tracking preference expression (dnt)the definition of 'dnt header field for http requests' in that specification.
DPR - HTTP
syntax dpr: <number>
examples server first needs to opt in to receive dpr header by sending the response headers accept-ch containing dpr and accept-ch-lifetime.
Date - HTTP
examples date: wed, 21 oct 2015 07:28:00 gmt new date().toutcstring() // "mon, 09 mar 2020 08:13:24 gmt" specifications specification title rfc 7231, section 7.1.1.2: date hypertext transfer protocol (http/1.1): semantics and content ...
Device-Memory - HTTP
device-memory: <number>
examples server first needs to opt in to receive device-memory header by sending the response headers accept-ch containing device-memory and accept-ch-lifetime.
Digest - HTTP
examples digest: sha-256=x48e9qookqqrvdts8nojrjn3owduoywxbf7kbu9dbpe= digest: sha-256=x48e9qookqqrvdts8nojrjn3owduoywxbf7kbu9dbpe=,unixsum=30637 specifications specification title draft-ietf-httpbis-digest-headers-latest resource digests for http this header was originally defined in rfc 3230, but the definition of "selected representation" in rfc 7231 made t...
ETag - HTTP
examples etag: "33a64df551425fcc55e4d42a148795d9f25f89d4" etag: w/"0815" avoiding mid-air collisions with the help of the etag and the if-match headers, you can detect mid-air edit collisions.
Early-Data - HTTP
header type request header forbidden header name no syntax early-data: 1
examples get /resource http/1.0 host: example.com early-data: 1 specifications specification title rfc 8470, section 5.1: the early-data header field using early data in http ...
Expect - HTTP
examples large message body a client sends a request with a expect header and waits for the server to respond before sending the message body.
Expires - HTTP
examples expires: wed, 21 oct 2015 07:28:00 gmt specifications specification title rfc 7234, section 5.3: expires hypertext transfer protocol (http/1.1): caching ...
Forwarded - HTTP
examples using the forwarded header forwarded: for="_mdn" # case insensitive forwarded: for="[2001:db8:cafe::17]:4711" # separated by semicolon forwarded: for=192.0.2.60;proto=http;by=203.0.113.43 # multiple values can be appended using a comma forwarded: for=192.0.2.43, for=198.51.100.17 transitioning from x-forwarded-for to forwarded if your application, server, or proxy supports the standardize...
From - HTTP
examples from: webmaster@example.org specifications specification title rfc 7231, section 5.5.1: from hypertext transfer protocol (http/1.1): semantics and content ...
Host - HTTP
examples host: developer.cdn.mozilla.net specifications specification title rfc 7230, section 5.4: host hypertext transfer protocol (http/1.1): message syntax and routing ...
If-Match - HTTP
examples if-match: "bfc13a64729c4290ef5b2c2730249c88ca92d82d" if-match: "67ab43", "54ed21", "7892dd" if-match: * specifications specification title rfc 7232, section 3.1: if-match hypertext transfer protocol (http/1.1): conditional requests ...
If-Modified-Since - HTTP
examples if-modified-since: wed, 21 oct 2015 07:28:00 gmt specifications specification title rfc 7232, section 3.3: if-modified-since hypertext transfer protocol (http/1.1): conditional requests ...
If-None-Match - HTTP
examples if-none-match: "bfc13a64729c4290ef5b2c2730249c88ca92d82d" if-none-match: w/"67ab43", "54ed21", "7892dd" if-none-match: * specifications specification title rfc 7232, section 3.2: if-none-match hypertext transfer protocol (http/1.1): conditional requests ...
If-Range - HTTP
examples if-range: wed, 21 oct 2015 07:28:00 gmt specifications specification title rfc 7233, section 3.2: if-range hypertext transfer protocol (http/1.1): range requests ...
If-Unmodified-Since - HTTP
examples if-unmodified-since: wed, 21 oct 2015 07:28:00 gmt specifications specification title rfc 7232, section 3.4: if-unmodified-since hypertext transfer protocol (http/1.1): conditional requests ...
Keep-Alive - HTTP
examples a response containing a keep-alive header: http/1.1 200 ok connection: keep-alive content-encoding: gzip content-type: text/html; charset=utf-8 date: thu, 11 aug 2016 15:23:13 gmt keep-alive: timeout=5, max=1000 last-modified: mon, 25 jul 2016 04:32:39 gmt server: apache (body) specifications specification title http keep-alive header keep-alive header (ietf inter...
Large-Allocation - HTTP
examples large-allocation: 0 large-allocation: 500 troubleshooting errors the large-allocation header throws warnings or error messages when used incorrectly.
Last-Modified - HTTP
examples last-modified: wed, 21 oct 2015 07:28:00 gmt specifications specification title rfc 7232, section 2.2: last-modified hypertext transfer protocol (http/1.1): conditional requests ...
Link - HTTP
examples the uri (absolute or relative) must be enclosed between < and >: link: <https://example.com>; rel="preconnect" link: https://bad.example; rel="preconnect" specifying multiple links you can specify multiple links separated by commas, for example: link: <https://one.example.com>; rel="preconnect", <https://two.example.com>; rel="preconnect", <https://three.example.com>; rel="preconnect" spec...
Location - HTTP
examples location: /index.html specifications specification title rfc 7231, section 7.1.2: location hypertext transfer protocol (http/1.1): semantics and content ...
Origin - HTTP
examples origin: https://developer.mozilla.org specifications specification comment rfc 6454, section 7: origin the web origin concept fetchthe definition of 'origin header' in that specification.
Pragma - HTTP
examples pragma: no-cache specifications specification title rfc 7234, section 5.4: pragma hypertext transfer protocol (http/1.1): caching ...
Proxy-Authenticate - HTTP
examples proxy-authenticate: basic proxy-authenticate: basic realm="access to the internal site" specifications specification title rfc 7235, section 4.3: proxy-authenticate http/1.1: authentication rfc 7617 the 'basic' http authentication scheme ...
Proxy-Authorization - HTTP
examples proxy-authorization: basic ywxhzgrpbjpvcgvuc2vzyw1l specifications specification title rfc 7235, section 4.4: proxy-authorization http/1.1: authentication rfc 7617 the 'basic' http authentication scheme ...
Range - HTTP
examples requesting three ranges from the file.
Referer - HTTP
examples referer: https://developer.mozilla.org/docs/web/javascript specifications specification title rfc 7231, section 5.5.2: referer hypertext transfer protocol (http/1.1): semantics and content ...
Referrer-Policy - HTTP
examples policy document navigation to referrer no-referrer https://example.com/page anywhere (no referrer) no-referrer-when-downgrade https://example.com/page https://example.com/otherpage https://example.com/page https://mozilla.org https://example.com/page http://example.org (no referrer) origin https://examp...
Retry-After - HTTP
examples dealing with scheduled downtime support for the retry-after header on both clients and servers is still inconsistent.
Save-Data - HTTP
examples the vary header ensures that the content is cached properly (for instance ensuring that the user is not served a lower-quality image from the cache when save-data header is no longer present [e.g.
Sec-Fetch-Dest - HTTP
-dest: style sec-fetch-dest: track sec-fetch-dest: video sec-fetch-dest: worker sec-fetch-dest: xslt sec-fetch-dest: audioworklet sec-fetch-dest: audioworklet values audio audioworklet document embed empty font image manifest object paintworklet report script serviceworker sharedworker style track video worker xslt nested-document
examples todo specifications specification title fetch metadata request headers the sec-fetch-dest http request header ...
Sec-Fetch-Mode - HTTP
fetch metadata request header forbidden header name yes, since it has prefix sec- cors-safelisted request header syntax sec-fetch-mode: cors sec-fetch-mode: navigate sec-fetch-mode: nested-navigate sec-fetch-mode: no-cors sec-fetch-mode: same-origin sec-fetch-mode: websocket values cors navigate nested-navigate no-cors same-origin websocket
examples todo specifications specification title fetch metadata request headers the sec-fetch-mode http request header ...
Sec-Fetch-Site - HTTP
examples todo specifications specification title fetch metadata request headers the sec-fetch-site http request header ...
Sec-Fetch-User - HTTP
examples todo specifications specification title fetch metadata request headers the sec-fetch-user http request header ...
Sec-WebSocket-Accept - HTTP
examples sec-websocket-accept: s3pplmbitxaq9kygzzhzrbk+xoo= specification specification title rfc 6455, section 11.3.3: sec-websocket-accept the websocket protocol ...
Server - HTTP
examples server: apache/2.4.1 (unix) specifications specification title rfc 7231, section 7.4.2: server hypertext transfer protocol (http/1.1): semantics and content ...
Set-Cookie - HTTP
examples session cookie session cookies are removed when the client shuts down.
SourceMap - HTTP
examples sourcemap: /path/to/file.js.map specifications specification title draft document source map revision 3 proposal ...
Strict-Transport-Security - HTTP
information regarding the hsts preload list in chrome : https://www.chromium.org/hsts consultation of the firefox hsts preload list : nsstspreloadlist.inc
examples all present and future subdomains will be https for a max-age of 1 year.
Timing-Allow-Origin - HTTP
examples to allow any resource to see timing resources: timing-allow-origin: * to allow https://developer.mozilla.org to see timing resources, you can specify: timing-allow-origin: https://developer.mozilla.org specifications specification status comment resource timing level 3the definition of 'timing-allow-origin' in that specification.
Tk - HTTP
examples a tk header for a resource that claims not to be tracking would look like: tk: n specifications specification status comment tracking preference expression (dnt)the definition of 'tk header field' in that specification.
Trailer - HTTP
examples chunked transfer encoding using a trailing header in this example, the expires header is used at the end of the chunked message and serves as a trailing header.
Transfer-Encoding - HTTP
examples chunked encoding chunked encoding is useful when larger amounts of data are sent to the client and the total size of the response may not be known until the request has been fully processed.
Upgrade-Insecure-Requests - HTTP
header type request header forbidden header name no syntax upgrade-insecure-requests: 1
examples a client's request signals to the server that it supports the upgrade mechanisms of upgrade-insecure-requests: get / http/1.1 host: example.com upgrade-insecure-requests: 1 the server can now redirect to a secure version of the site.
Vary - HTTP
examples dynamic serving when using the vary: user-agent header, caching servers should consider the user agent when deciding whether to serve the page from cache.
Via - HTTP
examples via: 1.1 vegur via: http/1.1 gwa via: 1.0 fred, 1.1 p.example.net specifications specification title rfc 7230, section 5.7.1: via hypertext transfer protocol (http/1.1): message syntax and routing ...
WWW-Authenticate - HTTP
examples typically, a server response contains a www-authenticate header that looks like these: www-authenticate: basic www-authenticate: basic realm="access to the staging site", charset="utf-8" see also http authentication for
examples on how to configure apache or nginx servers to password protect your site with http basic authentication.
Want-Digest - HTTP
examples want-digest: sha-256 want-digest: sha-512;q=0.3, sha-256;q=1, md5;q=0 basic operation the sender provides a list of digests which it is prepared to accept, and the server uses one of them: request: get /item want-digest: sha-256;q=0.3, sha;q=1 response: http/1.1 200 ok digest: sha-256=x48e9qookqqrvdts8nojrjn3owduoywxbf7kbu9dbpe= unsupported digests the server does not support any...
Warning - HTTP
299 miscellaneous persistent warning same as 199, but indicating a persistent warning
examples warning: 110 anderson/1.3.37 "response is stale" date: wed, 21 oct 2015 07:28:00 gmt warning: 112 - "cache down" "wed, 21 oct 2015 07:28:00 gmt" specifications specification title rfc 7234, section 5.5: warning hypertext transfer protocol (http/1.1): caching ...
X-DNS-Prefetch-Control - HTTP
examples turning on and off prefetching you can either send the x-dns-prefetch-control header server-side, or from individual documents, using the http-equiv attribute on the <meta> element, like this: <meta http-equiv="x-dns-prefetch-control" content="off"> you can reverse this setting by setting content to "on".
X-Forwarded-For - HTTP
examples x-forwarded-for: 2001:db8:85a3:8d3:1319:8a2e:370:7348 x-forwarded-for: 203.0.113.195 x-forwarded-for: 203.0.113.195, 70.41.3.18, 150.172.238.178 other non-standard forms: # used for some google services x-proxyuser-ip: 203.0.113.19 specifications not part of any current specification.
X-Forwarded-Host - HTTP
examples x-forwarded-host: id42.example-cdn.com specifications not part of any current specification.
X-Forwarded-Proto - HTTP
examples x-forwarded-proto: https other non-standard forms: # microsoft front-end-https: on x-forwarded-protocol: https x-forwarded-ssl: on x-url-scheme: https specifications not part of any current specification.
Link prefetching FAQ - HTTP
some more
examples follow: <link rel="prefetch alternate stylesheet" title="designed for mozilla" href="mozspecific.css"> <link rel="next" href="2.html"> are anchor (<a>) tags prefetched?
OPTIONS - HTTP
request has body no successful response has body yes safe yes idempotent yes cacheable no allowed in html forms no syntax options /index.html http/1.1 options * http/1.1
examples identifying allowed request methods to find out which request methods a server supports, one can use the curl command-line program to issue an options request: curl -x options https://example.org -i the response then contains an allow header that holds the allowed methods: http/1.1 204 no content allow: options, get, head, post cache-control: max-age=604800 date: thu, 13 oct 2016 11:45:00 gm...
Network Error Logging - HTTP
the reporting group referenced above is defined in the usual manner within the report-to header, for example: report-to: { "group": "nel", "max_age": 31556952, "endpoints": [ { "url": "https://example.com/csp-reports" } ] } error reports in these
examples, the entire reporting api payload is shown.
Proxy servers and tunneling - HTTP
the example below 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"; } see proxy auto-configuration (pac) for more
examples.
206 Partial Content - HTTP
status 206 partial content
examples a response containing one single range: http/1.1 206 partial content date: wed, 15 nov 2015 06:25:24 gmt last-modified: wed, 15 nov 2015 04:58:08 gmt content-range: bytes 21010-47021/47022 content-length: 26012 content-type: image/gif ...
412 Precondition Failed - HTTP
status 412 precondition failed
examples etag: "33a64df551425fcc55e4d42a148795d9f25f89d4" etag: w/"0815" avoiding mid-air collisions with the help of the etag and the if-match headers, you can detect mid-air edit collisions.
426 Upgrade Required - HTTP
status 426 upgrade required
examples http/1.1 426 upgrade required upgrade: http/2.0 connection: upgrade content-length: 53 content-type: text/plain this service requires use of the http/2.0 protocol specifications specification title rfc 7231, section 6.5.15: 426 upgrade required hypertext transfer protocol (http/1.1): semantics and content ...
Groups and ranges - JavaScript
examples counting vowels var aliceexcerpt = "there was a long silence after this, and alice could only hear whispers now and then."; var regexpvowels = /[aeiouy]/g; console.log("number of vowels:", aliceexcerpt.match(regexpvowels).length); // number of vowels: 25 using groups let personlist = `first_name: john, last_name: doe first_name: jane, last_name: smith`; let regexpnames = /first_name: (\w+)...
Quantifiers - JavaScript
for example, given a string like "some <foo> <bar> new </bar> </foo> thing": /<.*>/ will match "<foo> <bar> new </bar> </foo>" /<.*?>/ will match "<foo>"
examples repeated pattern var wordendingwithas = /\w+a+\b/; var delicatemessage = "this is spartaaaaaaa"; console.table(delicatemessage.match(wordendingwithas)); // [ "spartaaaaaaa" ] counting characters var singleletterword = /\b\w\b/g; var notsolongword = /\b\w{1,6}\b/g; var loooongword = /\b\w{13,}\b/g; var sentence = "why do i have to learn multiplication table?"; console.table(sentence.match(...
Text formatting - JavaScript
(
examples should be added to this page after mdn bug 857438 is fixed.) see also string.fromcodepoint() or string.prototype.codepointat().
Working with objects - JavaScript
examples are as follows: // four variables are created and assigned in a single go, // separated by commas var myobj = new object(), str = 'mystring', rand = math.random(), obj = new object(); myobj.type = 'dot syntax'; myobj['date created'] = 'string with space'; myobj[str] = 'string value'; myobj[rand] = 'random number'; myobj[obj] = 'ob...
Private class fields - JavaScript
syntax class classwithprivatefield { #privatefield } class classwithprivatemethod { #privatemethod() { return 'hello world' } } class classwithprivatestaticfield { static #private_static_field }
examples private static fields private fields are accessible on the class constructor from inside the class declaration itself.
Public class fields - JavaScript
syntax class classwithinstancefield { instancefield = 'instance field' } class classwithstaticfield { static staticfield = 'static field' } class classwithpublicinstancemethod { publicmethod() { return 'hello world' } }
examples public static fields public static fields are useful when you want a field to exist only once per class, not on every class instance you create.
TypeError: invalid Array.prototype.sort argument - JavaScript
examples invalid cases [1, 3, 2].sort(5); // typeerror var cmp = { asc: (x, y) => x >= y, dsc: (x, y) => x <= y }; [1, 3, 2].sort(cmp[this.key] || 'asc'); // typeerror valid cases [1, 3, 2].sort(); // [1, 2, 3] var cmp = { asc: (x, y) => x >= y, dsc: (x, y) => x <= y }; [1, 3, 2].sort(cmp[this.key || 'asc']); // [1, 2, 3] ...
Warning: 08/09 is not a legal ECMA-262 octal constant - JavaScript
examples invalid octal numbers 08; 09; // syntaxerror: 08 is not a legal ecma-262 octal constant // syntaxerror: "0"-prefixed octal literals and octal escape sequences // are deprecated valid octal numbers use a leading zero followed by the letter "o"; 0o755; 0o644; ...
RangeError: radix must be an integer - JavaScript
examples invalid cases (42).tostring(0); (42).tostring(1); (42).tostring(37); (42).tostring(150); // you cannot use a string like this for formatting: (12071989).tostring('mm-dd-yyyy'); valid cases (42).tostring(2); // "101010" (binary) (13).tostring(8); // "15" (octal) (0x42).tostring(10); // "66" (decimal) (100000).tostring(16) // "186a0" (hexadecimal) ...
SyntaxError: return not in function - JavaScript
examples missing curly brackets var cheer = function(score) { if (score === 147) return 'maximum!'; }; if (score > 100) { return 'century!'; } } // syntaxerror: return not in function the curly brackets look correct at a first glance, but this code snippet is missing a { after the first if statement.
TypeError: cyclic object value - JavaScript
examples circular references in a circular structure like the following var circularreference = {otherdata: 123}; circularreference.myself = circularreference; json.stringify() will fail json.stringify(circularreference); // typeerror: cyclic object value to serialize circular references you can use a library that supports them (e.g.
SyntaxError: JSON.parse: bad parsing - JavaScript
examples json.parse() does not allow trailing commas both lines will throw a syntaxerror: json.parse('[1, 2, 3, 4,]'); json.parse('{"foo": 1,}'); // syntaxerror json.parse: unexpected character // at line 1 column 14 of the json data omit the trailing commas to parse the json correctly: json.parse('[1, 2, 3, 4]'); json.parse('{"foo": 1}'); property names must be double-quoted strings you cannot us...
SyntaxError: Malformed formal parameter - JavaScript
examples invalid cases var f = function('x y', 'return x + y;'); // syntaxerror (missing a comma) var f = function('x,', 'return x;'); // syntaxerror (extraneous comma) var f = function(37, "alert('ok')"); // syntaxerror (numbers can't be argument names) valid cases var f = function('x, y', 'return x + y;'); // correctly punctuated var f = function('x', 'return x;'); // if you can, avoid using f...
SyntaxError: missing ] after element list - JavaScript
examples incomplete array initializer var list = [1, 2, var instruments = [ 'ukulele', 'guitar', 'piano' }; var data = [{foo: 'bar'} {bar: 'foo'}]; correct would be: var list = [1, 2]; var instruments = [ 'ukulele', 'guitar', 'piano' ]; var data = [{foo: 'bar'}, {bar: 'foo'}]; ...
SyntaxError: missing } after function body - JavaScript
examples forgotten closing curly bracket oftentimes, there is a missing curly bracket in your function code: var charge = function() { if (sunny) { usesolarcells(); } else { promptbikeride(); }; correct would be: var charge = function() { if (sunny) { usesolarcells(); } else { promptbikeride(); } }; it can be more obscure when using iife, closures, or other constructs that...
SyntaxError: missing ) after condition - JavaScript
in javascript, this condition must appear in parenthesis after the if keyword, like this: if (condition) { // do something if the condition is true }
examples missing parenthesis it might just be an oversight, carefully check all you parenthesis in your code.
TypeError: More arguments needed - JavaScript
examples required arguments not provided the object.create() method requires at least one argument and the object.setprototypeof() method requires at least two arguments: var obj = object.create(); // typeerror: object.create requires at least 1 argument, but only 0 were passed var obj = object.setprototypeof({}); // typeerror: object.setprototypeof requires at least 2 arguments, but only 1 were passe...
TypeError: "x" is not a non-null object - JavaScript
examples property descriptor expected when methods like object.create() or object.defineproperty() and object.defineproperties() are used, the optional descriptor parameter expects a property descriptor object.
RangeError: argument is not a valid code point - JavaScript
examples invalid cases string.fromcodepoint('_'); // rangeerror string.fromcodepoint(infinity); // rangeerror string.fromcodepoint(-1); // rangeerror string.fromcodepoint(3.14); // rangeerror string.fromcodepoint(3e-2); // rangeerror string.fromcodepoint(nan); // rangeerror valid cases string.fromcodepoint(42); // "*" string.fromcodepoint(65, 90); // "az" string.fromcod...
TypeError: "x" is not a constructor - JavaScript
examples invalid cases var car = 1; new car(); // typeerror: car is not a constructor new math(); // typeerror: math is not a constructor new symbol(); // typeerror: symbol is not a constructor function* f() {}; var obj = new f; // typeerror: f is not a constructor a car constructor suppose you want to create an object type for cars.
TypeError: "x" is not a function - JavaScript
e methods working properly: when working with array or typedarray objects: array.prototype.every(), array.prototype.some(), array.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...
RangeError: precision is out of range - JavaScript
method firefox (spidermonkey) chrome, opera (v8) number.prototype.toexponential() 0 to 100 0 to 20 number.prototype.tofixed() -20 to 100 0 to 20 number.prototype.toprecision() 1 to 100 1 to 21
examples invalid cases 77.1234.toexponential(-1); // rangeerror 77.1234.toexponential(101); // rangeerror 2.34.tofixed(-100); // rangeerror 2.34.tofixed(1001); // rangeerror 1234.5.toprecision(-1); // rangeerror 1234.5.toprecision(101); // rangeerror valid cases 77.1234.toexponential(4); // 7.7123e+1 77.1234.toexponential(2); // 7.71e+1 2.34.tofixed(1); // 2.3 2.35.tofixed(...
Error: Permission denied to access property "x" - JavaScript
examples no permission to access document <!doctype html> <html> <head> <iframe id="myframe" src="http://www1.w3c-test.org/common/blank.html"></iframe> <script> onload = function() { console.log(frames[0].document); // error: permission denied to access property "document" } </script> </head> <body></body> </html> ...
SyntaxError: "x" is a reserved identifier - JavaScript
these are reserved in strict mode and sloppy mode: enum the following are only reserved when they are found in strict mode code: implements interface let package private protected public static
examples strict and non-strict reserved keywords the enum identifier is generally reserved.
RangeError: repeat count must be less than infinity - JavaScript
examples invalid cases 'abc'.repeat(infinity); // rangeerror 'a'.repeat(2**28); // rangeerror valid cases 'abc'.repeat(0); // '' 'abc'.repeat(1); // 'abc' 'abc'.repeat(2); // 'abcabc' 'abc'.repeat(3.5); // 'abcabcabc' (count will be converted to integer) ...
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: retu...
SyntaxError: "use strict" not allowed in function with non-simple parameters - JavaScript
examples function statement in this case, the function sum has default parameters a=1 and b=2: function sum(a = 1, b = 2) { // syntaxerror: "use strict" not allowed in function with default parameter 'use strict'; return a + b; } if the function should be in strict mode, and the entire script or enclosing function is also okay to be in strict mode, you can move the "use strict" directive outsid...
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 express...
SyntaxError: unterminated string literal - JavaScript
examples multiple lines you can't split a string across multiple lines like this in javascript: var longstring = 'this is a very long string which needs to wrap across multiple lines because otherwise my code is unreadable.'; // syntaxerror: unterminated string literal instead, use the + operator, a backslash, or template literals.
TypeError: invalid 'instanceof' operand 'x' - JavaScript
examples instanceof vs typeof "test" instanceof ""; // typeerror: invalid 'instanceof' operand "" 42 instanceof 0; // typeerror: invalid 'instanceof' operand 0 function foo() {} var f = foo(); // foo() is called and returns undefined var x = new foo(); x instanceof f; // typeerror: invalid 'instanceof' operand f x instanceof x; // typeerror: x is not a function to fix these e...
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 ?
arguments[@@iterator]() - JavaScript
syntax arguments[symbol.iterator]()
examples iteration using for...of loop function f() { // your browser must support for..of loop // and let-scoped variables in for loops for (let letter of arguments) { console.log(letter); } } f('w', 'y', 'k', 'o', 'p'); specifications specification ecmascript (ecma-262)the definition of 'createunmappedargumentsobject' in that specification.
arguments.callee - JavaScript
examples using arguments.callee in an anonymous recursive function a recursive function must be able to refer to itself.
AggregateError() constructor - JavaScript
examples creating an aggregateerror try { throw new aggregateerror([ new error("some error"), ], 'hello'); } catch (e) { console.log(e instanceof aggregateerror); // true console.log(e.message); // "hello" console.log(e.name); // "aggregateerror" console.log(e.errors); // [ error: "some error" ] } specifications specification promise.anythe definition of 'aggregateerror()' in tha...
AggregateError - JavaScript
examples catching an aggregateerror promise.any([ promise.reject(new error("some error")), ]).catch(e => { console.log(e instanceof aggregateerror); // true console.log(e.message); // "all promises rejected" console.log(e.name); // "aggregateerror" console.log(e.errors); // [ error: "some error" ] }); creating an aggregateerror try {...
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>...
get Array[@@species] - JavaScript
examples species in ordinary objects the species property returns the default constructor function, which is the array constructor for array objects: array[symbol.species]; // function array() species in derived objects in a derived collection object (e.g.
Array.prototype[@@unscopables] - JavaScript
property attributes of array.prototype[@@unscopables] writable no enumerable no configurable yes
examples use in with environments the following code works fine in es5 and below.
Array() constructor - JavaScript
examples array literal notation arrays can be created using the literal notation: let fruits = ['apple', 'banana']; console.log(fruits.length); // 2 console.log(fruits[0]); // "apple" array constructor with a single parameter arrays can be created using a constructor with a single number parameter.
Array.isArray() - JavaScript
if (!array.isarray) { array.isarray = function(arg) { return object.prototype.tostring.call(arg) === '[object array]'; }; }
examples using array.isarray // all following calls return true array.isarray([]); array.isarray([1]); array.isarray(new array()); array.isarray(new array('a', 'b', 'c', 'd')); array.isarray(new array(3)); // little known fact: array.prototype itself is an array: array.isarray(array.prototype); // all following calls return false array.isarray(); array.isarray({}); array.isarray(null); array.isarray(un...
Array.of() - JavaScript
if (!array.of) { array.of = function() { return array.prototype.slice.call(arguments); // or let vals = []; for(let prop in arguments){ vals.push(arguments[prop]); } return vals; } }
examples using array.of array.of(1); // [1] array.of(1, 2, 3); // [1, 2, 3] array.of(undefined); // [undefined] specifications specification ecmascript (ecma-262)the definition of 'array.of' in that specification.
Array.prototype.toSource() - JavaScript
examples examining the source code of an array to examine the source code of an array: var alpha = new array('a', 'b', 'c'); alpha.tosource(); //returns ['a', 'b', 'c'] specifications not part of any standard.
Array.prototype.toString() - JavaScript
examples using tostring const array1 = [1, 2, 'a', '1a']; console.log(array1.tostring()); // expected output: "1,2,a,1a" specifications specification ecmascript (ecma-262)the definition of 'array.prototype.tostring' in that specification.
Array.prototype.unshift() - JavaScript
see example: let arr = [4, 5, 6] arr.unshift(1, 2, 3) console.log(arr); // [1, 2, 3, 4, 5, 6] arr = [4, 5, 6] // resetting the array arr.unshift(1) arr.unshift(2) arr.unshift(3) console.log(arr) // [3, 2, 1, 4, 5, 6]
examples using unshift let arr = [1, 2] arr.unshift(0) // result of the call is 3, which is the new array length // arr is [0, 1, 2] arr.unshift(-2, -1) // the new array length is 5 // arr is [-2, -1, 0, 1, 2] arr.unshift([-4, -3]) // the new array length is 6 // arr is [[-4, -3], -2, -1, 0, 1, 2] arr.unshift([-7, -6], [-5]) // the new array length is 8 // arr is [ [-7...
Array.prototype.values() - JavaScript
examples iteration using for...of loop var arr = ['a', 'b', 'c', 'd', 'e']; var iterator = arr.values(); for (let letter of iterator) { console.log(letter); } //"a" "b" "c" "d" "e" array.prototype.values is default implementation of array.prototype[symbol.iterator].
Array - JavaScript
examples creating an array the following example creates an array, msgarray, with a length of 0, then assigns values to msgarray[0] and msgarray[99], changing the length of the array to 100.
get ArrayBuffer[@@species] - JavaScript
examples species in ordinary objects the species property returns the default constructor function, which is the arraybuffer constructor for arraybuffer objects: arraybuffer[symbol.species]; // function arraybuffer() species in derived objects in a derived collection object (e.g.
ArrayBuffer - JavaScript
examples creating an arraybuffer in this example, we create a 8-byte buffer with a int32array view referring to the buffer: const buffer = new arraybuffer(8); const view = new int32array(buffer); specifications specification ecmascript (ecma-262)the definition of 'arraybuffer' in that specification.
AsyncFunction - JavaScript
examples creating an async function from an asyncfunction() constructor function resolveafter2seconds(x) { return new promise(resolve => { settimeout(() => { resolve(x); }, 2000); }); } let asyncfunction = object.getprototypeof(async function(){}).constructor let a = new asyncfunction('a', 'b', 'return await resolveafter2seconds(a) ...
Atomics.notify() - JavaScript
examples using notify given a shared int32array: const sab = new sharedarraybuffer(1024); const int32 = new int32array(sab); a reading thread is sleeping and waiting on location 0 which is expected to be 0.
Atomics.wait() - JavaScript
examples using wait() given a shared int32array: const sab = new sharedarraybuffer(1024); const int32 = new int32array(sab); a reading thread is sleeping and waiting on location 0 which is expected to be 0.
Atomics - JavaScript
examples using atomics const sab = new sharedarraybuffer(1024); const ta = new uint8array(sab); ta[0] = 5; atomics.add(ta, 0, 12); atomics.load(ta, 0); // 12 atomics.and(ta, 0, 1); atomics.load(ta, 0); // 1 atomics.compareexchange(ta, 0, 5, 12); atomics.load(ta, 0); // 12 atomics.exchange(ta, 0, 12); atomics.load(ta, 0); // 12 atomics.islockfree(1); // true atomics.islockfree(2); // true atomics.i...
BigInt() constructor - JavaScript
examples creating a new bigint bigint(123); // 123n specifications specification ecmascript (ecma-262)the definition of 'bigint constructor' in that specification.
BigInt - JavaScript
however, you can implement your own tojson method if needed: bigint.prototype.tojson = function() { return this.tostring() } instead of throwing, json.stringify now produces a string like this: json.stringify(bigint(1)) // '"1"'
examples calculating primes // returns true if passed bigint is a prime number function isprime(p) { for (let i = 2n; i * i <= p; i++) { if (p % i === 0n) return false; } return true } // takes a bigint as an argument, returns nth prime number as bigint function nthprime(nth) { let maybeprime = 2n let prime = 0n while (nth >= 0n) { if (isprime(maybeprime)) { nth-- prime...
BigInt64Array() constructor - JavaScript
examples different ways to create a bigint64array // from a length var bigint64 = new bigint64array(2); bigint64[0] = 42n; console.log(bigint64[0]); // 42n console.log(bigint64.length); // 2 console.log(bigint64.bytes_per_element); // 8 // from an array var arr = new bigint64array([21n,31n]); console.log(arr[1]); // 31n // from another typedarray var x = new bigint64array([21n, 31n]); var y = new bigi...
BigInt64Array - JavaScript
examples different ways to create a bigint64array // from a length var bigint64 = new bigint64array(2); bigint64[0] = 42n; console.log(bigint64[0]); // 42n console.log(bigint64.length); // 2 console.log(bigint64.bytes_per_element); // 8 // from an array var arr = new bigint64array([21n,31n]); console.log(arr[1]); // 31n // from another typedarray var x = new bigint64array([21n, 31n]); var y = new bigi...
BigUint64Array() constructor - JavaScript
examples different ways to create a biguint64array // from a length var biguint64 = new biguint64array(2); biguint64[0] = 42n; console.log(biguint64[0]); // 42n console.log(biguint64.length); // 2 console.log(biguint64.bytes_per_element); // 8 // from an array var arr = new biguint64array([21n,31n]); console.log(arr[1]); // 31n // from another typedarray var x = new biguint64array([21n, 31n]); var y =...
BigUint64Array - JavaScript
examples different ways to create a biguint64array // from a length var biguint64 = new biguint64array(2); biguint64[0] = 42n; console.log(biguint64[0]); // 42n console.log(biguint64.length); // 2 console.log(biguint64.bytes_per_element); // 8 // from an array var arr = new biguint64array([21n,31n]); console.log(arr[1]); // 31n // from another typedarray var x = new biguint64array([21n, 31n]); var y =...
Boolean.prototype.toSource() - JavaScript
examples native function for the built-in boolean object, tosource returns the following string indicating that the source code is not available: function boolean() { [native code] } specifications not part of any standard.
Boolean - JavaScript
examples creating boolean objects with an initial value of false var bnoparam = new boolean(); var bzero = new boolean(0); var bnull = new boolean(null); var bemptystring = new boolean(''); var bfalse = new boolean(false); creating boolean objects with an initial value of true var btrue = new boolean(true); var btruestring = new boolean('true'); var bfalsestring = new boolean('false'); var bsulin = n...
DataView - JavaScript
examples using dataview var buffer = new arraybuffer(16); var view = new dataview(buffer, 0); view.setint16(1, 42); view.getint16(1); // 42 specifications specification ecmascript (ecma-262)the definition of 'dataview' in that specification.
Date.prototype[@@toPrimitive] - JavaScript
examples returning date primitives const testdate = new date(1590757517834); // "date fri may 29 2020 14:05:17 gmt+0100 (british summer time)" testdate[symbol.toprimitive]('string'); // returns "date fri may 29 2020 14:05:17 gmt+0100 (british summer time)" testdate[symbol.toprimitive]('number'); // returns "1590757517834" testdate[symbol.toprimitive]('default'); // returns "date fri may 29 2020 14:05...
Error.prototype.fileName - JavaScript
examples using filename var e = new error('could not parse input'); throw e; // e.filename could look like "file:///c:/example.html" specifications not part of any standard.
Error.prototype.lineNumber - JavaScript
examples using linenumber var e = new error('could not parse input'); throw e; console.log(e.linenumber) // 2 alternative example using error event window.addeventlistener('error', function(e) { console.log(e.linenumber); // 5 }); var e = new error('could not parse input'); throw e; this is not a standard feature and lacks widespread support.
Error.prototype.message - JavaScript
examples throwing a custom error var e = new error('could not parse input'); // e.message is 'could not parse input' throw e; specifications specification ecmascript (ecma-262)the definition of 'error.prototype.message' in that specification.
Error.prototype.name - JavaScript
examples throwing a custom error var e = new error('malformed input'); // e.name is 'error' e.name = 'parseerror'; throw e; // e.tostring() would return 'parseerror: malformed input' specifications specification ecmascript (ecma-262)the definition of 'error.prototype.name' in that specification.
Error.prototype.toSource() - JavaScript
examples using tosource calling the tosource method of an error instance (including nativeerrors) will return a string containing the source code of the error.
Error.prototype.toString() - JavaScript
'' : string(msg); if (name === '') { return msg; } if (msg === '') { return name; } return name + ': ' + msg; };
examples using tostring() var e = new error('fatal error'); console.log(e.tostring()); // 'error: fatal error' e.name = undefined; console.log(e.tostring()); // 'error: fatal error' e.name = ''; console.log(e.tostring()); // 'fatal error' e.message = undefined; console.log(e.tostring()); // '' e.name = 'hello'; console.log(e.tostring()); // 'hello' specifications specification ...
Error - JavaScript
examples throwing a generic error usually you create an error object with the intention of raising it using the throw keyword.
EvalError() constructor - JavaScript
the line number of the code that caused the exception
examples evalerror is not used in the current ecmascript specification and will thus not be thrown by the runtime.
EvalError - JavaScript
examples evalerror is not used in the current ecmascript specification and will thus not be thrown by the runtime.
FinalizationRegistry.prototype.register() - JavaScript
examples using register the following registers the target object referenced by target, passing in the held value "some value" and passing the target object itself as the unregistration token: registry.register(target, "some value", target); the following registers the target object referenced by target, passing in another object as the held value, and not passing in any unregistration token (which m...
FinalizationRegistry.prototype.unregister() - JavaScript
examples using unregister this example shows registering a target object using that same object as the unregister token, then later unregistering it via unregister: class thingy { #cleanup = label => { // ^^^^^−−−−− held value console.error( `the \`release\` method was never called for the object with the label "${label}"` ); }; #registry = ...
FinalizationRegistry - JavaScript
examples creating a new registry you create the registry passing in the callback: const registry = new finalizationregistry(heldvalue => { // ....
Float32Array() constructor - JavaScript
examples different ways to create a float32array // from a length var float32 = new float32array(2); float32[0] = 42; console.log(float32[0]); // 42 console.log(float32.length); // 2 console.log(float32.bytes_per_element); // 4 // from an array var arr = new float32array([21,31]); console.log(arr[1]); // 31 // from another typedarray var x = new float32array([21, 31]); var y = new float32array(x); con...
Float32Array - JavaScript
examples different ways to create a float32array // from a length var float32 = new float32array(2); float32[0] = 42; console.log(float32[0]); // 42 console.log(float32.length); // 2 console.log(float32.bytes_per_element); // 4 // from an array var arr = new float32array([21,31]); console.log(arr[1]); // 31 // from another typedarray var x = new float32array([21, 31]); var y = new float32array(x); con...
Float64Array() constructor - JavaScript
examples different ways to create a float64array // from a length var float64 = new float64array(2); float64[0] = 42; console.log(float64[0]); // 42 console.log(float64.length); // 2 console.log(float64.bytes_per_element); // 8 // from an array var arr = new float64array([21,31]); console.log(arr[1]); // 31 // from another typedarray var x = new float64array([21, 31]); var y = new float64array(x); con...
Float64Array - JavaScript
examples different ways to create a float64array // from a length var float64 = new float64array(2); float64[0] = 42; console.log(float64[0]); // 42 console.log(float64.length); // 2 console.log(float64.bytes_per_element); // 8 // from an array var arr = new float64array([21,31]); console.log(arr[1]); // 31 // from another typedarray var x = new float64array([21, 31]); var y = new float64array(x); con...
Function.arguments - JavaScript
examples using the arguments object function f(n) { g(n - 1) } function g(n) { console.log('before: ' + g.arguments[0]) if (n > 0) { f(n) } console.log('after: ' + g.arguments[0]) } f(2) console.log('returned: ' + g.arguments) // output // before: 1 // before: 0 // after: 0 // after: 1 // returned: null specifications not part of any standard.
Function.caller - JavaScript
examples checking the value of a function's caller property the following code checks the value a function's caller property.
Function.prototype.toSource() - JavaScript
examples native functions for the built-in function object, tosource() returns the following string indicating that the source code is not available: function function() { [native code] } custom functions for custom functions, tosource() returns the javascript source that defines the object as a string.
Function - JavaScript
examples difference between function constructor and function declaration functions created with the function constructor do not create closures to their creation contexts; they always are created in the global scope.
Generator.prototype.next() - JavaScript
examples using next() the following example shows a simple generator and the object that the next method returns: function* gen() { yield 1; yield 2; yield 3; } const g = gen(); // "generator { }" g.next(); // "object { value: 1, done: false }" g.next(); // "object { value: 2, done: false }" g.next(); // "object { value: 3, done: false }" g.next(); // "object { value: undefin...
Generator - JavaScript
examples an infinite iterator function* infinite() { let index = 0; while (true) { yield index++; } } const generator = infinite(); // "generator { }" console.log(generator.next().value); // 0 console.log(generator.next().value); // 1 console.log(generator.next().value); // 2 // ...
GeneratorFunction - JavaScript
examples creating a generator function from a generatorfunction() constructor var generatorfunction = object.getprototypeof(function*(){}).constructor var g = new generatorfunction('a', 'yield a * 2'); var iterator = g(10); console.log(iterator.next().value); // 20 specifications specification ecmascript (ecma-262)the definition of 'generatorfunction' in that specification.
Int16Array() constructor - JavaScript
examples different ways to create an int16array // from a length var int16 = new int16array(2); int16[0] = 42; console.log(int16[0]); // 42 console.log(int16.length); // 2 console.log(int16.bytes_per_element); // 2 // from an array var arr = new int16array([21,31]); console.log(arr[1]); // 31 // from another typedarray var x = new int16array([21, 31]); var y = new int16array(x); console.log(y[0]); // ...
Int16Array - JavaScript
examples different ways to create an int16array // from a length var int16 = new int16array(2); int16[0] = 42; console.log(int16[0]); // 42 console.log(int16.length); // 2 console.log(int16.bytes_per_element); // 2 // from an array var arr = new int16array([21,31]); console.log(arr[1]); // 31 // from another typedarray var x = new int16array([21, 31]); var y = new int16array(x); console.log(y[0]); // ...
Int32Array() constructor - JavaScript
examples different ways to create an int32array // from a length var int32 = new int32array(2); int32[0] = 42; console.log(int32[0]); // 42 console.log(int32.length); // 2 console.log(int32.bytes_per_element); // 4 // from an array var arr = new int32array([21,31]); console.log(arr[1]); // 31 // from another typedarray var x = new int32array([21, 31]); var y = new int32array(x); console.log(y[0]); // ...
Int32Array - JavaScript
examples different ways to create an int32array // from a length var int32 = new int32array(2); int32[0] = 42; console.log(int32[0]); // 42 console.log(int32.length); // 2 console.log(int32.bytes_per_element); // 4 // from an array var arr = new int32array([21,31]); console.log(arr[1]); // 31 // from another typedarray var x = new int32array([21, 31]); var y = new int32array(x); console.log(y[0]); // ...
Int8Array() constructor - JavaScript
examples different ways to create an int8array // from a length var int8 = new int8array(2); int8[0] = 42; console.log(int8[0]); // 42 console.log(int8.length); // 2 console.log(int8.bytes_per_element); // 1 // from an array var arr = new int8array([21,31]); console.log(arr[1]); // 31 // from another typedarray var x = new int8array([21, 31]); var y = new int8array(x); console.log(y[0]); // 21 // fro...
Int8Array - JavaScript
examples different ways to create an int8array // from a length var int8 = new int8array(2); int8[0] = 42; console.log(int8[0]); // 42 console.log(int8.length); // 2 console.log(int8.bytes_per_element); // 1 // from an array var arr = new int8array([21,31]); console.log(arr[1]); // 31 // from another typedarray var x = new int8array([21, 31]); var y = new int8array(x); console.log(y[0]); // 21 // fro...
InternalError() constructor - JavaScript
the line number of the code that caused the exception
examples creating a new internalerror new internalerror("engine failure"); specifications not part of any standard.
Intl.DateTimeFormat.prototype.formatToParts() - JavaScript
examples datetimeformat outputs localized, opaque strings that cannot be manipulated directly: var date = date.utc(2012, 11, 17, 3, 0, 42); var formatter = new intl.datetimeformat('en-us', { weekday: 'long', year: 'numeric', month: 'numeric', day: 'numeric', hour: 'numeric', minute: 'numeric', second: 'numeric', fractionalseconddigits: 3, hour12: true, timezone: 'utc' }); formatter...
Intl.DisplayNames.prototype.resolvedOptions() - JavaScript
examples using resolvedoptions const displaynames = new intl.displaynames(['de-de'], {type: 'region'}); const usedoptions = displaynames.resolvedoptions(); console.log(usedoptions.locale); // "de-de" console.log(usedoptions.style); // "long" console.log(usedoptions.type); // "region" console.log(usedoptions.fallback); // "code" specifications specification intl.display...
Intl.DisplayNames.supportedLocalesOf() - JavaScript
examples using supportedlocalesof assuming a runtime that supports indonesian and german but not balinese in date and time formatting, supportedlocalesof returns the indonesian and german language tags unchanged, even though pinyin collation is neither relevant to date and time formatting nor used with indonesian, and a specialized german for indonesia is unlikely to be supported.
Intl.ListFormat.prototype.formatToParts() - JavaScript
examples using formattoparts const fruits = ['apple', 'orange', 'pineapple']; const mylistformat = new intl.listformat('en-gb', { style: 'long', type: 'conjunction' }); console.table(mylistformat.formattoparts(fruits)); // [ // { "type": "element", "value": "apple" }, // { "type": "literal", "value": ", " }, // { "type": "element", "value": "orange" }, // { "type": "literal", "value": ", and " }, /...
Intl.ListFormat.prototype.resolvedOptions() - JavaScript
examples using resolvedoptions const delistformatter = new intl.listformat("de-de", { style: "short" }); const usedoptions = de.resolvedoptions(); console.log(usedoptions.locale); // "de-de" console.log(usedoptions.style); // "short" console.log(usedoptions.type); // "conjunction" (the default value) specifications specification intl.listformatthe definition of 'resolvedopti...
Intl.ListFormat.supportedLocalesOf() - JavaScript
examples using supportedlocalesof assuming a runtime that supports indonesian and german but not balinese in date and time formatting, supportedlocalesof returns the indonesian and german language tags unchanged, even though pinyin collation is neither relevant to date and time formatting nor used with indonesian, and a specialized german for indonesia is unlikely to be supported.
Intl.Locale() constructor - JavaScript
examples basic usage at its very simplest, the intl.locale constructor takes a locale identifier string as its argument: let us = new intl.locale('en-us'); using the locale constructor with an options object the constructor also takes an optional configuration object argument, which can contain any of several extension types.
Intl.Locale.prototype.baseName - JavaScript
examples basic example let myloc = new intl.locale("fr-latn-ca"); // sets locale to canadian french console.log(myloc.tostring()); // prints out "fr-latn-ca-u-ca-gregory" console.log(myloc.basename); // prints out "fr-latn-ca" example with options in the input string // sets language to japanese, region to japan, // calendar to gregorian, hour cycle to 24 hours let japan = new intl.locale("ja-jp-u-ca...
Intl.Locale.prototype.collation - JavaScript
stroke pinyin ordering for latin, stroke order for cjk characters (used in chinese) trad traditional style ordering (such as in spanish) unihan pinyin ordering for latin, unihan radical-stroke ordering for cjk characters (used in chinese) zhuyin pinyin ordering for latin, zhuyin order for bopomofo and cjk characters (used in chinese)
examples like other locale subtags, the collation type can be added to the intl.locale object via the locale string, or a configuration object argument to the constructor.
Intl.Locale.prototype.numberingSystem - JavaScript
i 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 numberingsystem represents correspond to the key nu.
Intl.Locale.prototype.region - JavaScript
examples setting the region in the locale identifer string argument the region is the third part of a valid unicode language identifier string, and can be set by adding it to the locale identifier string that is passed into the locale constructor.
Intl.Locale.prototype.script - JavaScript
examples setting the script in the locale identifer string argument the script is the second part of a valid unicode language identifier string, and can be set by adding it to the locale identifier string that is passed into the locale constructor.
Intl.Locale - JavaScript
examples basic usage at its very simplest, the intl.locale constructor takes a locale identifier string as its argument: let us = new intl.locale('en-us'); using the locale constructor with an options object the constructor also takes an optional configuration object argument, which can contain any of several extension types.
Intl.NumberFormat.prototype.formatToParts() - JavaScript
examples comparing format and formattoparts numberformat outputs localized, opaque strings that cannot be manipulated directly: var number = 3500; var formatter = new intl.numberformat('de-de', { style: 'currency', currency: 'eur' }); formatter.format(number); // "3.500,00 €" however, in many user interfaces there is a desire to customize the formatting of this string.
Intl.PluralRules.prototype.resolvedOptions() - JavaScript
examples using the resolvedoptions method var de = new intl.pluralrules('de-de'); var usedoptions = de.resolvedoptions(); usedoptions.locale; // "de-de" usedoptions.maximumfractiondigits; // 3 usedoptions.minimumfractiondigits; // 0 usedoptions.minimumintegerdigits; // 1 usedoptions.pluralcategories; // array [ "one", "other" ] usedoptions.type; // "cardinal" spe...
Intl.PluralRules.select() - JavaScript
examples using select() new intl.pluralrules('ar-eg').select(0); // → 'zero' new intl.pluralrules('ar-eg').select(1); // → 'one' new intl.pluralrules('ar-eg').select(2); // → 'two' new intl.pluralrules('ar-eg').select(6); // → 'few' new intl.pluralrules('ar-eg').select(18); // → 'many' specifications specification ecmascript internationalization api (ecma-402)the ...
Intl.PluralRules.supportedLocalesOf() - JavaScript
examples using supportedlocalesof() assuming a runtime that supports indonesian and german but not balinese in plural formatting, supportedlocalesof returns the indonesian and german language tags unchanged, even though pinyin collation is neither relevant to plural formatting nor used with indonesian, and a specialized german for indonesia is unlikely to be supported.
JSON - JavaScript
examples example json { "browsers": { "firefox": { "name": "firefox", "pref_url": "about:config", "releases": { "1": { "release_date": "2004-11-09", "status": "retired", "engine": "gecko", "engine_version": "1.7" } } } } } specifications specification ecmascript (ecma-262)the definition o...
get Map[@@species] - JavaScript
examples species in ordinary objects the species property returns the default constructor function, which is the map constructor for map objects: map[symbol.species]; // function map() species in derived objects in a derived collection object (e.g.
Map() constructor - JavaScript
examples creating a new map let mymap = new map([ [1, 'one'], [2, 'two'], [3, 'three'], ]) specifications specification ecmascript (ecma-262)the definition of 'map constructor' in that specification.
Map - JavaScript
examples using the map object let mymap = new map() let keystring = 'a string' let keyobj = {} let keyfunc = function() {} // setting the values mymap.set(keystring, "value associated with 'a string'") mymap.set(keyobj, 'value associated with keyobj') mymap.set(keyfunc, 'value associated with keyfunc') mymap.size // 3 // getting the values mymap.get(keystring) // "value associat...
Math.random() - JavaScript
examples note that as numbers in javascript are ieee 754 floating point numbers with round-to-nearest-even behavior, the ranges claimed for the functions below (excluding the one for math.random() itself) aren't exact.
Math.random() - JavaScript
examples note that as numbers in javascript are ieee 754 floating point numbers with round-to-nearest-even behavior, the ranges claimed for the functions below (excluding the one for math.random() itself) aren't exact.
Math.tanh() - JavaScript
-1 : (a - b) / (a + b); }
examples using math.tanh() math.tanh(0); // 0 math.tanh(infinity); // 1 math.tanh(1); // 0.7615941559557649 specifications specification ecmascript (ecma-262)the definition of 'math.tanh' in that specification.
Math - JavaScript
examples converting between degrees and radians the trigonometric functions sin(), cos(), tan(), asin(), acos(), atan(), and atan2() expect (and return) angles in radians.
Number.NaN - JavaScript
property attributes of number.nan writable no enumerable no configurable no
examples checking whether values are numeric function sanitise(x) { if (isnan(x)) { return number.nan; } return x; } testing against nan see testing against nan on the nan page.
Number() constructor - JavaScript
examples creating number objects const a = new number('123'); // a === 123 is false const b = number('123'); // b === 123 is true a instanceof number; // is true b instanceof number; // is false specifications specification ecmascript (ecma-262)the definition of 'number constructor' in that specification.
Number.prototype.toPrecision() - JavaScript
examples using toprecision let numobj = 5.123456 console.log(numobj.toprecision()) // logs '5.123456' console.log(numobj.toprecision(5)) // logs '5.1235' console.log(numobj.toprecision(2)) // logs '5.1' console.log(numobj.toprecision(1)) // logs '5' numobj = 0.000123 console.log(numobj.toprecision()) // logs '0.000123' console.log(numobj.toprecision(5)) // logs '0.00012300' console.log(...
Number.prototype.toSource() - JavaScript
examples native function for the built-in number object, tosource() returns the following string indicating that the source code is not available: function number() { [native code] } for instances of number, tosource() returns a string representing the source code.
Number - JavaScript
examples using the number object to assign values to numeric variables the following example uses the number object's properties to assign values to several numeric variables: const biggestnum = number.max_value const smallestnum = number.min_value const infinitenum = number.positive_infinity const neginfinitenum = number.negative_infinity const notanum = number.nan integer range for...
Object() constructor - JavaScript
examples creating a new object let o = new object() o.foo = 42 console.log(o) // object { foo: 42 } using object given undefined and null types the following
examples store an empty object object in o: let o = new object() let o = new object(undefined) let o = new object(null) specifications specification ecmascript (ecma-262)the definition of 'object constructor' in that...
Object.prototype.__defineGetter__() - JavaScript
examples non-standard and deprecated way var o = {}; o.__definegetter__('gimmefive', function() { return 5; }); console.log(o.gimmefive); // 5 standard-compliant ways // using the get operator var o = { get gimmefive() { return 5; } }; console.log(o.gimmefive); // 5 // using object.defineproperty var o = {}; object.defineproperty(o, 'gimmefive', { get: function() { return 5; } }); console.lo...
Object.prototype.__defineSetter__() - JavaScript
examples non-standard and deprecated way var o = {}; o.__definesetter__('value', function(val) { this.anothervalue = val; }); o.value = 5; console.log(o.value); // undefined console.log(o.anothervalue); // 5 standard-compliant ways // using the set operator var o = { set value(val) { this.anothervalue = val; } }; o.value = 5; console.log(o.value); // undefined console.log(o.anothervalue); // 5 // us...
Object.prototype.__lookupSetter__() - JavaScript
examples standard-compliant and non-standard ways to get a property setter var obj = { set foo(value) { this.bar = value; } }; // non-standard and deprecated way obj.__lookupsetter__('foo') // (function(value) { this.bar = value; }) // standard-compliant way object.getownpropertydescriptor(obj, 'foo').set; // (function(value) { this.bar = value; }) specifications specification ...
Object.prototype.constructor - JavaScript
let o = {} o.constructor === object // true let o = new object o.constructor === object // true let a = [] a.constructor === array // true let a = new array a.constructor === array // true let n = new number(3) n.constructor === number // true
examples displaying the constructor of an object the following example creates a constructor (tree) and an object of that type (thetree).
Object.getOwnPropertyDescriptors() - JavaScript
examples creating a shallow clone whereas the object.assign() method will only copy enumerable and own properties from a source object to a target object, you are able to use this method and object.create() for a shallow copy between two unknown objects: object.create( object.getprototypeof(obj), object.getownpropertydescriptors(obj) ); creating a subclass a typical way of creating a subclass is...
Object.getOwnPropertyNames() - JavaScript
object.getownpropertynames('foo'); // typeerror: "foo" is not an object (es5 code) object.getownpropertynames('foo'); // ["0", "1", "2", "length"] (es2015 code)
examples using object.getownpropertynames() var arr = ['a', 'b', 'c']; console.log(object.getownpropertynames(arr).sort()); // .sort() is an array method.
Object.is() - JavaScript
polyfill if (!object.is) { object.is = function(x, y) { // samevalue algorithm if (x === y) { // steps 1-5, 7-10 // steps 6.b-6.e: +0 != -0 return x !== 0 || 1 / x === 1 / y; } else { // step 6.a: nan == nan return x !== x && y !== y; } }; }
examples using object.is object.is('foo', 'foo'); // true object.is(window, window); // true object.is('foo', 'bar'); // false object.is([], []); // false var foo = { a: 1 }; var bar = { a: 1 }; object.is(foo, foo); // true object.is(foo, bar); // false object.is(null, null); // true // special cases object.is(0, -0); // false object.is(-0, -0); ...
Object.setPrototypeOf() - JavaScript
else { // if you want to return prototype of object.create(null): var fn = function() { for (var key in obj) { object.defineproperty(this, key, { value: obj[key], }); } }; fn.prototype = proto; return new fn(); } } }
examples using object.setprototypeof var dict = object.setprototypeof({}, null); specifications specification ecmascript (ecma-262)the definition of 'object.setprototypeof' in that specification.
Object.prototype.toSource() - JavaScript
examples using tosource() the following code defines the dog object type and creates thedog, an object of type dog: function dog(name, breed, color, sex) { this.name = name; this.breed = breed; this.color = color; this.sex = sex; } thedog = new dog('gabby', 'lab', 'chocolate', 'female'); calling the tosource() method of thedog displays the javascript source that defines the object: thedog.t...
Object - JavaScript
examples using object given undefined and null types the following
examples store an empty object object in o: let o = new object() let o = new object(undefined) let o = new object(null) using object to create boolean objects the following
examples store boolean objects in o: // equivalent to o = new boolean(true) let o = new object(true) // equivalent to o = new boolean(false) let o = new ob...
Promise.allSettled() - JavaScript
examples using promise.allsettled promise.allsettled([ promise.resolve(33), new promise(resolve => settimeout(() => resolve(66), 0)), 99, promise.reject(new error('an error')) ]) .then(values => console.log(values)); // [ // {status: "fulfilled", value: 33}, // {status: "fulfilled", value: 66}, // {status: "fulfilled", value: 99}, // {status: "rejected", reason: error: an error} // ] ...
Promise.any() - JavaScript
examples first to fulfil promise.any() resolves with the first promise to fulfil, even if a promise rejects first.
Promise.prototype.finally() - JavaScript
examples using finally let isloading = true; fetch(myrequest).then(function(response) { var contenttype = response.headers.get("content-type"); if(contenttype && contenttype.includes("application/json")) { return response.json(); } throw new typeerror("oops, we haven't got json!"); }) .then(function(json) { /* process your json further */ }) .catch(function(error) { console.
Promise.resolve() - JavaScript
examples using the static promise.resolve method promise.resolve('success').then(function(value) { console.log(value); // "success" }, function(value) { // not called }); resolving an array var p = promise.resolve([1,2,3]); p.then(function(v) { console.log(v[0]); // 1 }); resolving another promise var original = promise.resolve(33); var cast = promise.resolve(original); cast.then(function(va...
Proxy.revocable() - JavaScript
examples using proxy.revocable var revocable = proxy.revocable({}, { get: function(target, name) { return "[[" + name + "]]"; } }); var proxy = revocable.proxy; console.log(proxy.foo); // "[[foo]]" revocable.revoke(); console.log(proxy.foo); // typeerror is thrown proxy.foo = 1 // typeerror again delete proxy.foo; // still typeerror typeof proxy // "object", typeof d...
Proxy - JavaScript
examples basic example in this simple example, the number 37 gets returned as the default value when the property name is not in the object.
RangeError() constructor - JavaScript
filename optional the name of the file containing the code that caused the exception linenumber optional the line number of the code that caused the exception
examples using rangeerror (for numeric values) function check(n) { if( !(n >= -500 && n <= 500) ) { throw new rangeerror("the argument must be between -500 and 500.") } } try { check(2000) } catch(error) { if (error instanceof rangeerror) { // handle the error } } using rangeerror (for non-numeric values) function check(value) { if(["apple", "banana", "...
RangeError - JavaScript
examples using rangeerror (for numeric values) function check(n) { if( !(n >= -500 && n <= 500) ) { throw new rangeerror("the argument must be between -500 and 500.") } } try { check(2000) } catch(error) { if (error instanceof rangeerror) { // handle the error } } using rangeerror (for non-numeric values) function check(value) { if(["apple", "banana", "...
ReferenceError() constructor - JavaScript
examples catching a referenceerror try { let a = undefinedvariable } catch (e) { console.log(e instanceof referenceerror) // true console.log(e.message) // "undefinedvariable is not defined" console.log(e.name) // "referenceerror" console.log(e.filename) // "scratchpad/1" console.log(e.linenumber) // 2 console.log(...
ReferenceError - JavaScript
examples catching a referenceerror try { let a = undefinedvariable } catch (e) { console.log(e instanceof referenceerror) // true console.log(e.message) // "undefinedvariable is not defined" console.log(e.name) // "referenceerror" console.log(e.filename) // "scratchpad/1" console.log(e.linenumber) // 2 console.log(...
Reflect - JavaScript
examples detecting whether an object contains certain properties const duck = { name: 'maurice', color: 'white', greeting: function() { console.log(`quaaaack!
RegExp.prototype.dotAll - JavaScript
examples using dotall var str1 = 'bar\nexample foo example'; var regex1 = new regexp('bar.example','s'); console.log(regex1.dotall); // output: true console.log(str1.replace(regex1,'')); // output: foo example var str2 = 'bar\nexample foo example'; var regex2 = new regexp('bar.example'); console.log(regex2.dotall); // output: false console.log(str2.replace(regex2,'')); // output: bar ...
RegExp.input ($_) - JavaScript
examples using input and $_ var re = /hi/g; re.test('hi there!'); regexp.input; // "hi there!" re.test('foo'); // new test, non-matching regexp.$_; // "hi there!" re.test('hi world!'); // new test, matching regexp.$_; // "hi world!" specifications specification legacy regexp features in javascript ...
RegExp.lastMatch ($&) - JavaScript
examples using lastmatch and $& var re = /hi/g; re.test('hi there!'); regexp.lastmatch; // "hi" regexp['$&']; // "hi" specifications specification legacy regexp features in javascript ...
RegExp.lastParen ($+) - JavaScript
examples using lastparen and $+ var re = /(hi)/g; re.test('hi there!'); regexp.lastparen; // "hi" regexp['$+']; // "hi" specifications specification legacy regexp features in javascript ...
RegExp.leftContext ($`) - JavaScript
examples using leftcontext and $` var re = /world/g; re.test('hello world!'); regexp.leftcontext; // "hello " regexp['$`']; // "hello " specifications specification legacy regexp features in javascript ...
RegExp.$1-$9 - JavaScript
examples using $n with string.replace the following script uses the replace() method of the string instance to match a name in the format first last and output it in the format last, first.
RegExp.rightContext ($') - JavaScript
examples using rightcontext and $' var re = /hello/g; re.test('hello world!'); regexp.rightcontext; // " world!" regexp["$'"]; // " world!" specifications specification legacy regexp features in javascript ...
RegExp.prototype.toSource() - JavaScript
examples native function for the built-in regexp object, tosource() returns the following string indicating that the source code is not available: function regexp() { [native code] } for instances of regexp, tosource() returns a string representing the source code.
RegExp - JavaScript
examples using a regular expression to change data format the following script uses the replace() method of the string instance to match a name in the format first last and output it in the format last, first.
get Set[@@species] - JavaScript
examples species in ordinary objects the species property returns the default constructor function, which is the set constructor for set objects: set[symbol.species]; // function set() species in derived objects in a derived collection object (e.g.
SharedArrayBuffer - JavaScript
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...
String() constructor - JavaScript
examples string constructor and string function string function and string constructor produce different results: typeof string('hello world'); // string typeof new string('hello world'); // object here, the function produces a string (the primitive type) as promised.
String.prototype.anchor() - JavaScript
examples using anchor() var mystring = 'table of contents'; document.body.innerhtml = mystring.anchor('contents_anchor'); will output the following html: <a name="contents_anchor">table of contents</a> specifications specification ecmascript (ecma-262)the definition of 'string.prototype.anchor' in that specification.
String.prototype.big() - JavaScript
examples using big() the following example uses string methods to change the 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 a...
String.prototype.blink() - JavaScript
examples using blink() the following example uses string methods to change the formatting of a string: var worldstring = 'hello, world'; console.log(worldstring.blink()); // <blink>hello, world</blink> console.log(worldstring.bold()); // <b>hello, world</b> console.log(worldstring.italics()); // <i>hello, world</i> console.log(worldstring.strike()); // <strike>hello, world</strike> specifications ...
String.prototype.bold() - JavaScript
examples using bold() the following example uses string methods to change the formatting of a string: var worldstring = 'hello, world'; console.log(worldstring.blink()); // <blink>hello, world</blink> console.log(worldstring.bold()); // <b>hello, world</b> console.log(worldstring.italics()); // <i>hello, world</i> console.log(worldstring.strike()); // <strike>hello, world</strike> specifications specification ecmascript (ecma-262)the definition of 'string.prototype.bold' in that specification.
String.prototype.fixed() - JavaScript
examples using fixed() the following example uses the fixed method to change the formatting of a string: var worldstring = 'hello, world'; console.log(worldstring.fixed()); // "<tt>hello, world</tt>" specifications specification ecmascript (ecma-262)the definition of 'string.prototype.fixed' in that specification.
String.prototype.fontsize() - JavaScript
examples using fontsize() the following example uses string methods to change the 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)); // <font size="7">hello, world</fontsize> with the element.style object you can get the element'...
String.prototype.italics() - JavaScript
examples using italics() the following example uses string methods to change the formatting of a string: var worldstring = 'hello, world'; console.log(worldstring.blink()); // <blink>hello, world</blink> console.log(worldstring.bold()); // <b>hello, world</b> console.log(worldstring.italics()); // <i>hello, world</i> console.log(worldstring.strike()); // <strike>hello, world</strike> specifications specification ecmascript (ecma-262)the definition of 'string.prototype.italics' in that specification.
String length - JavaScript
iterator that is used here iterates over characters, // not mere code units return [...str].length; } console.log(getcharacterlength('a\ud87e\udc04z')); // 3 // while not recommended, you could add this to each string as follows: object.defineproperty(string.prototype, 'charlength', { get () { return getcharacterlength(this); } }); console.log('a\ud87e\udc04z'.charlength); // 3
examples basic usage let x = 'mozilla'; let empty = ''; console.log(x + ' is ' + x.length + ' code units long'); /* "mozilla is 7 code units long" */ console.log('the empty string has a length of ' + empty.length); // expected output: "the empty string has a length of 0" assigning to length let mystring = "bluebells"; // attempting to assign a value to a string's .length property has no observable ...
String.prototype.link() - JavaScript
examples using link() the following example displays the word "mdn" as a hypertext link that returns the user to the mozilla developer network.
String.raw() - JavaScript
examples using string.raw() string.raw`hi\n${2+3}!`; // 'hi\n5!', the character after 'hi' // is not a newline character, // '\' and 'n' are two characters.
String.prototype.small() - JavaScript
examples using small() the following example uses string methods to change the 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)); // <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.
String.prototype.strike() - JavaScript
examples using strike() the following example uses string methods to change the formatting of a string: var worldstring = 'hello, world'; console.log(worldstring.blink()); // <blink>hello, world</blink> console.log(worldstring.bold()); // <b>hello, world</b> console.log(worldstring.italics()); // <i>hello, world</i> console.log(worldstring.strike()); // <strike>hello, world</strike> specifications specification ecmascript (ecma-262)the definition of 'string.prototype.strike' in that specifi...
String.prototype.sub() - JavaScript
examples using sub() and sup() methods the following example uses the sub() and sup() methods to format a string: var supertext = 'superscript'; var subtext = 'subscript'; console.log('this is what a ' + supertext.sup() + ' looks like.'); // this is what a <sup>superscript</sup> looks like console.log('this is what a ' + subtext.sub() + ' looks like.'); // this is what a <sub>subscript</sub> looks like.
String.prototype.sup() - JavaScript
examples using sub() and sup() methods the following example uses the sub() and sup() methods to format a string: var supertext = 'superscript'; var subtext = 'subscript'; console.log('this is what a ' + supertext.sup() + ' looks like.'); // "this is what a <sup>superscript</sup> looks like." console.log('this is what a ' + subtext.sub() + ' looks like.'); // "this is what a <sub>subscript</sub> looks like." specifications specification ecmascript (ecma-262)the definition of 'string.prototype.sup' in that specificati...
String.prototype.toSource() - JavaScript
examples native function for the built-in string object, tosource() returns the following string indicating that the source code is not available: function string() { [native code] } for instances of string or string literals, tosource() returns a string representing the source code.
String.prototype.toString() - JavaScript
examples using tostring() the following example displays the string value of a string object: var x = new string('hello world'); console.log(x.tostring()); // logs 'hello world' specifications specification ecmascript (ecma-262)the definition of 'string.prototype.tostring' in that specification.
String.prototype.valueOf() - JavaScript
examples using valueof() var x = new string('hello world'); console.log(x.valueof()); // displays 'hello world' specifications specification ecmascript (ecma-262)the definition of 'string.prototype.valueof' in that specification.
String - JavaScript
() <blink> string.prototype.bold() <b> string.prototype.fixed() <tt> string.prototype.fontcolor() <font color="color"> string.prototype.fontsize() <font size="size"> string.prototype.italics() <i> string.prototype.link() <a href="url"> (link to url) string.prototype.small() <small> string.prototype.strike() <strike> string.prototype.sub() <sub> string.prototype.sup() <sup>
examples string conversion it's possible to use string as a more reliable tostring() alternative, as it works when used on null, undefined, and on symbols.
Symbol.prototype[@@toPrimitive] - JavaScript
examples using @@toprimitive const sym = symbol("example"); sym === sym[symbol.toprimitive](); // true specifications specification ecmascript (ecma-262)the definition of 'symbol.prototype.@@toprimitive' in that specification.
Symbol.prototype.toSource() - JavaScript
examples native function for the built-in symbol object, tosource returns the following string indicating that the source code is not available: "function symbol() { [native code] }" for instances of symbol, tosource returns a string representing the source code.
Symbol.prototype.valueOf() - JavaScript
examples using valueof const sym = symbol("example"); sym === sym.valueof(); // true specifications specification ecmascript (ecma-262)the definition of 'symbol.prototype.valueof' in that specification.
Symbol - JavaScript
examples using the typeof operator with symbols the typeof operator can help you to identify symbols.
SyntaxError() constructor - JavaScript
syntax new syntaxerror([message[, filename[, linenumber]]]) parameters message optional human-readable description of the error filename optional the name of the file containing the code that caused the exception linenumber optional the line number of the code that caused the exception
examples catching a syntaxerror try { eval('hoo bar'); } catch (e) { console.error(e instanceof syntaxerror); console.error(e.message); console.error(e.name); console.error(e.filename); console.error(e.linenumber); console.error(e.columnnumber); console.error(e.stack); } creating a syntaxerror try { throw new syntaxerror('hello', 'somefile.js', 10); } catch (e) { console.error(e i...
SyntaxError - JavaScript
examples catching a syntaxerror try { eval('hoo bar'); } catch (e) { console.error(e instanceof syntaxerror); console.error(e.message); console.error(e.name); console.error(e.filename); console.error(e.linenumber); console.error(e.columnnumber); console.error(e.stack); } creating a syntaxerror try { throw new syntaxerror('hello', 'somefile.js', 10); } catch (e) { console.error(e i...
TypeError() constructor - JavaScript
the line number of the code that caused the exception
examples catching a typeerror try { null.f() } catch (e) { console.log(e instanceof typeerror) // true console.log(e.message) // "null has no properties" console.log(e.name) // "typeerror" console.log(e.filename) // "scratchpad/1" console.log(e.linenumber) // 2 console.log(e.columnnumber) // 2 console.log(e.stack) ...
TypeError - JavaScript
examples catching a typeerror try { null.f() } catch (e) { console.log(e instanceof typeerror) // true console.log(e.message) // "null has no properties" console.log(e.name) // "typeerror" console.log(e.filename) // "scratchpad/1" console.log(e.linenumber) // 2 console.log(e.columnnumber) // 2 console.log(e.stack) ...
TypedArray.prototype[@@iterator]() - JavaScript
examples iteration using for...of loop var arr = new uint8array([10, 20, 30, 40, 50]); // your browser must support for..of loop // and let-scoped variables in for loops for (let n of arr) { console.log(n); } alternative iteration var arr = new uint8array([10, 20, 30, 40, 50]); var earr = arr[symbol.iterator](); console.log(earr.next().value); // 10 console.log(earr.next().value); // 20 console.log(earr.next().value); // 30 console.log(earr.next().value); // 40 console.log(earr.next().value); // 50 specifications specification ecmascri...
get TypedArray[@@species] - JavaScript
examples species in ordinary objects the species property returns the default constructor function, which is one of the typed array constructors for a given typed array object: int8array[symbol.species]; // function int8array() uint8array[symbol.species]; // function uint8array() float32array[symbol.species]; // function float32array() species in derived objects in a derived collection object (e.g.
TypedArray.prototype.byteOffset - JavaScript
examples using the byteoffset property var buffer = new arraybuffer(8); var uint8 = new uint8array(buffer); uint8.byteoffset; // 0 (no offset specified) var uint8 = new uint8array(buffer, 3); uint8.byteoffset; // 3 (as specified when constructing uint8array) specifications specification ecmascript (ecma-262)the definition of 'typedarray.prototype.byteoffset' in that specification.
TypedArray.prototype.forEach() - JavaScript
examples logging the contents of a typed array the following code logs a line for each element in a typed array: function logarrayelements(element, index, array) { console.log('a[' + index + '] = ' + element); } new uint8array([0, 1, 2, 3]).foreach(logarrayelements); // logs: // a[0] = 0 // a[1] = 1 // a[2] = 2 // a[3] = 3 specifications specification ecmascript (ecma-262)the de...
TypedArray.prototype.reduceRight() - JavaScript
examples sum up all values within an array var total = new uint8array([0, 1, 2, 3]).reduceright(function(a, b) { return a + b; }); // total == 6 specifications specification ecmascript (ecma-262)the definition of '%typedarray%.prototype.reduceright' in that specification.
TypedArray.prototype.toLocaleString() - JavaScript
examples using tolocalestring var uint = new uint32array([2000, 500, 8123, 12, 4212]); uint.tolocalestring(); // if run in a de-de locale // "2.000,500,8.123,12,4.212" uint.tolocalestring('en-us'); // "2,000,500,8,123,12,4,212" uint.tolocalestring('ja-jp', { style: 'currency', currency: 'jpy' }); // "¥2,000,¥500,¥8,123,¥12,¥4,212" specifications specification ecmascript...
URIError() constructor - JavaScript
examples catching an urierror try { decodeuricomponent('%') } catch (e) { console.log(e instanceof urierror) // true console.log(e.message) // "malformed uri sequence" console.log(e.name) // "urierror" console.log(e.filename) // "scratchpad/1" console.log(e.linenumber) // 2 console.log(e.columnnumber) // 2 console.log(e.stack) ...
URIError - JavaScript
examples catching an urierror try { decodeuricomponent('%') } catch (e) { console.log(e instanceof urierror) // true console.log(e.message) // "malformed uri sequence" console.log(e.name) // "urierror" console.log(e.filename) // "scratchpad/1" console.log(e.linenumber) // 2 console.log(e.columnnumber) // 2 console.log(e.stack) ...
Uint16Array() constructor - JavaScript
var dv = uint16array([1, 2, 3]); // typeerror: calling a builtin uint16array constructor // without new is forbidden var dv = new uint16array([1, 2, 3]);
examples different ways to create a uint16array // from a length var uint16 = new uint16array(2); uint16[0] = 42; console.log(uint16[0]); // 42 console.log(uint16.length); // 2 console.log(uint16.bytes_per_element); // 2 // from an array var arr = new uint16array([21,31]); console.log(arr[1]); // 31 // from another typedarray var x = new uint16array([21, 31]); var y = new uint16array(x); console.log(y...
Uint16Array - JavaScript
examples different ways to create a uint16array // from a length var uint16 = new uint16array(2); uint16[0] = 42; console.log(uint16[0]); // 42 console.log(uint16.length); // 2 console.log(uint16.bytes_per_element); // 2 // from an array var arr = new uint16array([21,31]); console.log(arr[1]); // 31 // from another typedarray var x = new uint16array([21, 31]); var y = new uint16array(x); console.log(y...
Uint32Array() constructor - JavaScript
examples different ways to create a uint32array // from a length var uint32 = new uint32array(2); uint32[0] = 42; console.log(uint32[0]); // 42 console.log(uint32.length); // 2 console.log(uint32.bytes_per_element); // 4 // from an array var arr = new uint32array([21,31]); console.log(arr[1]); // 31 // from another typedarray var x = new uint32array([21, 31]); var y = new uint32array(x); console.log(y...
Uint32Array - JavaScript
examples different ways to create a uint32array // from a length var uint32 = new uint32array(2); uint32[0] = 42; console.log(uint32[0]); // 42 console.log(uint32.length); // 2 console.log(uint32.bytes_per_element); // 4 // from an array var arr = new uint32array([21,31]); console.log(arr[1]); // 31 // from another typedarray var x = new uint32array([21, 31]); var y = new uint32array(x); console.log(y...
Uint8Array() constructor - JavaScript
examples different ways to create a uint8array // from a length var uint8 = new uint8array(2); uint8[0] = 42; console.log(uint8[0]); // 42 console.log(uint8.length); // 2 console.log(uint8.bytes_per_element); // 1 // from an array var arr = new uint8array([21,31]); console.log(arr[1]); // 31 // from another typedarray var x = new uint8array([21, 31]); var y = new uint8array(x); console.log(y[0]); // 2...
Uint8Array - JavaScript
examples different ways to create a uint8array // from a length var uint8 = new uint8array(2); uint8[0] = 42; console.log(uint8[0]); // 42 console.log(uint8.length); // 2 console.log(uint8.bytes_per_element); // 1 // from an array var arr = new uint8array([21,31]); console.log(arr[1]); // 31 // from another typedarray var x = new uint8array([21, 31]); var y = new uint8array(x); console.log(y[0]); // 2...
Uint8ClampedArray() constructor - JavaScript
examples different ways to create a uint8clampedarray // from a length var uintc8 = new uint8clampedarray(2); uintc8[0] = 42; uintc8[1] = 1337; console.log(uintc8[0]); // 42 console.log(uintc8[1]); // 255 (clamped) console.log(uintc8.length); // 2 console.log(uintc8.bytes_per_element); // 1 // from an array var arr = new uint8clampedarray([21,31]); console.log(arr[1]); // 31 // from another typedarray...
Uint8ClampedArray - JavaScript
examples different ways to create a uint8clampedarray // from a length var uintc8 = new uint8clampedarray(2); uintc8[0] = 42; uintc8[1] = 1337; console.log(uintc8[0]); // 42 console.log(uintc8[1]); // 255 (clamped) console.log(uintc8.length); // 2 console.log(uintc8.bytes_per_element); // 1 // from an array var arr = new uint8clampedarray([21,31]); console.log(arr[1]); // 31 // from another typedarray...
WeakMap() constructor - JavaScript
examples using weakmap const wm1 = new weakmap(), wm2 = new weakmap(), wm3 = new weakmap(); const o1 = {}, o2 = function() {}, o3 = window; wm1.set(o1, 37); wm1.set(o2, 'azerty'); wm2.set(o1, o2); // a value can be anything, including an object or a function wm2.set(o3, undefined); wm2.set(wm1, wm2); // keys and values can be any objects.
WeakMap.prototype.clear() - JavaScript
syntax wm.clear();
examples using the clear method var wm = new weakmap(); var obj = {}; wm.set(obj, 'foo'); wm.set(window, 'bar'); wm.has(obj); // true wm.has(window); // true wm.clear(); wm.has(obj) // false wm.has(window) // false specifications not part of any standard.
WeakMap - JavaScript
examples using weakmap const wm1 = new weakmap(), wm2 = new weakmap(), wm3 = new weakmap(); const o1 = {}, o2 = function() {}, o3 = window; wm1.set(o1, 37); wm1.set(o2, 'azerty'); wm2.set(o1, o2); // a value can be anything, including an object or a function wm2.set(o3, undefined); wm2.set(wm1, wm2); // keys and values can be any objects.
WeakRef - JavaScript
examples using a weakref object this example starts a counter shown in a dom element, stopping when the element doesn't exist anymore: class counter { constructor(element) { // remember a weak reference to the dom element this.ref = new weakref(element); this.start(); } start() { if (this.timer) { return; } this.count = 0; const tick = () => { // get the...
WeakSet() constructor - JavaScript
examples using the weakset object var ws = new weakset(); var foo = {}; var bar = {}; ws.add(foo); ws.add(bar); ws.has(foo); // true ws.has(bar); // true ws.delete(foo); // removes foo from the set ws.has(foo); // false, foo has been removed ws.has(bar); // true, bar is retained note that foo !== bar.
WeakSet.prototype.clear() - JavaScript
syntax ws.clear();
examples using the clear method var ws = new weakset(); ws.add(window); ws.has(window); // true ws.clear(); ws.has(window); // false specifications not part of any standard.
WeakSet - JavaScript
examples using the weakset object const ws = new weakset(); const foo = {}; const bar = {}; ws.add(foo); ws.add(bar); ws.has(foo); // true ws.has(bar); // true ws.delete(foo); // removes foo from the set ws.has(foo); // false, foo has been removed ws.has(bar); // true, bar is retained note that foo !== bar.
WebAssembly.CompileError() constructor - JavaScript
examples creating a new compileerror instance the following snippet creates a new compileerror instance, and logs its details to the console: try { throw new webassembly.compileerror('hello', 'somefile', 10); } catch (e) { console.log(e instanceof compileerror); // true console.log(e.message); // "hello" console.log(e.name); // "compileerror" console.log(e.f...
WebAssembly.CompileError - JavaScript
examples creating a new compileerror instance the following snippet creates a new compileerror instance, and logs its details to the console: try { throw new webassembly.compileerror('hello', 'somefile', 10); } catch (e) { console.log(e instanceof compileerror); // true console.log(e.message); // "hello" console.log(e.name); // "compileerror" console.log(e.f...
WebAssembly.Global - JavaScript
examples creating a new global instance the following example shows a new global instance being created using the webassembly.global() constructor.
WebAssembly.Instance() constructor - JavaScript
examples synchronously instantiating a webassembly module the webassembly.instance() constructor function can be called to synchronously instantiate a given webassembly.module object, for example: const importobject = { imports: { imported_func: function(arg) { console.log(arg); } } }; fetch('simple.wasm').then(response => response.arraybuffer() ).then(bytes => { let mod = new we...
WebAssembly.Instance.prototype.exports - JavaScript
instance.exports
examples using exports after fetching some webassembly bytecode using fetch, we compile and instantiate the module using the webassembly.instantiatestreaming() function, importing a javascript function into the webassembly module in the process.
WebAssembly.Instance - JavaScript
examples synchronously instantiating a webassembly module the webassembly.instance() constructor function can be called to synchronously instantiate a given webassembly.module object, for example: const importobject = { imports: { imported_func: function(arg) { console.log(arg); } } }; fetch('simple.wasm').then(response => response.arraybuffer() ).then(bytes => { let mod = new we...
WebAssembly.LinkError() constructor - JavaScript
examples creating a new linkerror instance the following snippet creates a new linkerror instance, and logs its details to the console: try { throw new webassembly.linkerror('hello', 'somefile', 10); } catch (e) { console.log(e instanceof linkerror); // true console.log(e.message); // "hello" console.log(e.name); // "linkerror" console.log(e.filename); ...
WebAssembly.LinkError - JavaScript
examples creating a new linkerror instance the following snippet creates a new linkerror instance, and logs its details to the console: try { throw new webassembly.linkerror('hello', 'somefile', 10); } catch (e) { console.log(e instanceof linkerror); // true console.log(e.message); // "hello" console.log(e.name); // "linkerror" console.log(e.filename); ...
WebAssembly.Memory.prototype.buffer - JavaScript
examples using buffer the following example (see memory.html on github, and view it live also) fetches and instantiates the loaded memory.wasm byte code using the webassembly.instantiatestreaming() method, while importing the memory created in the line above.
WebAssembly.Module() constructor - JavaScript
examples synchronously compiling a webassembly module var importobject = { imports: { imported_func: function(arg) { console.log(arg); } } }; function createwasmmodule(bytes) { return new webassembly.module(bytes); } fetch('simple.wasm').then(response => response.arraybuffer() ).then(bytes => { let mod = createwasmmodule(bytes); webassembly.instantiate(mod, importobject) .t...
WebAssembly.Module.customSections() - JavaScript
the wast2wasm command available as part of the wabt tool has a --debug-names option — specify this during conversion to get a .wasm with a names custom section, for example: wast2wasm simple-name-section.was -o simple-name-section.wasm --debug-names
examples using customsections the following example (see the custom-section.html source and live example) compiles the loaded simple-name-section.wasm byte code.
WebAssembly.validate() - JavaScript
examples using validate the following example (see the validate.html source code, and see it live too) fetches a .wasm module and converts it into a typed array.
WebAssembly - JavaScript
examples stream a .wasm module then compile and instantiate it the following example (see our instantiate-streaming.html demo on github, and view it live also) directly streams a .wasm module from an underlying source then compiles and instantiates it, the promise fulfilling with a resultobject.
escape() - JavaScript
examples using escape escape('abc123'); // "abc123" escape('äöü'); // "%e4%f6%fc" escape('ć'); // "%u0107" // special characters escape('@*_+-./'); // "@*_+-./" specifications specification ecmascript (ecma-262)the definition of 'escape' in that specification.
isNaN() - JavaScript
a polyfill for isnan would be (the polyfill leverages the unique never-equal-to-itself characteristic of nan): var isnan = function(value) { var n = number(value); return n !== n; };
examples isnan(nan); // true isnan(undefined); // true isnan({}); // true isnan(true); // false isnan(null); // false isnan(37); // false // strings isnan('37'); // false: "37" is converted to the number 37 which is not nan isnan('37.37'); // false: "37.37" is converted to the number 37.37 which is not nan isnan("37,5"); // true isnan('123abc'); // true: parsei...
unescape() - JavaScript
examples using unescape unescape('abc123'); // "abc123" unescape('%e4%f6%fc'); // "äöü" unescape('%u0107'); // "ć" specifications specification ecmascript (ecma-262)the definition of 'unescape' in that specification.
uneval() - JavaScript
examples using uneval var a = 1; uneval(a); // returns a string containing 1 var b = '1'; uneval(b); // returns a string containing "1" uneval(function foo() {}); // returns "(function foo(){})" var a = uneval(function foo() { return 'hi'; }); var foo = eval(a); foo(); // returns "hi" specifications not part of any standard.
async function expression - JavaScript
examples simple example function resolveafter2seconds(x) { return new promise(resolve => { settimeout(() => { resolve(x); }, 2000); }); }; const add = async function(x) { // async function expression assigned to a variable let a = await resolveafter2seconds(20); let b = await resolveafter2seconds(30); return x + a + b; }; add(10).then(v => { console.log(v); // prints 60 aft...
await - JavaScript
examples awaiting a promise to be fulfilled if a promise is passed to an await expression, it waits for the promise to be fulfilled and returns the fulfilled value.
super - JavaScript
examples using super in classes this code snippet is taken from the classes sample (live demo).
debugger - JavaScript
syntax debugger;
examples using the debugger statement the following example shows code where a debugger statement has been inserted, to invoke a debugger (if one exists) when the function is called.
export - JavaScript
note: the following is syntactically invalid despite its import equivalent: import defaultexport from 'bar.js'; // valid export defaultexport from 'bar.js'; // invalid the correct way of doing this is to rename the export: export { default as defaultexport } from 'bar.js';
examples using named exports in a module my-module.js, we could include the following code: // module "my-module.js" function cube(x) { return x * x * x; } const foo = math.pi + math.sqrt2; var graph = { options: { color:'white', thickness:'2px' }, draw: function() { console.log('from graph draw function'); } } export { cube, foo, graph }; then in the top-level module i...
for await...of - JavaScript
examples iterating over async iterables you can also iterate over an object that explicitly implements async iterable protocol: const asynciterable = { [symbol.asynciterator]() { return { i: 0, next() { if (this.i < 3) { return promise.resolve({ value: this.i++, done: false }); } return promise.resolve({ done: true }); } }; } }; (async f...
import.meta - JavaScript
examples using import.meta given a module my-module.js <script type="module" src="my-module.js"></script> you can access meta information about the module using the import.meta object.
with - JavaScript
examples using with the following with statement specifies that the math object is the default object.
Trailing commas - JavaScript
syntax ,
examples trailing commas in literals arrays javascript ignores trailing commas in arrays: var arr = [ 1, 2, 3, ]; arr; // [1, 2, 3] arr.length; // 3 if more than one trailing comma is used, an elision (or hole) is produced.
background_color - Web app manifests
examples "background_color": "red" specification specification status comment feedback web app manifestthe definition of 'background_color' in that specification.
description - Web app manifests
examples simple description in left-to-right language: "description": "awesome application that will help you achieve your dreams." description in arabic, which will be displayed right-to-left: "dir": "rtl", "lang": "ar", "description": ".تطبيق رائع سيساعدك على تحقيق أحلامك" specification specification status comment feedback web app manifestthe definition of 'description' in that specification.
iarc_rating_id - Web app manifests
examples "iarc_rating_id": "e84b072d-71b3-4d3e-86ae-31a8ce4e53b7" specification specification status comment feedback web app manifestthe definition of 'iarc_rating_id' in that specification.
icons - Web app manifests
examples "icons": [ { "src": "icon/lowres.webp", "sizes": "48x48", "type": "image/webp" }, { "src": "icon/lowres", "sizes": "48x48" }, { "src": "icon/hd_hi.ico", "sizes": "72x72 96x96 128x128 256x256" }, { "src": "icon/hd_hi.svg", "sizes": "72x72" } ] values image objects may contain the following values: member description sizes a string co...
lang - Web app manifests
examples "lang": "en-us" specification specification status comment feedback web app manifestthe definition of 'lang' in that specification.
name - Web app manifests
examples simple name in left-to-right language: "name": "awesome application" right-to-left name in arabic: "dir": "rtl", "lang": "ar", "name": "!أنا من التطبيق" specification specification status comment feedback web app manifestthe definition of 'name' in that specification.
orientation - Web app manifests
values orientation can take one of the following values: any natural landscape landscape-primary landscape-secondary portrait portrait-primary portrait-secondary
examples "orientation": "portrait-primary" specification specification status comment feedback web app manifestthe definition of 'orientation' in that specification.
related_applications - Web app manifests
examples "related_applications": [ { "platform": "play", "url": "https://play.google.com/store/apps/details?id=com.example.app1", "id": "com.example.app1" }, { "platform": "itunes", "url": "https://itunes.apple.com/app/example-app1/id123456789" } ] related application values application objects may contain the following values: member description plat...
scope - Web app manifests
examples if the scope is relative, the manifest url is used as a base url: "scope": "/app/" the following scope limits navigation to the current site: "scope": "https://example.com/" finally, the following example limits navigation to a subdirectory of the current site: "scope": "https://example.com/subdirectory/" specification specification status comment feedback ...
screenshots - Web app manifests
examples "screenshots" : [ { "src": "screenshot1.webp", "sizes": "1280x720", "type": "image/webp" }, { "src": "screenshot2.webp", "sizes": "1280x720", "type": "image/webp" } ] specification specification status comment feedback web app manifestthe definition of 'screenshots' in that specification.
serviceworker - Web app manifests
examples "serviceworker": { "src": "./serviceworker.js", "scope": "/app", "type": "", "update_via_cache": "none" } values service worker contain the following values (only src is required): member description src the url to download the service worker script from.
short_name - Web app manifests
examples simple short_name in left-to-right language: "name": "awesome application", "short_name": "awesome app" short_name in arabic, which will be displayed right-to-left: "dir": "rtl", "lang": "ar", "name": "تطبيق رائع", "short_name": "رائع" specification specification status comment feedback web app manifestthe definition of 'short_name' in that ...
shortcuts - Web app manifests
examples the following is a list of shortcuts a calendar app might have: "shortcuts" : [ { "name": "today's agenda", "url": "/today", "description": "list of events planned for today" }, { "name": "new event", "url": "/create/event" }, { "name": "new reminder", "url": "/create/reminder" } ] specification specification status comment feedback ...
start_url - Web app manifests
examples absolute url "start_url": "https://example.com" relative url if the url is relative, the manifest url is used as the base url to resolve it.
theme_color - Web app manifests
examples "theme_color": "red" specification specification status comment feedback web app manifestthe definition of 'theme_color' in that specification.
<maction> - MathML
examples the following example uses the "toggle" actiontype: <math> <maction actiontype="toggle"> <mfrac> <mn>6</mn> <mn>8</mn> </mfrac> <mfrac> <mrow> <mn>3</mn> <mo>⋅</mo> <mn>2</mn> </mrow> <mrow> <mn>4</mn> <mo>⋅</mo> <mn>2</mn> </mrow> </mfrac> <mfrac> <mn>3</mn> <mn>4</mn> </mfrac> </maction> </math> ...
<math> - MathML
examples html5 notation <!doctype html> <html> <head> <title>mathml in html5</title> </head> <body> <math> <mrow> <mrow> <msup> <mi>a</mi> <mn>2</mn> </msup> <mo>+</mo> <msup> <mi>b</mi> <mn>2</mn> </msup> </mrow> <mo>=</mo> <msup> <mi>c</mi> <mn>2</mn> </msup>...
<menclose> - MathML
verticalstrike a2 + b2 vertical strikeout line through contents horizontalstrike a2 + b2 horizontal strikeout line through contents madruwb a2 + b2 arabic factorial symbol updiagonalarrow a2 + b2 diagonal arrow phasorangle a2 + b2 phasor angle
examples <math> <menclose notation="circle box"> <mi> x </mi> <mo> + </mo> <mi> y </mi> </menclose> </math> specifications specification status comment mathml 3.0the definition of 'menclose' in that specification.
<merror> - MathML
examples <math> <merror> <mrow> <mtext> division by zero: </mtext> <mfrac> <mn> 1 </mn> <mn> 0 </mn> </mfrac> </mrow> </merror> </math> specifications specification status comment mathml 3.0the definition of 'merror' in that specification.
<mfenced> - MathML
examples the last separator is repeated (,) sample rendering: rendering in your browser: a b c d e <math> <mfenced open="{" close="}" separators=";;,"> <mi>a</mi> <mi>b</mi> <mi>c</mi> <mi>d</mi> <mi>e</mi> </mfenced> </math> all excess is ignored (,) sample rendering: rendering in your browser: a b c d e <math> <mfenced open="[" close="]" separators="||||,"> ...
<mfrac> - MathML
examples sample rendering: your browser rendering: a b c d <math> <mfrac bevelled="true"> <mfrac> <mi> a </mi> <mi> b </mi> </mfrac> <mfrac> <mi> c </mi> <mi> d </mi> </mfrac> </mfrac> </math> specifications specification status comment mathml 3.0the definition of 'mfrac' in that specification.
<mglyph> - MathML
examples <math> <mi><mglyph src="my-glyph.png" alt="my glyph"/></mi> </math> specifications specification status comment mathml 3.0the definition of 'mglyph' in that specification.
<mi> - MathML
aracter) ; example bold-italic ; example double-struck ; example bold-fraktur ; example script ; example bold-script ; example fraktur ; example sans-serif ; example bold-sans-serif ; example sans-serif-italic ; example sans-serif-bold-italic ; example monospace ; example initial ; مثال tailed ; مثال looped ; مثال stretched ; مثال
examples <math> <mi> y </mi> <mi> sin </mi> <mi mathvariant="monospace"> x </mi> <mi mathvariant="bold"> π </mi> </math> specifications specification status comment mathml 3.0the definition of 'mi' in that specification.
<mlabeledtr> - MathML
examples rendering: <math> <mtable> <mlabeledtr> <mtd><mn>1</mn></mtd> <!-- label --> <mtd><mi>a</mi></mtd> <mtd><mi>b</mi></mtd> </mlabeledtr> <mtr> <mtd><mi>c</mi></mtd> <mtd><mi>d</mi></mtd> <mtd><mi>e</mi></mtd> </mtr> </mtable> </math> specifications specification status comment mathml 3.0the definition of '...
<mn> - MathML
italic ; example bold-italic ; example double-struck ; example bold-fraktur ; example script ; example bold-script ; example fraktur ; example sans-serif ; example bold-sans-serif ; example sans-serif-italic ; example sans-serif-bold-italic ; example monospace ; example initial ; مثال tailed ; مثال looped ; مثال stretched ; مثال
examples <math> <mn> 0 </mn> <mn> 1.337 </mn> <mn> twelve </mn> <mn> xvi </mn> <mn> 2e10 </mn> </math> specifications specification status comment mathml 3.0the definition of 'mn' in that specification.
<mo> - MathML
examples <math> <mrow> <mn>5</mn> <mo>+</mo> <mn>5</mn> </mrow> <mrow> <mo> [ </mo> <!-- default form value: prefix --> <mrow> <mn> 0 </mn> <mo> ; </mo> <!-- default form value: infix --> <mn> 1 </mn> </mrow> <mo> ) </mo> <!-- default form value: postfix --> </mrow> </math> specifications specification status comment mathml 3.0the definition of ...
<mover> - MathML
examples sample rendering: rendering in your browser: x + y + z ⏞ <math> <mover accent="true"> <mrow> <mi> x </mi> <mo> + </mo> <mi> y </mi> <mo> + </mo> <mi> z </mi> </mrow> <mo> ⏞ <!--top curly bracket--> </mo> </mover> </math> specifications specification status comment mathml 3.0the definition of 'mover' in that ...
<mpadded> - MathML
examples <math> <mpadded height="+150px" width="100px" lspace="2height"> <mi> x </mi> <mo> + </mo> <mi> y </mi> </mpadded> </math> specifications specification status comment mathml 3.0the definition of 'mpadded' in that specification.
<mphantom> - MathML
examples sample rendering: rendering in your browser: x + y + z <math> <mrow> <mi> x </mi> <mo> + </mo> <mphantom> <mi> y </mi> <mo> + </mo> </mphantom> <mi> z </mi> </mrow> </math> specifications specification status comment mathml 3.0the definition of 'mphantom' in that specification.
<mroot> - MathML
examples sample rendering: rendering in your browser: x 3 <math> <mroot> <mi>x</mi> <mn>3</mn> </mroot> </math> specifications specification status comment mathml 3.0the definition of 'mroot' in that specification.
<mrow> - MathML
examples <math> <mrow> <mn> 1 </mn> <mo> + </mo> <mn> 1 </mn> </mrow> <mrow> <mo> ( </mo> <mrow> <mi> x </mi> <mo> , </mo> <mi> y </mi> </mrow> <mo> ) </mo> </mrow> </math> specifications specification status comment mathml 3.0the definition of 'mrow' in that specification.
<ms> - MathML
examples <math> <ms lquote="„" rquote="“"> abc </ms> </math> specifications specification status comment mathml 3.0the definition of 'ms' in that specification.
<mspace> - MathML
examples <math> <mspace depth="40px" height="20px" /> <mspace width="100px" /> </math> specifications specification status comment mathml 3.0the definition of 'mspace' in that specification.
<msqrt> - MathML
examples sample rendering: rendering in your browser: x <math> <msqrt> <mi>x</mi> </msqrt> </math> specifications specification status comment mathml 3.0the definition of 'msqrt' in that specification.
<mstyle> - MathML
examples using displaystyle and mathcolor to effect style changes in the layout of the whole sum.
<msub> - MathML
examples sample rendering: rendering in your browser: x 1 <math> <msub> <mi>x</mi> <mn>1</mn> </msub> </math> specifications specification status comment mathml 3.0the definition of 'msub' in that specification.
<msubsup> - MathML
examples sample rendering: rendering in your browser: ∫ 0 1 <math displaystyle="true"> <msubsup> <mo> ∫<!--integral --> </mo> <mn> 0 </mn> <mn> 1 </mn> </msubsup> </math> specifications specification status comment mathml 3.0the definition of 'msubsup' in that specification.
<msup> - MathML
examples sample rendering: rendering in your browser: x 2 <math> <msup> <mi>x</mi> <mn>2</mn> </msup> </math> specifications specification status comment mathml 3.0the definition of 'msup' in that specification.
<mtable> - MathML
examples alignment with row number rendering: <math> <mi>x</mi> <mo>=</mo> <mtable frame="solid" rowlines="solid" align="axis 3"> <mtr> <mtd><mi>a</mi></mtd> <mtd><mi>b</mi></mtd> </mtr> <mtr> <mtd><mi>c</mi></mtd> <mtd><mi>d</mi></mtd> </mtr> <mtr> <mtd><mi>e</mi></mtd> <...
<mtext> - MathML
ic ; example double-struck ; example bold-fraktur ; example script ; example bold-script ; example fraktur ; example sans-serif ; example bold-sans-serif ; example sans-serif-italic ; example sans-serif-bold-italic ; example monospace ; example normal (default) ; مثال initial ; مثال tailed ; مثال looped ; مثال stretched ; مثال
examples <math> <mtext> theorem of pythagoras </mtext> <mtext> /* comment here */ </mtext> </math> specifications specification status comment mathml 3.0the definition of 'mtext' in that specification.
<munder> - MathML
examples sample rendering: rendering in your browser: x + y + z ⏟ <math> <munder accentunder="true"> <mrow> <mi> x </mi> <mo> + </mo> <mi> y </mi> <mo> + </mo> <mi> z </mi> </mrow> <mo> ⏟ <!--bottom curly bracket--> </mo> </munder> </math> specifications specification status comment mathml 3.0the definition of 'munde...
<munderover> - MathML
examples sample rendering: rendering in your browser: ∫ 0 ∞ <math displaystyle="true"> <munderover > <mo> ∫ <!--integral--> </mo> <mn> 0 </mn> <mi> ∞ <!--infinity--> </mi> </munderover> </math> specifications specification status comment mathml 3.0the definition of 'munderover' in that specification.
MathML documentation index - MathML
3
examples beginner, example, guide, mathml, needsbeginnerupdate below you'll find some
examples you can look at to help you to understand how to use mathml to display increasingly complex mathematical concepts in web content.
Animation performance and frame rate - Web Performance
css property cost in the context of the rendering waterfall, some properties are more expensive than others: property type cost
examples properties that affect an element's geometry or position trigger a style recalculation, a layout and a repaint.
Using dns-prefetch - Web Performance
the cross-origin domain is then specified in the href attribute: syntax <link rel="dns-prefetch" href="https://fonts.gstatic.com/" >
examples <html> <head> <link rel="dns-prefetch" href="https://fonts.gstatic.com/"> <!-- and all other head elements --> </head> <body> <!-- your page content --> </body> </html> you should place dns-prefetch hints in the <head> element any time your site references resources on cross-origin domains, but there are some things to keep in mind.
How to make PWAs installable - Progressive web apps (PWAs)
{ "src": "icons/icon-512.png", "sizes": "512x512", "type": "image/png" } ], "start_url": "/pwa-
examples/js13kpwa/index.html", "display": "fullscreen", "theme_color": "#b12a34", "background_color": "#b12a34" } most of the fields are self-explanatory, but to be certain we're on the same page: name: the full name of your web app.
begin - SVG: Scalable Vector Graphics
examples offset example <svg width="120" height="120" viewbox="0 0 120 120" xmlns="http://www.w3.org/2000/svg" version="1.1"> <!-- animated rectangles --> <rect x="10" y="35" height="15" width="0"> <animate attributetype="xml" attributename="width" to="100" begin="0s" dur="8s" fill="freeze" /> </rect> <rect x="35" y="60" height="15" width...
end - SVG: Scalable Vector Graphics
examples offset example <svg width="120" height="120" viewbox="0 0 120 120" xmlns="http://www.w3.org/2000/svg" version="1.1"> <!-- animated rectangles --> <rect x="10" y="35" height="15" width="0"> <animate attributetype="xml" attributename="width" to="100" begin="0s" end="8s" fill="freeze" /> </rect> <rect x="10" y="60" height="15" width...
rotate - SVG: Scalable Vector Graphics
examples svg <svg width="400" height="120" viewbox="0 0 480 120" xmlns="http://www.w3.org/2000/svg"> <!-- draw the outline of the motion path in grey --> <path d="m10,110 a120,120 -45 0,1 110 10 a120,120 -45 0,1 10,110" stroke="lightgrey" stroke-width="2" fill="none" id="themotionpath"/> <!-- red arrow which will not rotate --> <path fill="red" d="m-5,-5 l10,0 -5,5 0,0 z"> ...
Content type - SVG: Scalable Vector Graphics
the following are
examples of legal clock values: full clock values: 02:30:03 = 2 hours, 30 minutes and 3 seconds 50:00:10.25 = 50 hours, 10 seconds and 250 milliseconds partial clock value: 02:33 = 2 minutes and 33 seconds 00:10.5 = 10.5 seconds = 10 seconds and 500 milliseconds timecount values: 3.2h = 3.2 hours = 3 hours and 12 minutes 45min = 45 minutes 30s = 30 seconds 5ms = 5 millisecon...
<feMorphology> - SVG: Scalable Vector Graphics
examples filtering svg content svg <svg xmlns="http://www.w3.org/2000/svg" width="300" height="180"> <filter id="erode"> <femorphology operator="erode" radius="1"/> </filter> <filter id="dilate"> <femorphology operator="dilate" radius="2"/> </filter> <text y="1em">normal text</text> <text id="thin" y="2em">thinned text</text> <text id="thick" y="3em">fattened text</text> </svg> ...
Patterns - SVG: Scalable Vector Graphics
all three of the preceding
examples are shown below on a rectangle that has been slightly elongated to a height of 300px, but i should note that it's not an exhaustive picture, and there are other options available depending on your application.
Subresource Integrity - Web security
therefore, the resource must be served with an access-control-allow-origin header that allows the resource to be shared with the requesting origin; for example: access-control-allow-origin: *
examples in the following
examples, assume that oqvuafxrkap7fdgccy5uykm6+r9gqq8k/uxy9rx7hnqlgyl1kpzqho1wx4jwy8wc is already known to be the expected sha-384 hash (digest) of a particular script example-framework.js, and there’s a copy of the script hosted at https://example.com/example-framework.js.
Tutorials
also includes a step-by-step guide to creating a basic web page with code
examples.
Web Components
examples we are building up a number of
examples in our web-components-
examples github repo.
XML introduction - XML: Extensible Markup Language
<?xml-stylesheet type="text/xsl" href="transform.xsl"?> recommendations this article is obviously only a very brief introduction to what xml is, with a few small
examples and references to get you started.
substring-after - XPath
examples xpath example output substring-after('aa-bb','-') bb substring-after('aa-bb','a') a-bb substring-after('aa-bb','b') b substring-after('aa-bb','q') (empty string) defined xpath 1.0 4.2 gecko support supported.
substring-before - XPath
examples xpath example output substring-before('aa-bb','-') aa substring-before('aa-bb','a') (empty string) substring-before('aa-bb','b') aa- substring-before('aa-bb','q') (empty string) defined xpath 1.0 4.2 gecko support supported.
Introduction to using XPath in JavaScript - XPath
none yet =====any_type example===== <pre> </pre>
examples within an html document the following code is intended to be placed in any javascript fragment within or linked to the html document against which the xpath expression is to be evaluated.
Transforming XML with XSLT - XSLT: Extensible Stylesheet Language Transformations
h() (supported) string() (supported) string-length() (supported) substring() (supported) substring-after() (supported) substring-before() (supported) sum() (supported) system-property() (supported) translate() (supported) true() (supported) unparsed-entity-url() (not supported) for further reading books online the world wide web consortium portals articles tutorials/
examples mailing lists/newsgroups resources index original document information copyright information: copyright © 2001-2003 netscape.
WebAssembly
examples wasmsobel see our webassembly-
examples repo for a number of other
examples.