Search completed in 1.21 seconds.
9200 results for "example":
Your results are loading. Please wait...
Examples and demos from articles - Archive of obsolete content
what follows is a brief list of examples and demos from our theoretical articles.
...[article] typewriter effect [html] the following example will delete and re-type simulating a typewriter all the text content of the nodelist which match a specified group of selectors.
... here is a possible and minimalist example of such abstraction, which for this reason we named minidaemon.
...And 17 more matches
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 17 more matches
Movement, orientation, and motion: A WebXR example - Web APIs
in this article, we'll make use of information introduced in the previous articles in our webxr tutorial series to construct an example which animates a rotating cube around which the user can move freely using a vr headset, keyboard, and/or mouse.
... screenshot of this example in action the core of this example—the spinning, textured, lighted cube—is taken from our webgl tutorial series; namely, the penultimate article in the series, covering lighting in webgl.
... this example demonstrates this by showing the canvas on the screen, even when presenting a scene as an immersive display using an xr device.
...And 15 more matches
Examples of web and XML development using the DOM - Web APIs
this chapter provides some longer examples of web and xml development using the dom.
... wherever possible, the examples use common apis, tricks, and patterns in javascript for manipulating the document object.
... example 1: height and width the following example shows the use of the height and width properties alongside images of varying dimensions: <!doctype html> <html lang="en"> <head> <title>width/height example</title> <script> function init() { var arrimages = new array(3); arrimages[0] = document.getelementbyid("image1"); arrimages[1] = document.getelementbyid("image2"); arrimages[2] = document.getelementbyid("image3"); var objoutput = document.getelementbyid("output"); var strhtml = "<ul>"; for (var i = 0; i < arrimages.length; i++) { strhtml += "<li>image" + (i+1) + ": height=" + arrimages[i].height + ", width=" + arrimages[i].width + ", style.height=" + arrimages[i].style.height + ", style.width=" + arrimages[i].style.width...
...And 11 more matches
Practical positioning examples - Learn web development
this article shows how to build some real world examples to illustrate what kinds of things you can do with positioning.
... prerequisites: html basics (study introduction to html), and an idea of how css works (study introduction to css.) objective: to get an idea of the practicalities of positioning a tabbed info-box the first example we'll look at is a classic tabbed info box — a very common feature used when you want to pack a lot of information into a small area.
...our simple example will look like this once we are finished: note: you can see the finished example running live at info-box.html (source code).
...And 10 more matches
Learn XPI Installer Scripting by Example - Archive of obsolete content
note also that when you call methods on the install--as you do so often in installation scripts (getfolder, initinstall, addfile, and performinstall are all examples of common install object methods)--the install object is implicit; like the window object in regular web page scripts, the install object does not need to be prefixed to the method.
...in the example above, "netscape seamonkey" is the display name, "browser" is the registry name, and the version is "6.0.0.2000110807." see initinstall in the xpinstall api reference for more information on the initialization process.
...in the example above, all of the contents of the "bin" directory in the archive are queued for installation, and the target of that installation (when the installation is actually begun with a call to performinstall at the end), is the communicatorfolder directory defined at line 22 as "program." "program" is one of a short list of keywords that can be used in place of full path names in methods such as addfil...
...And 8 more matches
XPCOM Examples - Archive of obsolete content
« previousnext » this section provides some examples of using xpcom along with some additional interfaces.
... window management this example contains rdf datasource that will be seen in the later section.
... you might skip this example for the time being, except when you have already had that knowledge.
...And 7 more matches
Examples
let lastpromise = newpromise.then(function onfulfill(){ }) .catch(function onreject(arejectreason) { console.warn('newpromise failed with reason: ', arejectreason); }); using a promise returned by a function (verbose) this example uses a verbose syntax, showing all the involved promises.
... if the file existence check fails, for example because access is denied, promise is rejected with an os.file.error instance.
... using a promise returned by a function (compact) the same code as the previous example is usually written with a more compact syntax: components.utils.import("resource://gre/modules/osfile.jsm") let path = os.path.join(os.constants.path.tmpdir, "file.txt"); os.file.exists(path).then(exists => { console.log(exists ?
...And 7 more matches
WebGL by example - Web APIs
next » webgl by example is a series of live samples with short explanations that showcase webgl concepts and capabilities.
... 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.
...And 7 more matches
Multiple Rule Example - Archive of obsolete content
for instance, in an earlier example, one of the photos had a description and the other photos did not.
...the next example shows how we can do this.
...ntainer="?start" child="?photo"/> <triple subject="?photo" predicate="http://purl.org/dc/elements/1.1/title" object="?phototitle"/> </conditions> <action> <vbox uri="?photo" class="box-padded"> <label value="?phototitle"/> <image src="?photo"/> </vbox> </action> </rule> </template> </vbox> in this example, the first rule matches only those photos with title, description, and date properties.
...And 6 more matches
XSLT Basic Example - Web APIs
basic example this first example demonstrates the basics of setting up an xslt transformation in a browser.
... the example will take an xml document that contains information (title, list of authors and body text) about an article and present it in an human readable form.
... figure 1 shows the source of the basic xslt example.
...And 5 more matches
Simple Example - Archive of obsolete content
« previousnext » let's look a more useful example, this time for a template that will show a list of photos.
... <rdf:description rdf:about="http://www.xulplanet.com/ndeakin/images/t/palace.jpg" dc:title="palace from above"/> <rdf:description rdf:about="http://www.xulplanet.com/ndeakin/images/t/canal.jpg" dc:title="canal"/> <rdf:description rdf:about="http://www.xulplanet.com/ndeakin/images/t/obelisk.jpg" dc:title="obelisk"/> </rdf:rdf> in this example, we have three images, which can be identified by urls.
...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.
...And 4 more matches
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.
...the best example of a binary implementation of an address book is the os x address book source code.
...And 4 more matches
Examples
these examples demonstrate how to use js-ctypes.
... general using c struct and pointers an example on how to use basic c data types with js-ctypes.
... standard os libraries some examples on how to get cursor position on each os.
...And 4 more matches
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.
...the enum.js script is a good example of using a javaadapter to implement a java interface using a javascript object.
...And 3 more matches
Advanced Example - XSLT: Extensible Stylesheet Language Transformations
advanced example this advanced example sorts several divs based on their content.
... the example allows sorting the content multiple times, alternating between ascending and descending order.
... once the transformation is complete, the result is appended to the document, as shown in this example.
...And 3 more matches
Basic Example - XSLT: Extensible Stylesheet Language Transformations
basic example the basic example will load an xml file and apply a xsl transformation on it.
... these are the same files used in the generating html example in the xslt in netscape gecko article.
...ny"> :: <b> <xsl:value-of select="@company" /> </b> </xsl:if> <br /> </xsl:template> <xsl:template match="myns:body"> <xsl:copy> <xsl:apply-templates select="@*|node()"/> </xsl:copy> </xsl:template> <xsl:template match="@*|node()"> <xsl:copy> <xsl:apply-templates select="@*|node()"/> </xsl:copy> </xsl:template> </xsl:stylesheet> the example loads using synchronous xmlhttprequest both the .xsl (xslstylesheet) and the .xml (xmldoc) files into memory.
...And 2 more matches
XBL Example - Archive of obsolete content
« previousnext » this section will describe an example xbl element.
... a slideshow element let's construct a full example of an xbl element.
... example 1 : source <binding id="slideshow"> <content> <xul:vbox flex="1"> <xul:deck xbl:inherits="selectedindex" selectedindex="0" flex="1"> <children/> </xul:deck> <xul:hbox> <xul:button xbl:inherits="label=previoustext"/> <xul:label flex="1"/> <xul:button xbl:inherits="label=nexttext"/> </xul:hbox> </xul:vbox> </content> </binding> ...
... the final code the final code is as follows: example 2 : source <binding id="slideshow"> <content> <xul:vbox flex="1"> <xul:deck xbl:inherits="selectedindex" selectedindex="0" flex="1"> <children/> </xul:deck> <xul:hbox> <xul:button xbl:inherits="label=previoustext" oncommand="parentnode.parentnode.parentnode.page--;"/> <xul:description flex="1"/> <xul:button xbl:inherits=...
Example and tutorial: Simple synth keyboard - Web APIs
this example makes use of the following web api interfaces: audiocontext, oscillatornode, periodicwave, and gainnode.
... because oscillatornode is based on audioscheduledsourcenode, this is to some extent an example for that as well.
... the values in the example table above have been rounded to two decimal places.
...we skip these, because we're leaving out the sharp notes in this example.
Stacking context example 1 - CSS: Cascading Style Sheets
« css « understanding css z-index stacking context example 1 let's start with a basic example.
... in this last example you can see that div #2 and div #4 are not siblings, because they belong to different parents in the html elements' hierarchy.
...and this example shows what happens when a parent element does not create a stacking context.
... example html <div id="div1"> <br /><span class="bold">div #1</span> <br />position: relative; <div id="div2"> <br /><span class="bold">div #2</span> <br />position: absolute; <br />z-index: 1; </div> </div> <br /> <div id="div3"> <br /><span class="bold">div #3</span> <br />position: relative; <div id="div4"> <br /><span class="bold">div #4</span> <br />position: absolute; <br />z-index: 2; </div> </div> </body></html> css .bold { font-weight: bold; font: 12px arial; } #div1, #div3 { height: 80px; position: relative; border: 1px dashed #669966; background-color: #ccffcc; padding-left: 5px; } #div2 { opacity: 0.8; z-index: 1; position: absolute; width: 150px; height: 200px; top: 20px; left: 170px; b...
Reddit Example - Archive of obsolete content
this example uses the action button api, which is only available from firefox 29 onwards.
... this example add-on creates a panel containing the mobile version of reddit.
... to run this example you'll also have to have an icon file named "icon-16.png" saved in your add-on's "data" directory.
XForms Custom Controls Examples - Archive of obsolete content
custom control examples.
... please feel free to add your own examples.
... a full example showing a complete form can be found on xforms:custom_controls.
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.
... this requires two chained asynchronous calls: //first take an email address and turn it into an identity object id_q = gloda.newquery(gloda.noun_identity); id_q.kind("email"); id_q.value("test@example.com"); id_coll = id_q.getcollection({ onitemsadded: function _onitemsadded(aitems, acollection) { }, onitemsmodified: function _onitemsmodified(aitems, acollection) { }, onitemsremoved: function _onitemsremoved(aitems, acollection) { }, onquerycompleted: function _onquerycompleted(id_co...
Ajax navigation example - Web APIs
this is an example of an ajax website composed only of three pages (first_page.php, second_page.php and third_page.php).
... to see how it works, please create the following files (or git clone https://github.com/giabao/mdn-ajax-nav-example.git ): note: for fully integrating the <form> elements within this mechanism, please take a look at the paragraph submitting forms and uploading files.
...it is shared between all ajax pages.</p> include/before_content.php: <p> [ <a class="ajax-nav" href="first_page.php">first example</a> | <a class="ajax-nav" href="second_page.php">second example</a> | <a class="ajax-nav" href="third_page.php">third example</a> | <a class="ajax-nav" href="unexisting.php">unexisting page</a> ] </p> include/header.php: <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <script type="text/javascript" src="js/ajax_nav.js"></script> <link rel="stylesheet" href="css/style.css...
Stacking context example 2 - CSS: Cascading Style Sheets
« css « understanding css z-index stacking context example 2 this is a very simple example, but it is the key for understanding the concept of stacking context.
... there are the same four divs of the previous example, but now z-index properties are assigned on both levels of the hierarchy.
... example source code <!doctype html public "-//w3c//dtd xhtml 1.0 transitional//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd"> <html> <head><style type="text/css"> div { font: 12px arial; } span.bold { font-weight: bold; } #div2 { z-index: 2; } #div3 { z-index: 1; } #div4 { z-index: 10; } #div1,#div3 { height: 80px; position: relative; border: 1px dashed #669966; backgroun...
Stacking context example 3 - CSS: Cascading Style Sheets
« css « understanding css z-index stacking context example 3 this last example shows problems that arise when mixing several positioned elements in a multi-level html hierarchy and when z-indexes are assigned using class selectors.
... let's take as an example a three-level hierarchical menu made from several positioned divs.
... example source code <!doctype html public "-//w3c//dtd xhtml 1.0 transitional//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd"> <html> <head><style type="text/css"> div { font: 12px arial; } span.bold { font-weight: bold; } div.lev1 { width: 250px; height: 70px; position: relative; border: 2px outset #669966; background-color: #ccffcc; padding-left: 5px; } #container1...
Example - SVG: Scalable Vector Graphics
in this example, we use xhtml, svg, javascript, and the dom to animate a swarm of "motes".
...this example should work in firefox 1.5 and above.
... view the example <?xml version='1.0'?> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:svg="http://www.w3.org/2000/svg"> <head> <title>a swarm of motes</title> <style type='text/css'> <![cdata[ label, input { width: 150px; display: block; float: left; margin-bottom: 10px; } label { text-align: right; width: 75px; padding-right: 20px; } br { clear: left; } ]]> </style> </head> <body onload='update()'> <svg:svg id='display' width='400' height='300'> <svg:circle id='cursor' cx='200' cy='150' r='7' fill='#0000ff' fill-opacity='0.5'/> </svg:svg> <p>a swarm of motes, governed by two simple principles.
Drag and Drop Example - Archive of obsolete content
an example of implementing drag and drop will be implemented in this section.
...this example is fairly simple.
Example Sticky Notes - Archive of obsolete content
view this example <!doctype html public "-//w3c//dtd html 4.01//en" "http://www.w3.org/tr/html401/strict.dtd"> <html> <head> <title>xbl demo : sticky notes</title> <meta http-equiv="content-type" content="text/html; charset=iso-8859-1"> <style type="text/css"> body { background-color: #ffffff; color: #000000; font: 1em verdana, sans-serif; } h1 { font-size: 1.5em; } /* binding: */ .sticker { -moz-binding: url(notes.xml#default); } </style> </head> <body> <h1><a href="http://developer.mozilla.org/en/docs/xbl:xbl_1.0_reference">xbl</a> demo : sticky notes</h1> <div class="sticker"><p>acme,&nbsp;inc.
...his.$bg; ]]></handler> </handlers> </binding> </bindings> notes.css .sticker { position: relative; left: 0px; right: 0px; float: left; clear: none; width: 10em; height: 10em; overflow: visible; margin: 1em 1em; padding: 0.5em 0.5em; border: 2px solid blue; background-color: yellow; font: 1em normal "times new roman",serif; font-style: italic; cursor: default; } view this example ...
Examples - Archive of obsolete content
examples trigger scripts and install scripts describes typical kinds of script that use the xpinstall api.
... the following samples demonstrate some of the principal installation functions in the xpinstall api: file.macalias file.windowsshortcut [install.]adddirectory [install.]addfile installtrigger.installchrome installtrigger.startsoftwareupdate windows install example ...
Activity Manager examples
(this example seems to be outdated and not working, see bug 557467 comment 1.) //optional: define some convenience constants const nsactprocess = components.constructor("@mozilla.org/activity-process;1", "nsiactivityprocess", "init"); const nsactevent = components.constructor("@mozilla.org/activity-event;1", "nsiactivityevent"...
...} sendercontextdisplayhelper.prototype = { getcontextdisplaytext: function(contexttype, contextobj) { // in this particular example we know that contexttype is "sender" // since we also pass the contexttype along with the contextobject // in some cases, one helper can be registered for a group of context types // we know that the context object is the author of the message // localization is omitted return "messages coming from " + contextobj.surname + ", " + contextobj.firstname; } } // step 2: register the helper for this context type gactivitymanager.registercontextdisplayhelpe...
Compositing example - Web APIs
the output looks like this: compositing example this code sets up the global values used by the rest of the program.
...uma and hue of the bottom layer, while adopting the chroma of the top layer.', 'preserves the luma of the bottom layer, while adopting the hue and chroma of the top layer.', 'preserves the hue and chroma of the bottom layer, while adopting the luma of the top layer.' ].reverse(); var width = 320; var height = 340; main program when the page loads, this code runs to set up and run the example: window.onload = function() { // lum in srgb var lum = { r: 0.33, g: 0.33, b: 0.33 }; // resize canvas canvas1.width = width; canvas1.height = height; canvas2.width = width; canvas2.height = height; lightmix() colorsphere(); runcomposite(); return; }; and this code, runcomposite(), handles the bulk of the work, relying on ...
A basic 2D WebGL animation example - Web APIs
in this webgl example, we create a canvas and within it render a rotating square using webgl.
... result this is a pretty simple example, since it's just drawing one simple object, but the concepts used here extend to much more complex animations.
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.
... pythagorean theorem small example showing a proof of the pythagorean theorem.
Examples - Game development
threejs app player a player into which you can load and run three.js examples.
Example 1 - Learn web development
this is the first example of code that explains how to build a custom form widget.
Example 2 - Learn web development
this is the second example that explain how to build custom form widgets.
Example 3 - Learn web development
this is the third example that explain how to build custom form widgets.
Example 4 - Learn web development
this is the fourth example that explain how to build custom form widgets.
Example 5 - Learn web development
this is the last example that explain how to build custom form widgets.
Example - Learn web development
this the example for a basic payment form for the article how to structure an html form.
Example - Learn web development
this is the example code for the article your first html form.
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.
Animation inspector example: CSS transitions - Firefox Developer Tools
firefox-logo-animation example animation using css transitions.
Animation inspector example: Web Animations API - Firefox Developer Tools
firefox-logo-animation example animation using the web animations api.
Index - Web APIs
WebAPIIndex
45 aeskeygenparams api, aeskeygenparams, dictionary, reference, web crypto api see the examples for subtlecrypto.generatekey().
...it allows them to react to such a change, for example by changing the color contrast of the user interface (ui) or by changing the exposure necessary to take a picture.
...this stream can be used in a similar way as a mediastream obtained via navigator.getusermedia — it can, for example, be sent to a remote peer using the rtcpeerconnection addstream() method.
...And 474 more matches
Index - Archive of obsolete content
perhaps your target audience is people that are using older hardware, for example, and can't upgrade to the latest and greatest browsers.
...see displaying notifications for an example.
... 20 reddit example advanced, codingscripting, javascript, mobile no summary!
...And 117 more matches
Index
some cryptography uses the same secret key for both encrypting and decrypting, for example password based encryption (pbe).
...a certificate contains lots of other details; for example, it contains a signature by a third party that expresses trust in the ownership relationship for the certificate.
...examples for the database files are key3.db and cert8.db, where the numbers are file version numbers.
...And 94 more matches
SVG documentation index - SVG: Scalable Vector Graphics
WebSVGIndex
7 example svg, xml in this example, we use xhtml, svg, javascript, and the dom to animate a swarm of "motes".
... 11 svg 1.1 support in firefox firefox, svg you can find some basic examples of svg syntax and usage in the w3c svg test suite.
... 14 svg conditional processing attributes intermediate, needsexample, property, reference, svg the svg conditional processing attributes are all the attributes that can be specified on some svg elements to control whether or not the element on which it appears should be rendered.
...And 69 more matches
Index - MDN Web Docs Glossary: Definitions of Web-related terms
it is usually measured in multiples of bits-per-second (bps), for example megabits-per-second (mbps) or gigabits-per-second (gbps).
...in other programming languages different numeric types can exist, for examples: integers, floats, doubles, or bignums.
...for example, <p> is by default a block-level element, whereas <a> is an inline element — you can put several links next to one another in your html source and they will sit on the same line as one another in the rendered output.
...And 48 more matches
WebIDL bindings
for example, nsinode::getparentobject returns the node's owner document.
...see audiocontext::wrapobject, for example.
...you can see an example of what the function declarations should look like by running mach webidl-example myinterface.
...And 47 more matches
Index - Learn web development
accessibility, beginner, design, example, intro, mobile, needsactivelearning when you're building a website, one top issue to consider is universal design: accommodating all users regardless of disability, technical constraints, culture, location, and so on.
... 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...
... beginner, ftp, github, uploading, webmechanics, hosting, rsync, sftp if you have built a simple web page (see html basics for an example), you will probably want to put it online, on a web server.
...And 46 more matches
Index
MozillaTechXPCOMIndex
if the component uses only "frozen" xpcom interfaces, there is a good chance the same binary component will work with different versions of gecko (version 1.8 and 1.9, for example).
...this can create a difficult situation for extension developers trying to support multiple gecko versions (firefox 2 and 3, for example).
...here is the interface, and a description of its use.</t> 10 how to pass an xpcom object to a new window needsexample, needshelp if you want to be able to call functions within an xpcom object from a xul window's code, you can do so if you pass the xpcom object as one of the arguments to the window creation method.
...And 46 more matches
Regular expression syntax cheatsheet - JavaScript
for example, /.y/ matches "my" and "ay", but not "yes", in "yes make my day".
...for example, /\d/ or /[0-9]/ matches "2" in "b2 is the suite number".
...for example, /\d/ or /[^0-9]/ matches "b" in "b2 is the suite number".
...And 34 more matches
Handling common HTML and CSS problems - Learn web development
for example, you might use a css framework and find that one of the class names it uses clashes with one you've already used for a different purpose.
... or you might find that html generated by some kind of third party api (generating ad banners, for example) includes a class name or id that you are already using for a different purpose.
...for example .audio-player ul a.
...And 33 more matches
CSS values and units - Learn web development
in the following example we have set the color of our heading using a keyword, and the background using the rgb() function: h1 { color: black; background-color: rgb(197,93,161); } a value in css is a way to define a collection of allowable sub-values.
...for example, if you look at the page for <color> you will see that the browser compatibility section lists different types of color value and support for them.
... 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.
...And 32 more matches
Grammar and types - JavaScript
for example, the word früh (which means "early" in german) could be used as a variable name.
... some examples of legal names are number_hits, temp99, $credit, and _name.
...for example, var x = 42.
...And 32 more matches
WAI-ARIA basics - Learn web development
for example, html5 introduced a number of semantic elements to define common page features (<nav>, <footer>, etc.) before these were available, developers would simply use <div>s with ids or classes, e.g.
... the initial solution was to add one or more hidden links at the top of the page to link to the navigation (or whatever else), for example: <a href="#hidden" class="hidden">skip to navigation</a> but this is still not very precise, and can only be used when the screenreader is reading from the top of the page.
... as another example, apps started to feature complex controls like date pickers for choosing dates, sliders for choosing values, etc.
...And 31 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.
... reference to link example note regarding dojo/dijit test files the main purpose of dojo's dijit test files are for dojo developers to exercise and debug the code.
...And 31 more matches
JavaScript modules - JavaScript
fast forward a few years and we now have complete applications being run in browsers with a lot of javascript, as well as javascript being used in other contexts (node.js, for example).
...node.js has had this ability for a long time, and there are a number of javascript libraries and frameworks that enable module usage (for example, other commonjs and amd-based module systems like requirejs, and more recently webpack and babel).
... introducing an example to demonstrate usage of modules, we've created a simple set of examples that you can find on github.
...And 31 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.
... let's look at a simple mapquest api example, and use it to illustrate how third-party apis differ from browser apis.
... 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.
...And 29 more matches
Handling common accessibility problems - Learn web development
when we say accessibility in the context of web technology, most people immediately think of making sure websites/apps are usable by people with disabilities, for example: visually impaired people using screen readers or magnification/zoom to access text people with motor function impairments using the keyboard (or other non-mouse features) to activate website functionality.
...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.
...And 29 more matches
Handling common JavaScript problems - Learn web development
when developers make use of new/nascent javascript features (for example ecmascript 6 / ecmascript next features, modern web apis...) in their code, and find that such features don't work in older browsers.
...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.
... incorrectly using functions inside loops — for example, in bad-for-loop.html (see source code), we loop through 10 iterations, each time creating a paragraph and adding an onclick event handler to it.
...And 29 more matches
Getting started with HTML - Learn web development
for example, consider the following line of text: my cat is very grumpy if we wanted the text to stand by itself, we could specify that it is a paragraph by enclosing it in a paragraph (<p>) element: <p>my cat is very grumpy</p> note: tags in html are case-insensitive.
...for example, a <title> tag could be written as <title>, <title>, <title>, <title>, etc., and it will work.
... anatomy of an html element let's further explore our paragraph element from the previous section: the anatomy of our element is: the opening tag: this consists of the name of the element (in this example, p for paragraph), wrapped in opening and closing angle brackets.
...And 28 more matches
Introduction to events - Learn web development
for example, if the user selects a button on a webpage, you might want to respond to that action by displaying an information box.
...for example, in an airport, when the runway is clear for take off, a signal is communicated to the pilot.
...for example: the user selects a certain element or hovers the cursor over a certain element.
...And 28 more matches
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.
...for example, a control button to play a video on your site could be marked up like this: <div>play video</div> but as you'll see in greater detail later on, it makes sense to use the correct element for the job: <button>play video</button> not only do html <button>s have some suitable styling applied by default (which you will probably want to override), they also have built-in keyboard accessibility — u...
... 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.
...And 27 more matches
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.
...for example, a control button to play a video on your site could be marked up like this: <div>play video</div> but as you'll see in greater detail later on, it makes sense to use the correct element for the job: <button>play video</button> not only do html <button>s have some suitable styling applied by default (which you will probably want to override), they also have built-in keyboard accessibility — u...
... 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.
...And 27 more matches
Introduction to CSS layout - Learn web development
let's look at a quick html example: <p>i love my cat.</p> <ul> <li>buy cat food</li> <li>exercise</li> <li>cheer up friend</li> </ul> <p>the end!</p> by default, the browser will display this code as follows: note here how the html is displayed in the exact order in which it appears in the source code, with elements stacked up on top of one another — the first paragraph, followed by the unordered list, followed by t...
... the methods that can change how elements are laid out in css are as follows: the display property — standard values such as block, inline or inline-block can change how elements behave in normal flow, for example making a block-level element behave like an inline element (see types of css boxes for more information).
... we also have entire layout methods that are switched on via specific display values, for example css grid and flexbox, which alter how elements inside the element they are set on are laid out.
...And 27 more matches
Client-side storage - Learn web development
for example, you could download a batch of music files (perhaps used by a web game or music player application), store them inside a client-side database, and play them as needed.
... use of cache and service workers is an advanced topic, and we won't be covering it in great detail in this article, although we will show a simple example in the offline asset storage section below.
... a more involved example let's apply this new-found knowledge by writing a simple working example to give you an idea of how web storage can be used.
...And 27 more matches
Index - Archive of obsolete content
ArchiveMozillaXULIndex
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.
...a floating panel can be created using the panel element with at least two additional attributes as in the following example: 601 menubuttons xul, xul popup guide menus may be attached to buttons in several ways.
... 892 sorting and filtering a custom tree view this is example code for sorting and filtering a custom tree view, that is, a tree whose values are loaded via javascript.
...And 26 more matches
Introduction to Public-Key Cryptography - Archive of obsolete content
for example, the digital signature on an email message, combined with the certificate that identifies the sender, provide strong evidence that the person identified by that certificate did indeed send that message.
...for example, a server might require a user to type a name and password before granting access to the server.
...the client asks for the password to this database the first time the client needs to access it during a given session-for example, the first time the user attempts to access an ssl-enabled server that requires certificate-based client authentication.
...And 26 more matches
Localization content best practices
for example, suppose this string needs to be changed from "event" to "add new event": new-event-header = event add-new-event-header is definitely a better choice for the new string than new-event-header1.
... don't forget to add a localization note when: part of the string is not supposed to be localized (for example, the name of an html attribute in a warning).
...for example: bookmark.
...And 26 more matches
Expressions and operators - JavaScript
a binary operator requires two operands, one before the operator and one after the operator: operand1 operator operand2 for example, 3+4 or x*y.
... a unary operator requires a single operand, either before or after the operator: operator operand or operand operator for example, x++ or ++x.
...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).
...And 26 more matches
Chapter 3: Introduction to XUL—How to build a more intuitive UI - Archive of obsolete content
for each element that i explain in this chapter, i will illustrate it with a source code example.
... 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 !.
...And 25 more matches
Making decisions in your code — conditionals - Learn web development
for example, in a game, if the player's number of lives is 0, then it's game over.
... human beings (and other animals) make decisions all the time that affect their lives, from small ("should i eat one cookie or two?") to large ("should i stay in my home country and work on my father's farm, or should i move to america and study astrophysics?") conditional statements allow us to represent such decision making in javascript, from the choice that must be made (for example, "one cookie or two"), to the resulting outcome of those choices (perhaps the outcome of "ate one cookie" might be "still felt hungry", and the outcome of "ate two cookies" might be "felt full, but mom scolded me for eating all the cookies".) if...else statements let's look at by far the most common type of conditional statement you'll use in javascript — the humble if...else statement.
... a real example to understand this syntax better, let's consider a real example.
...And 25 more matches
Drawing graphics - Learn web development
the below example shows a simple 2d canvas-based bouncing balls animation that we originally met in our introducing javascript objects module: around 2006–2007, mozilla started work on an experimental 3d canvas implementation.
...webgl allows you to create real 3d graphics inside your web browser; the below example shows a simple rotating webgl cube: this article will focus mainly on 2d canvas, as raw webgl code is very complex.
...in a real example you'd want to relate the fallback content to the canvas content.
...And 25 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.
...(in the first example above, netscape will ask user confirmation about making direct connections; in this case, there is no user intervention.) proxy w3proxy.netscape.com:8080; socks socks:1080 use socks if the primary proxy goes down.
... the examples at the end of this document are complete.
...And 25 more matches
How CSS is structured - Learn web development
you reference an external css stylesheet from an html <link> element: <!doctype html> <html> <head> <meta charset="utf-8"> <title>my css experiment</title> <link rel="stylesheet" href="styles.css"> </head> <body> <h1>hello world!</h1> <p>this is my first css example</p> </body> </html> the css stylesheet file might look like this: h1 { color: blue; background-color: yellow; border: 1px solid black; } p { color: red; } the href attribute of the <link> element needs to reference a file on your file system.
... in the example above, the css file is in the same folder as the html document, but you could place it somewhere else and adjust the path.
... 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" href="../styles/style.css"> internal stylesheet an internal stylesheet resides within an html document.
...And 24 more matches
Graceful asynchronous programming with Promises - Learn web development
code similar to this, but much more complete, is used in that example.
... explaining basic promise syntax: a real example promises are important to understand because most modern web apis use them for functions that perform potentially lengthy tasks.
...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.
...And 24 more matches
NSS tools : certutil
some smart cards (for example, the litronic card) do not let you remove a public key you have generated.
...some smart cards (for example, the litronic card) can store only one key pair.
... · oid (example): 1.2.3.4 · critical-flag: critical or not-critical · filename: full path to a file containing an encoded extension -f password-file specify a file that will automatically supply the password to include in a certificate or to access a certificate database.
...And 24 more matches
Cross-Origin Resource Sharing (CORS) - HTTP
WebHTTPCORS
an example of a cross-origin request: the front-end javascript code served from https://domain-a.com uses xmlhttprequest to make a request for https://domain-b.com/data.json.
...for example, xmlhttprequest and the fetch api follow the same-origin policy.
... examples of access control scenarios we present three scenarios that demonstrate how cross-origin resource sharing works.
...And 24 more matches
Browser Detection and Cross Browser Support - Archive of obsolete content
an example of this approach involved testing for the existence of the document.images object.
... the classic example of this vendor/version client side detection strategy can be found in the ultimate browser sniffer.
...consider the following example: // wrong approach - do not use!
...And 23 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.
... simple start file let's start with a simple example: an input that allows you to choose whether you prefer a banana or a cherry.
...And 23 more matches
Cooperative asynchronous JavaScript: Timeouts and intervals - Learn web development
in the following example, the browser will wait two seconds before executing the anonymous function, then will display the alert message (see it running live, and see the source code): let mygreeting = settimeout(function() { alert('hello, mr.
...universe!'); } let mygreeting = settimeout(sayhi, 2000); that can be useful if you have a function that needs to be called both from a timeout and in response to an event, for example.
... for example, you could refactor the previous function so that it will say hi to whatever person's name is passed to it: function sayhi(who) { alert(`hello ${who}!`); } now, you can pass the name of the person into the settimeout() call as a third parameter: let mygreeting = settimeout(sayhi, 2000, 'mr.
...And 23 more matches
Mozilla DOM Hacking Guide
a function for example can be represented by a jsfunction, a jsobject, a jsval, ...
...for example, when we ask for |document.getelementbyid("myid");|, xpconnect will find that |document| is a property of the window object, so it will look on the interface nsidomwindow, and it will find the getdocument() method.
...i'll take two very different examples.
...And 23 more matches
certutil
some smart cards (for example, the litronic card) do not let you remove a public key you have generated.
...some smart cards (for example, the litronic card) can store only one key pair.
...for example: -t "tcu,cu,tuw" use the -l option to see a list of the current certificates and trust attributes in a certificate database.
...And 23 more matches
Web Video Text Tracks Format (WebVTT) - Web APIs
example 1 - simplest possible webvtt file webvtt example 2 - very simple webvtt file with a text header webvtt - this file has no cues.
... example 3 - common webvtt example with a header and cues webvtt - this file has cues.
... 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.
...And 23 more matches
Install Manifests - Archive of obsolete content
id the id of the extension, which must be one of the following: guid (firefox 1.0) a string formatted like so: extensionname@example.org the latter format is significantly easier to generate and manipulate.
... 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.
...And 22 more matches
Templates - Archive of obsolete content
for example, if you are using a tree, you should place the template element inside a tree element.
... simple template example this is better explained with an example.
... let's take a simple example where we want to create a button for each top-level bookmark.
...And 22 more matches
UI pseudo-classes - Learn web development
this included some usage of pseudo-classes, for example using :checked to target a checkbox only when it is selected.
...for example: <form> <fieldset> <legend>feedback form</legend> <div> <label for="fname">first name: </label> <input id="fname" name="fname" type="text" required> </div> <div> <label for="lname">last name: </label> <input id="lname" name="lname" type="text" required> </div> <div> <label for="email">email address (include if you want a response): </label>...
...for example, if we apply the following css to the above html: input:required { border: 1px solid black; } input:optional { border: 1px solid silver; } the required controls would have a black border, and the optional control will have a silver border, like so: you can also try submitting the form without filling it in, to see the client-side validation error messages browsers give you by default.
...And 22 more matches
What is JavaScript? - Learn web development
html is the markup language that we use to structure and give meaning to our web content, for example defining paragraphs, headings, and data tables, or embedding images and videos in the page.
... css is a language of style rules that we use to apply styling to our html content, for example setting background colors and fonts, and laying out our content in multiple columns.
...let's take a simple text label as an example.
...And 22 more matches
Understanding WebAssembly text format - WebAssembly
note: this is potentially overkill if you are a web developer who just wants to load a wasm module into a page and use it in your code (see using the webassembly javascript api), but it is more useful if for example, you want to write wasm modules to optimize the performance of your javascript library, or build your own webassembly compiler.
...) after the signature, locals are listed with their type, for example (local i32).
... for example, local.get is defined to push the value of the local it read onto the stack, and i32.add pops two i32 values (it implicitly grabs the previous two values pushed onto the stack), computes their sum (modulo 2^32) and pushes the resulting i32 value.
...And 22 more matches
StringView - Archive of obsolete content
however, this is slow and error-prone, due to the need for multiple conversions (especially if the binary data is not actually byte-format data, but, for example, 32-bit integers or floats).
... 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][, l...
... examples var mystringview = stringview.makefrombase64("sgvsbg8gd29ybgqh"); alert(mystringview) // "hello world!" this function is useful in order to pass binary data containing strings.
...And 21 more matches
Beginner's guide to media queries - Learn web development
previous overview: css layout next the css media query gives you a way to apply css only when the browser and device environment matches a rule that you specify, for example "viewport is wider than 480 pixels".
... media queries are a key part of responsive web design, as they allow you to create different layouts depending on the size of the viewport, but they can also be used to detect other things about the environment your site is running on, for example whether the user is using a touchscreen rather than a mouse.
... in this lesson you will first learn about the syntax used in media queries, and then move on to use them in a worked example showing how a simple design might be made responsive.
...And 21 more matches
Introduction to web APIs - Learn web development
as a real-world example, think about the electricity supply in your house, apartment, or other dwellings.
...for example, the web audio api provides javascript constructs for manipulating audio in the browser — taking an audio track, altering its volume, applying effects to it, etc.
...for example, the twitter api allows you to do things like displaying your latest tweets on your website.
...And 21 more matches
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.
...http://example.com/foo/bar) or on its end (e.g.
...And 21 more matches
Applying styles and colors - Web APIs
each of the following examples describe the same color.
... // these all set the fillstyle to 'orange' ctx.fillstyle = 'orange'; ctx.fillstyle = '#ffa500'; ctx.fillstyle = 'rgb(255, 165, 0)'; ctx.fillstyle = 'rgba(255, 165, 0, 1)'; a fillstyle example in this example, we once again use two for loops to draw a grid of rectangles, each in a different color.
...etcontext('2d'); for (var i = 0; i < 6; i++) { for (var j = 0; j < 6; j++) { ctx.fillstyle = 'rgb(' + math.floor(255 - 42.5 * i) + ', ' + math.floor(255 - 42.5 * j) + ', 0)'; ctx.fillrect(j * 25, i * 25, 25, 25); } } } <canvas id="canvas" width="150" height="150"></canvas> draw(); the result looks like this: screenshotlive sample a strokestyle example this example is similar to the one above, but uses the strokestyle property to change the colors of the shapes' outlines.
...And 21 more matches
Basic Concepts of grid layout - CSS: Cascading Style Sheets
css grid layout has the following features: fixed and flexible track sizes you can create a grid with fixed track sizes – using pixels for example.
... in this example, i have a containing div with a class of wrapper and, inside are five child elements.
...if you view this example in firefox and inspect the grid, you will see a small icon next to the value grid.
...And 21 more matches
Migrate apps from Internet Explorer to Mozilla - Archive of obsolete content
as a result, mozilla is not fully backwards-compatible with netscape navigator 4.x and microsoft internet explorer legacy code; for example, mozilla does not support <layer> as i will discuss later.
...for example, rather than: if (ismozilla || isie5) you would use: if (document.getelementbyid) this would allow other browsers that support that w3c standard method, such as opera or safari, to work without any changes.
...conditionistrue : conditionisfalse; for example, to retrieve an element, you would use: function getelement(aid){ return (document.getelementbyid) ?
...And 20 more matches
Legacy layout methods - Learn web development
a two column layout let's start with the simplest possible example — a two column layout.
...at the bottom of the section you can see a live example of what the final code should look like.
...replace whatever is inside the body currently with the following: <h1>2 column layout example</h1> <div> <h2>first column</h2> <p> lorem ipsum dolor sit amet, consectetur adipiscing elit.
...And 20 more matches
How to build custom form controls - Learn web development
for example, if you need to perform advanced styling on some controls such as the <select> element or if you want to provide custom behaviors, you may consider building your own controls.
...to that end, we will work with an example: rebuilding the <select> element.
... in our example, we will rebuild the <select> element.
...And 20 more matches
Command line crash course - Learn web development
it is also useful for automation — for example to write a command to update the titles of hundreds of files instantly, say from “ch01-xxxx.png” to “ch02-xxxx.png”.
...ve around your directory structure: cd create directories: mkdir create files (and modify their metadata): touch copy files: cp move files: mv delete files or directories: rm download files found at specific urls: curl search for fragments of text inside larger bodies of text: grep view a file's contents page by page: less, cat manipulate and transform streams of text (for example changing all the instances of <div>s in an html file to <article>): awk, tr, sed note: there are a number of good tutorials on the web that go much deeper into the command line on the web — this is only a brief introduction!
...for example, after typing the above two commands, try typing cd d and pressing tab — it should autocomplete the directory name desktop for you, provided it is present in the current directory.
...And 20 more matches
Drag Operations - Web APIs
here is an example which allows a section of content to be dragged.
... starting a drag operation in this example, a listener is added for the dragstart event by using the ondragstart attribute.
... in this example the dragstart listener is added to the draggable element itself.
...And 20 more matches
Document Object Model - Archive of obsolete content
for example, if the global object has a 'name' property, you can change the name with the code 'name = 7', without having to specify any object to use.
...for example, the following two lines which open a new window are functionally equivalent: window.open("test.xul","_new"); open("test.xul","_new"); when you declare a function or a variable at the top level of a script, that is outside another function, you are actually declaring a property of the global object.
...for example, the following code will display the text 'message' in an alert twice.
...And 19 more matches
LiveConnect Overview - Archive of obsolete content
for example, you can create a java string object and assign it to the javascript variable mystring by using the new operator with the java constructor, as follows: var mystring = new java.lang.string("hello world"); in the previous example, the variable mystring is a javaobject because it holds an instance of the java object string.
...for example, suppose the redwood corporation uses a java package called redwood to contain various java classes that it implements.
...for example, if the helloworld class is directly in the classpath and not in a package, you can access it as follows: var red = new packages.helloworld(); the liveconnect java, sun, and netscape objects provide shortcuts for commonly used java packages.
...And 19 more matches
CSS and JavaScript accessibility best practices - Learn web development
as an example, a screen reader user can't navigate a page via heading elements if the developer hasn't appropriately used heading elements to markup the content.
... form elements elements to allow users to input data into websites: <div> <label for="name">enter your name</label> <input type="text" id="name" name="name"> </div> you can see some good example css in our form-css.html example (see it live also).
... you can see a good, simple example of table html and css in our table-css.html example (see it live also).
...And 19 more matches
Fundamental text and font styling - Learn web development
text layout styles: properties that affect the spacing and other layout features of the text, allowing manipulation of, for example, the space between lines and letters, and how the text is aligned within the content box.
...in this example we'll apply some different css properties to the same html sample, which looks like this: <h1>tommy the cat</h1> <p>well i remember it as though it were a meal ago...</p> <p>said tommy the cat as he reeled back to clear whatever foreign matter may have nestled its way into his mighty throat.
...but it was a rare occasion such as this that he did.</p> you can find the finished example on github (see also the source code.) color the color property sets the color of the foreground content of the selected elements (which is usually the text, but can also include a couple of other things, such as an underline or overline placed on text using the text-decoration property).
...And 19 more matches
Client-Server Overview - Learn web development
a method that defines the required action (for example, to get a file or to save or update some data).
...you might for example use a head request to find out the last time a resource was updated, and then only use the (more "expensive") get request to download the resource if it has changed.
... additional information can be encoded with the request (for example, html form data).
...And 19 more matches
NSS API Guidelines
for example, pkcs #7 is used to encrypt certificate data to exchange between applications, or to encrypt s/mime message data.
... here is an example from lib/base/baset.h: #ifdef debug static const char baset_cvs_id[] = "@(#) $rcsfile: nss-guidelines.html, v $ $revision: 48936 $ $date: 2009-08-11 07:45:57 -0700 (tue, 11 aug 2009) $ $name$"; #endif /* debug */ the difference, between this and id, is that id has some useless information (every file is "experimental"), and doesn't have name.
...for example: layer_capitalizedenglishwords() or cert_destroycertificate().
...And 19 more matches
Plug-in Basics - Plugins
if you are browsing a page that has several embedded realaudio clips, for example, the browser will create as many instances of the realplayer plug-in as are needed (though of course playing several realaudio files at the same time would seldom be a good idea).
...for example: #!/bin/bash export moz_plugin_path=/usr/lib64/mozilla/plugins exec /usr/lib64/firefox/firefox profile directory/plugins, where profile directory is the directory of the current user profile.
... advanced: you can determine which directories a gecko program checks with the linux strace command, for example: strace -e open /usr/bin/firefox 2>&1 | grep plugin but with version firefox-41.0.2 we can not check.
...And 19 more matches
Inputs and input sources - Web APIs
the fundamental capabilities of an input source are: targeting monitoring directional controls (either a motion-sensing pointer or a joystick or trackpad, for example) to aim in a direction, possibly at a target, though targeting is left to you to implement yourself.
...it can also be useful if your app uses the notion of "main hand" and "off hand" for determining the functionality of a controller; in a game, for example, the main hand controller may be the player's weapon while the off hand controller might be used to control the positioning of a shield.
...this space's native origin is located at the point from which the target ray is emitted (such as the front tip of the controller, or the end of a gun barrel if the controller is being rendered as a gun, for example), and the space's orientation vector extends outward along the path of the target ray.
...And 19 more matches
Element Positioning - Archive of obsolete content
for example, the position of a button in a horizontal box is to the right of the previous button, if any.
...for example, a button's width is determined by the amount of text inside the button.
...an example is shown below: example 1: source view <button label="ok" width="100" height="40"/> however, it is not recommended that you do this.
...And 18 more matches
Manipulating documents - Learn web development
using methods available on this object you can do things like return the window's size (see window.innerwidth and window.innerheight), manipulate the document loaded into that window, store data specific to that document on the client-side (for example using a local database or other storage mechanism), attach an event handler to the current window, and more.
...you can use this object to return and manipulate information on the html and css that comprises the document, for example get a reference to an element in the dom, change its text content, apply new styles to it, create new elements and add them to the current element as children, or even delete it altogether.
...this is a "tree structure" representation created by the browser that enables the html structure to be easily accessed by programming languages — for example the browser itself uses it to apply styling and other information to the correct elements as it renders a page, and developers like you can manipulate the dom with javascript after the page has been rendered.
...And 18 more matches
Aprender y obtener ayuda - Learn web development
like most of this course, for example.
...codecademy for example is a learning site where the tutorials mainly consist of interactive code editors where you have to directly write code and see if the desired result was achieved.
... many mdn web docs reference pages provide interactive examples too, where you can alter the code and see how the live result changes.
...And 18 more matches
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?
...for example, a request for content from tracker.example on news.example will not reuse an http connection with a request for content from tracker.example on shopping.example or with requests that occur when tracker.example is visited directly (i.e., as a first party).
...as an example, if a resource from tracker.example is granted storage access on foo.example.com, then tracker.example will be able to access its cookies on bar.foo.example.com but not example.com.
...And 18 more matches
OS.File for the main thread
example: read the contents of a file as text the following snippet opens a file "file.txt" and read its contents as a string, using the default encoding (utf-8).
... let decoder = new textdecoder(); // this decoder can be reused for several reads let promise = os.file.read("file.txt"); // read the complete file as an array promise = promise.then( function onsuccess(array) { return decoder.decode(array); // convert this array to a text } ); this example requires firefox 18 or a more recent version.
... example: write a string to a file the following snippet writes the text "this is some text" to a string "file.txt", using the default encoding (utf-8).
...And 18 more matches
JSAPI User Guide
each time the application runs a js script (using, for example, js_evaluatescript), it provides the global object for that script to use.
... a minimal example each of the three key elements described in the previous section requires a few jsapi calls: the runtime: use js_newruntime to create it and js_destroyruntime to clean it up when you're done.
...the example below defines a very basic jsclass (named global_class) with no methods or properties of its own.
...And 18 more matches
Secure Development Guidelines
introduction provide developers with information on specific security issues cover common coding mistakes and how they affect a product how to avoid making them how to mitigate them everything is oriented toward c/c++ introduction: gaining control specifics about the underlying architecture, using x86 as an example 6 basic registers (eax, ebx, ecx, edx, edi, esi) 2 stack-related registers (esp, ebp) mark top and bottom of current stack frame status register (eflags) contains various state information instruction pointer (eip) points to register being executed; can’t be modified directly introduction: gaining control (2) eip is modified using call or jump instructi...
...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 execute...
... xss: example the following snippet of javascript: document.write("welcome to " + document.location); ...
...And 18 more matches
XPCOM array guide
MozillaTechXPCOMGuideArrays
for example: // handlelist cannot modify the array because of const void handlelist(const nstarray<t>&); in-place enumeration most of the arrays presented here provide callback-style means to enumerate members of an array.
...for example, you should not delete elements of an array during the enumeration as this will often confuse the loop which is enumerating the array.
... example: an array attribute in an idl file would be nsiarray.
...And 18 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 18 more matches
font-family - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... the example below lists two font families, the first with a <family-name> and the second with a <generic-name>: font-family: gill sans extrabold, sans-serif; values <family-name> the name of a font family.
...And 18 more matches
Functions - JavaScript
for example, the following code defines a simple function named square: function square(number) { return number * number; } the function square takes one parameter, called number.
...a non-primitive value, such as array or a user-defined object) as a parameter and the function changes the object's properties, that change is visible outside the function, as shown in the following example: function myfunc(theobject) { theobject.make = 'toyota'; } var mycar = {make: 'honda', model: 'accord', year: 1998}; var x, y; x = mycar.make; // x gets the value "honda" myfunc(mycar); y = mycar.make; // y gets the value "toyota" // (the make property was changed by the function) function expressions while the function declaration above is syntactically a statement, func...
...for example, the function square could have been defined as: const square = function(number) { return number * number } var x = square(4) // x gets the value 16 however, a name can be provided with a function expression.
...And 18 more matches
Tabbed browser - Archive of obsolete content
xul: <menuitem oncommand="myextension.foo(event)" onclick="checkformiddleclick(this, event)" label="click me"/> js: var myextension = { foo: function(event) { openuilink("http://www.example.com", event, false, true); } } opening a url in an on demand tab cu.import("resource://gre/modules/xpcomutils.jsm"); xpcomutils.definelazyservicegetter(this, "gsessionstore", "@mozilla.org/browser/sessionstore;1", "nsisessionstore"); // create new tab, but don't load the content.
... reusing by url/uri a common feature found in many extensions is to point the user to chrome:// uris in a browser window (for example, help or about information) or external (on-line http(s)://) html documents when the user clicks an extension's button or link.
... closing a tab this example closes the currently selected tab.
...And 17 more matches
Object prototypes - Learn web development
let's look at an example to make this a bit clearer.
... understanding prototype objects here we'll go back to the example in which we finished writing our person() constructor — load the example in your browser.
... you can use our oojs-class-further-exercises.html example (see also the source code), if you don't already have it from working through the last article.
...And 17 more matches
Implementing feature detection - Learn web development
let's recap and look at the example we touched on in our handling common javascript problems — the geolocation api (which exposes available location data for the device the web browser is running on) has the main entry point for its use, a geolocation property available on the global navigator object.
... a classic example might be to test for flexbox support in a browser; for browsers that support the newest flexbox spec, we could use a flexible and robust flex layout.
... we will add the html5 shiv to our example too so that the html5 semantic elements will style properly in older versions of ie.
...And 17 more matches
An Overview of XPCOM
they are usually contained in reusable binary libraries (a dll on windows, for example, or a dso on unix), which can include one or more components.
...the network library, for example, consists of components for each of the protocols, http, ftp, and others, which are bundled together and linked into a single library.
...for example, one author's son will not eat a peanut-butter sandwich if there isn't jam on it, because in his world, peanut butter and jam form an indelible union.
...And 17 more matches
Signaling and video calling - Web APIs
you can try out this example on glitch, and you can remix the example to experiment with it as well.
... note: if you try out the example on glitch, please note that any changes made to the code will immediately reset any connections.
...we could have made it receive our original message object, but in this example it's more efficient this way.
...And 17 more matches
Using Web Workers - Web APIs
for example, you can't directly manipulate the dom from inside a worker, or use some default methods and properties of the window object.
...in this section we'll discuss the javascript found in our basic dedicated worker example (run dedicated worker): this allows you to enter two numbers to be multiplied together.
... this example is rather trivial, but we decided to keep it simple while introducing you to basic worker concepts.
...And 17 more matches
<input>: The Input (Form Input) element - HTML: Hypertext Markup Language
WebHTMLElementinput
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... the 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.
...And 17 more matches
Menus - Archive of obsolete content
the following is a brief summary of these elements, examples of each will be provided later.
...for example, the file and edit menus along the top of an application window (or the menubar on the top of screen).
...this type of menu would be used when you want to have a set of commands yet don't want to use a menu bar, for example in a dialog box.
...And 16 more matches
Template Logging - Archive of obsolete content
for example, if you spell a value wrong, no data may be returned, but the template system won't know that that this was because of a spelling error, or simply that there shouldn't be any data anyway.
...each result is logged in a form much like the following: in template with id root using ref http://www.some-fictitious-zoo.com/birds new active result for query 2 matching rule 1: http://www.some-fictitious-zoo.com/birds/emperorpenguin in the example above, a new result has been added.
...the example also specifies 'query 2 matching rule 1'.
...And 16 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.
...example 1: client-side detection scripts browser architecture supports: netscapeplugin windows media player installed: true windows media scriptable: false windows media version: pluginversion a complete source code listing showing how that detection was done can be found here (devedge-temp).
...for example if (window.activexobject) { // internet explorer only script } server-side detection using user-agent strings netscape 7.1's user agent string on windows has the general pattern: mozilla/5.0 (windows; u; <em>operating system version</em>; <em>language</em>; rv:1.4) gecko/20030624 netscape/7.1 (ax<em>[;optional comments]</em>) the "vendor comment" (ax) following the "vendor version" netscap...
...And 16 more matches
Anatomy of a video game - Game development
your game loop might be similar to the find the differences example and base itself on input events.
...here is an example of a simple main loop: window.main = function () { window.requestanimationframe( main ); // whatever your main loop needs to do }; main(); // start the cycle note: in each of the main() methods discussed here, we schedule a new requestanimationframe before performing our loop contents.
... building a better main loop in javascript there are two obvious issues with our previous main loop: main() pollutes the window object (where all global variables are stored) and the example code did not leave us with a way to stop the loop unless the whole tab is closed or refreshed.
...And 16 more matches
Backgrounds and borders - Learn web development
in the example below, we have used various color values to add a background color to the box, a heading, and a <span> element.
...in the example below, we have two boxes — one has a background image which is larger than the box, the other has a small image of a star.
... this example demonstrates two things about background images.
...And 16 more matches
Responsive design - Learn web development
note: see this simple liquid layout: example, source code.
... when viewing the example, drag your browser window in and out to see how this looks at different sizes.
... note: see this simple fixed-width layout: example, source code.
...And 16 more matches
JavaScript basics - Learn web development
example javascript is one of the most popular modern web technologies!
...example.
...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.
...And 16 more matches
Introducing asynchronous JavaScript - Learn web development
let's look at a simple example (see it live here, and see the source): const btn = document.queryselector('button'); btn.addeventlistener('click', () => { alert('you clicked me!'); let pelem = document.createelement('p'); pelem.textcontent = 'this is a newly-added paragraph.'; document.body.appendchild(pelem); }); in this block, the lines are executed one after the other: we grab a reference to a <button> elemen...
... so in the example above, after you've clicked the button the paragraph won't appear until after the ok button is pressed in the alert box.
...let's look at a quick example.
...And 16 more matches
Basic math in JavaScript — numbers and operators - Learn web development
we use different terms to describe different types of decimal numbers, for example: integers are whole numbers, e.g.
... floating point numbers (floats) have decimal points and decimal places, for example 12.5, and 56.7786543.
... for example, to round your number to a fixed number of decimal places, use the tofixed() method.
...And 16 more matches
Setting up your own test automation environment - Learn web development
most popular environments have available a package or framework that will install webdriver and the bindings required to communicate with webdriver using this language, for example, java, c#, ruby, python, javascript (node), etc.
...for example, if we were using a mac os x machine, our user name was bob, and we put our drivers in the root of our home folder, the path would be /users/bob.
...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.
...And 16 more matches
Python binding for NSS
examples of this are the various callbacks which can be set and their parameters.
...for example it is already known there are some naming inconsistencies.
... example code the doc/examples directory contains numerous examples of python-nss programs and libraries you may wish to consult.
...And 16 more matches
Starting WebLock
for example, an object may be created and have its observe method called at startup, or it may register to be notified prior to xpcom shutdown.
...for example, in the case of the xpcom shutdown observation, asubject and adata are not defined, and atopic is defined as the string "xpcom-shutdown".
...xxx what is example 2?following example 2, you change the class definition to support the nsiobserver interface and change ns_impl_isupports1 so that the queryinterface implementation knows that the component also supports nsiobserver.
...And 16 more matches
nsIPromptService
a delay can be useful not only to give the user more time to think before acting, but also as a countermeasure against malicious web sites that intentionally create a race condition whereby the user intends to click or type a key responding, for example, to the web site's prompt but the security dialog pops up unexpectedly and its button is unintentionally activated.
... see also the alert_example.
... see also the alertcheck_example.
...And 16 more matches
Working with windows in chrome code
it contains tips and example code on opening new windows, finding an already opened window, and passing data between different windows.
... from xpcom components and modules if the window object is unavailable (for example, when opening a window from xpcom component code), you might want to use nsiwindowwatcher interface.
...so, for example, to access the dom document corresponding to the window, you can use win.document.
...And 16 more matches
Using the CSS Painting API - Web APIs
*/ paint(ctx) { ctx.fillstyle = 'hsla(55, 90%, 60%, 1.0)'; ctx.fillrect(0, 15, 200, 20); /* order: x, y, w, h */ } }); in this class example we have defined a single context option with the contextoptions() function: we returned a simple object stating alpha transparency is allowed.
... we tried to keep the example simple.
... in our example, the paintworklet is stored on github.
...And 16 more matches
Introduction to the DOM - Web APIs
for example, the standard dom specifies that the getelementsbytagname method in the code below must return a list of all the <p> elements in the document: const paragraphs = document.getelementsbytagname("p"); // paragraphs[0] is the first <p> element // paragraphs[1] is the second <p> element, etc.
... alert(paragraphs[0].nodename); all of the properties, methods, and events available for manipulating and creating web pages are organized into objects (for example, the document object that represents the document itself, the table object that implements the special htmltableelement dom interface for accessing html tables, and so forth).
...for example, the html dom api adds support for representing html documents to the core dom.
...And 16 more matches
Web Accessibility: Understanding Colors and Luminance - Accessibility
for example, "saturation" is known as "chroma" in some circles.
... for example, the color "crimson red" may be described in hex values as #990000 by some and #dc143c by others.
...webgl is usually in the rgba format; see an example of how it is used in "clearing with colors".
...And 16 more matches
Reference - Archive of obsolete content
for example, "script" and "program" are synonymous.
...-- 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.
...And 15 more matches
Cascade and inheritance - Learn web development
in the below example, we have two rules that could apply to the h1.
... example time!
... for example, if you set a color and font-family on an element, every element inside it will also be styled with that color and font, unless you've applied different color and font values directly to them.
...And 15 more matches
Floats - Learn web development
but web developers quickly realized that you can float anything, not just images, so the use of float broadened, for example to fun layout effects such as drop-caps.
... a simple float example let's explore how to use floats.
... we'll start with a really simple example involving floating a block of text around an element.
...And 15 more matches
Positioning - Learn web development
previous overview: css layout next positioning allows you to take elements out of the normal document layout flow, and make them behave differently; for example sitting on top of one another, or always remaining in the same place inside the browser viewport.
... static positioning static positioning is the default that every element gets — it just means "put the element into its normal position in the document layout flow — nothing special to see here." to demonstrate this, and get your example set up for future sections, first add a class of positioned to the second <p> in the html: <p class="positioned"> ...
... note: you can see the example at this point live at 1_static-positioning.html (see source code).
...And 15 more matches
Creating hyperlinks - Learn web development
for example, the bbc homepage contains a many links that point not only to multiple news stories, but also different areas of the site (navigation functionality), login/registration pages (user tools), and more.
...if a title's information is truly important to the usability of page, then you should present it in a manner that will be accessible to all users, for example by putting it in the regular text.
... active learning: creating your own example link create an html document using your local code editor and our getting started template.
...And 15 more matches
HTML text fundamentals - Learn web development
implementing structural hierarchy for example, in this story, the <h1> element represents the title of the story, the <h2> elements represent the title of each chapter, and the <h3> elements represent sub-sections of each chapter: <h1>the crushing bore</h1> <p>by chris mills</p> <h2>chapter 1: the dark night</h2> <p>it was a dark night.
... to answer this question, let's take a look at text-start.html—the starting point of our running example for this article (a nice hummus recipe).
... active learning: giving our content structure let's jump straight in with a live example.
...And 15 more matches
What’s in the head? Metadata in HTML - Learn web development
in the above example, the head is quite small: <head> <meta charset="utf-8"> <title>my test page</title> </head> in larger pages however, the head can get quite full.
... the <h1> element appears on the page when loaded in the browser — generally this should be used once per page, to mark up the title of your page content (the story title, or news headline, or whatever is appropriate to your usage.) the <title> element is metadata that represents the title of the overall html document (not the document's content.) active learning: inspecting a simple example to start off this active learning, we'd like you to go to our github repo and download a copy of our title-example.html page.
...for example, if you try bookmarking the page (bookmarks > bookmark this page or the star icon in the url bar in firefox), you will see the <title> contents filled in as the suggested bookmark name.
...And 15 more matches
Fetching data from the server - Learn web development
the trouble with this model is that whenever you want to update any part of the page, for example, to display a new set of products or load a new page, you've got to load the entire page again.
...for these examples, we'll request data out of a few different text files and use them to populate a content area.
... to begin this example, make a local copy of ajax-start.html and the four text files — verse1.txt, verse2.txt, verse3.txt, and verse4.txt — in a new directory on your computer.
...And 15 more matches
NSS tools : modutil
MozillaProjectsNSStoolsmodutil
usage and examples creating database files before any operations can be performed, there must be a set of security databases available.
...for the most basic case, simply upload the library: modutil -add modulename -libfile library-file [-ciphers cipher-enable-list] [-mechanisms mechanism-list] for example: modutil -dbdir sql:/home/my/sharednssdb -add "example pkcs #11 module" -libfile "/tmp/crypto.so" -mechanisms rsa:dsa:rc2:random using database directory ...
... module "example pkcs #11 module" added to database.
...And 15 more matches
Working with data
example: creating an array let arraytype = ctypes.arraytype(ctypes.int32_t); let myarray = new arraytype(5); at this point, myarray.length is 5; there are 5 entries in the array.
... example: creating an array of strings var cstr1 = ctypes.jschar.array()('rawr'); var cstr2 = ctypes.jschar.array()('boo'); var mycarray_ofstrings = ctypes.jschar.ptr.array(2)([cstr1, cstr2]); // specifying length of 2 is optional, can omit it, so can just do `ctypes.jschar.ptr.array()([cstr1, cstr2])` mycarray_ofstrings.addressofelement(0).contents.readstring(); // outputs: "rawr" mycarray_ofstrings.addressofelement(1).contents.readstring(); // outputs: "boo" example: creating an array of integers var jsarr = [4, 10]; var mycarr = ctypes.int.array(jsarr.length)(jsarr); // specifying length is optional, can omit.
... example: cast an array this example shows how to cast an array of a certain type to another type.
...And 15 more matches
filter - CSS: Cascading Style Sheets
WebCSSfilter
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... filter: blur(5px) <table class="standard-table"> <thead> <tr> <th style="text-align: left;" scope="col">original image</th> <th style="text-align: left;" scope="col">live example</th> <th style="text-align: left;" scope="col">svg equivalent</th> <th style="text-align: left;" scope="col">static example</th> </tr> </thead> <tbody> <tr> <td><img alt="test_form.jpg" id="img1" class="internal default" src="/files/3710/test_form_2.jpg" style="width: 100%;" /></td> <td><img alt="test_form.jpg" id="img2" class="internal default" src="/files/371...
...And 15 more matches
Content Security Policy (CSP) - HTTP
WebHTTPCSP
(sometimes you may see mentions of the x-content-security-policy header, but that's an older version and you don't need to specify it anymore.) alternatively, the <meta> element can be used to configure a policy, for example: <meta http-equiv="content-security-policy" content="default-src 'self'; img-src https://*; child-src 'none';"> threats mitigating cross site scripting a primary goal of csp is to mitigate and report xss attacks.
... mitigating packet sniffing attacks in addition to restricting the domains from which content can be loaded, the server can specify which protocols are allowed to be used; for example (and ideally, from a security standpoint), a server can specify that all content must be loaded using https.
...for example, a page that uploads and displays images could allow images from anywhere, but restrict a form action to a specific endpoint.
...And 15 more matches
Inner-browsing extending the browser navigation paradigm - Archive of obsolete content
for web developers, for example, it provides less fine-grained control over the experience, and it can strain bandwidth and other resources.
...it also provides two implementation examples using the model.
...the second example shows a tabbed menu that dynamically loads news headlines into the current web page.
...And 14 more matches
JXON - Archive of obsolete content
there are some cases in which the whole content of an xml document must be read from the javascript interpreter (like for web-apps languages or settings xml documents, for example).
... conversion snippets now imagine you have this sample xml document: example.xml <?xml version="1.0"?> <!doctype catalog system "catalog.dtd"> <catalog> <product description="cardigan sweater"> <catalog_item gender="men's"> <item_number>qwz5671</item_number> <price>39.95</price> <size description="medium"> <color_swatch image="red_cardigan.jpg">red</color_swatch> <color_swatch image="burgundy_cardigan.jpg">burgundy</color_swatch> </...
...dec 25, 1995</discount_until> <price>42.50</price> <size description="medium"> <color_swatch image="black_cardigan.jpg">black</color_swatch> </size> </catalog_item> </product> <script type="text/javascript"><![cdata[function matchwo(a,b) { if (a < b && a < 0) { return 1; } else { return 0; } }]]></script> </catalog> first, create a dom tree like the previous example as described in the how to create a dom tree article.
...And 14 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".
...statements about the same rdf resource can then be intermingled: for example, the "last visit date" of a particular website comes from the "browser global history" datasource, and the "shortcut keyword" that you can type to reach that website comes from the "browser bookmarks" datasource.
... for example, rdf:foo would load: @mozilla.org/rdf/datasource;1?name=foo as with rdf/xml datasources, a datasource that is retrieved this way is "cached" by the rdf service until the last reference is dropped.
...And 14 more matches
Mobile accessibility - Learn web development
for example: single-tapping an app will select it, and the device will read out what the app is.
... for example, with talkback turned on: open your web browser.
... tap with two fingers to perform a context-relevant action — for example, taking a photo while in the camera app.
...And 14 more matches
Accessible multimedia - Learn web development
for example: <img src="dinosaur.png" alt="a red tyrannosaurus rex: a two legged dinosaur standing upright like a human, with small arms, and a large head with lots of sharp teeth."> accessible audio and video controls implementing controls for web-based audio/video shouldn't be a problem, right?
...for example (see native-controls.html source code and live): <audio controls> <source src="viper.mp3" type="audio/mp3"> <source src="viper.ogg" type="audio/ogg"> <p>your browser doesn't support html5 audio.
... let's take the video example from above and add custom controls to them.
...And 14 more matches
Flexbox - Learn web development
introducing a simple example in this article we are going to get you to work through a series of exercises to help you understand how flexbox works.
... the parent element that has display: flex set on it (the <section> in our example) is called the flex container.
... the items being laid out as flexible boxes inside the flex container are called flex items (the <article> elements in our example).
...And 14 more matches
Advanced form styling - Learn web development
for example, let's take the following controls: <form> <p> <label for="search">search: </label> <input id="search" name="search" type="search"> </p> <p> <label for="text">text: </label> <input id="text" name="text" type="text"> </p> <p> <label for="date">date: </label> <input id="date" name="date" type="datetime-local"> </p> <p> <label for="radio">radio: </label> ...
... the following live example shows you what they look like in your system — default on the left, and with the above css applied on the right (find it here also if you want to test it on other systems).
...the answer is that in chromium-based browsers on macos, search boxes have some styling restrictions — you can't adjust their height or font-size freely, for example.
...And 14 more matches
Basic native form controls - Learn web development
previous overview: forms next in the previous article, we marked up a functional web form example, introducing some form controls and common structural elements, and focusing on accessibility best practices.
...they are a very convenient way to let the user enter any kind of data, and we've already seen a few simple examples.
...the value text for this attribute is also the fallback value if the value you specify for the type attribute is unknown by the browser (for example if you specify type="color" and the browser doesn't support native color pickers).
...And 14 more matches
Sending form data - Learn web development
in this example, the data is sent to an absolute url — https://example.com: <form action="https://example.com"> here, we use a relative url — the data is sent to a different url on the same origin: <form action="/somewhere_else"> when specified with no attributes, as below, the <form> data is sent to the same page that the form is present on: <form> note: it's possible to specify a url that uses the h...
...in this case we are passing two pieces of data to the server: say, which has a value of hi to, which has a value of mom the http request looks like this: get /?say=hi&to=mom http/2.0 host: foo.com note: you can find this example on github — see get-method.html (see it live also).
... let's look at an example — this is the same form we looked at in the get section above, but with the method attribute set to post.
...And 14 more matches
NSS tools : modutil
usage and examples creating database files before any operations can be performed, there must be a set of security databases available.
...for the most basic case, simply upload the library: modutil -add modulename -libfile library-file [-ciphers cipher-enable-list] [-mechanisms mechanism-list] for example: modutil -dbdir sql:/home/my/sharednssdb -add "example pkcs #11 module" -libfile "/tmp/crypto.so" -mechanisms rsa:dsa:rc2:random using database directory ...
... module "example pkcs #11 module" added to database.
...And 14 more matches
Drawing shapes with canvas - Web APIs
rectangular shape example <html> <body onload="draw();"> <canvas id="canvas" width="150" height="150"></canvas> </body> </html> function draw() { var canvas = document.getelementbyid('canvas'); if (canvas.getcontext) { var ctx = canvas.getcontext('2d'); ctx.fillrect(25, 25, 100, 100); ctx.clearrect(45, 45, 60, 60); ctx.strokerect(50, 50, 50, 50); } } this example's output is shown below.
... drawing a triangle for example, the code for drawing a triangle would look something like this: <html> <body onload="draw();"> <canvas id="canvas" width="100" height="100"></canvas> </body> </html> function draw() { var canvas = document.getelementbyid('canvas'); if (canvas.getcontext) { var ctx = canvas.getcontext('2d'); ctx.beginpath(); ctx.moveto(75, 50); ctx.lineto(100, 75); ctx.lineto(10...
... the example below draws two triangles, one filled and one outlined.
...And 14 more matches
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.
... as our simple stream pump example shows (see it live also), exposing it is a matter of just accessing the body property of the response: // fetch the original image fetch('./tortoise.png') // retrieve its body as readablestream .then(response => response.body) this provides us with a readablestream object.
...And 14 more matches
Using XMLHttpRequest - Web APIs
examples of both common and more obscure use cases for xmlhttprequest are included.
... function reqlistener () { console.log(this.responsetext); } var oreq = new xmlhttprequest(); oreq.addeventlistener("load", reqlistener); oreq.open("get", "http://www.example.org/example.txt"); oreq.send(); types of requests a request made via xmlhttprequest can fetch the data in one of two ways, asynchronously or synchronously.
... for example, consider this snippet, which uses the responsetype of "arraybuffer" to fetch the remote content into a arraybuffer object, which stores the raw binary data.
...And 14 more matches
Implementing a Microsoft Active Accessibility (MSAA) Server - Accessibility
for example, screen readers look for screen draws of a vertical blinking line, to determine the location of the caret.
...for example, gecko support isimpledomnode to provide information about the dom node for an accessible object.
...[important] get_accname: get the "name" of the iaccessible, for example the name of a button, checkbox or menu item.
...And 14 more matches
Relationship of grid layout to other layout methods - CSS: Cascading Style Sheets
two-dimensional layout a simple example can demonstrate the difference between one- and two-dimensional layouts.
... in this first example, i am using flexbox to lay out a set of boxes.
... the same layout with css grids in this next example, i create the same layout using grid.
...And 14 more matches
<input type="email"> - HTML: Hypertext Markup Language
WebHTMLElementinputemail
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...see allowing multiple e-mail addresses for an example, or html attribute: multiple for more details.
...And 14 more matches
<input type="tel"> - HTML: Hypertext Markup Language
WebHTMLElementinputtel
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...e id of the <datalist> element that contains the optional pre-defined autocomplete options maxlength the maximum length, in utf-16 characters, to accept as a valid input minlength the minimum length that is considered valid for the field's contents pattern a regular expression the entered value must match to pass constraint validation placeholder an example value to display inside the field when it has no value readonly a boolean attribute which, if present, indicates that the field's contents should not be user-editable size the number of characters wide the input field should be onscreen list the values of the list attribute is the id of a <datalist> element located in the same document.
...And 14 more matches
Details of the object model - JavaScript
for example, the employee class could represent the set of all employees.
...for example, victoria could be an instance of the employee class, representing a particular individual as an employee.
...for example, assume the employee class includes only the name and dept properties, and manager is a subclass of employee that adds the reports property.
...And 14 more matches
Working with objects - JavaScript
compare it with a cup, for example.
...for example, let's create an object named mycar and give it properties named make, model, and year as follows: var mycar = new object(); mycar.make = 'ford'; mycar.model = 'mustang'; mycar.year = 1969; the above example could also be written using an object initializer, which is a comma-delimited list of zero or more pairs of property names and associated values of an object, enclosed in curly braces ({})...
...so, for example, you could access the properties of the mycar object as follows: mycar['make'] = 'ford'; mycar['model'] = 'mustang'; mycar['year'] = 1969; an object property name can be any valid javascript string, or anything that can be converted to a string, including the empty string.
...And 14 more matches
Using custom elements - Web Components
so for example, we can define a custom word-count element like this: customelements.define('word-count', wordcount, { extends: 'p' }); the element is called word-count, its class object is wordcount, and it extends the <p> element.
...for example, wordcount is structured like so: class wordcount extends htmlparagraphelement { constructor() { // always call super first in constructor super(); // element functionality written in here ...
... } } this is just a simple example, but there is more you can do here.
...And 14 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 13 more matches
Notes on HTML Reflow - Archive of obsolete content
more than one frame may be needed to represent a single element from the content model; for example, text that wraps is broken into several frames, one per wrapped line.
...reflow may have the side-effect of creating new continuation frames, for example, for a text frame when the text must be wrapped.
... some reflows are immediate in response to user or script actions; for example, resizing the window or changing the document's default font.
...And 13 more matches
Multiple Rules - Archive of obsolete content
« previousnext » all of the examples shown so far have used only a single rule.
...for example, the first rule might match directories or folders, whereas the second rule might match files.
...in this example, the where element in the first rule defines a condition which matches results that have a title of 'canal'.
...And 13 more matches
Adobe Flash - Archive of obsolete content
the example below shows a detection heuristic in action.
... example 1: verifying the flash plugin version below, javascript identifies the version of flash, and whether it is scriptable in netscape gecko: can we have javascript in a wiki page?
...for example, the current flash plugin version is flash 6 r79.
...And 13 more matches
Responsive images - Learn web development
here's a simple example: this works well on a wide screen device, such as a laptop or desktop (you can see the example live and find the source code on github.) we won't discuss the css much in this lesson, except to say that: the body content has been set to a maximum width of 1200 pixels — in viewports above that width, the body remains at 1200px and centers itself in the available space.
...raster image formats such as jpegs are more suited to the kind of images we see in the above example.
...you should note that we will be focusing on the html <img>s for this section, as seen in the content area of the example above — the image in the site header is only for decoration, and therefore implemented using css background images.
...And 13 more matches
NSS Tools modutil
-dbprefix prefix specify the prefix used on the cert8.db and key3.db files (for example, my_cert8.db and my_key3.db).
...this directory should be one below which it is appropriate to store dynamic library files (for example, a server's root directory or the netscape communicator root directory).
... sample script for example, the pkcs #11 installer script could be in the file pk11install.
...And 13 more matches
nsIHttpChannel
inherits from: nsichannel last changed in gecko 1.3 to create an http channel, use nsiioservice with a http uri, for example: var ios = components.classes["@mozilla.org/network/io-service;1"] .getservice(components.interfaces.nsiioservice); var ch = ios.newchannel("https://www.example.com/", null, null); method overview void getoriginalresponseheader(in acstring aheader, in nsihttpheadervisitor avisitor); acstring getrequestheader(in acstring aheader); acstring getresponseheader(in acstring header); boolea...
...this should be set to false, for example, if the application knows that the corresponding document is likely to be very large.
... responsestatus unsigned long get the http response code (for example 200).
...And 13 more matches
Using DTMF with WebRTC - Web APIs
each time a tone is sent, the rtcpeerconnection receives a tonechange event with a tone property specifying which tone finished playing, which is an opportunity to update interface elements, for example.
...instead, we'll focus on how to use dtmf within the context of an rtcpeerconnection by studying how an example works.
... simple example this simple example constructs two rtcpeerconnections, establishes a connection between them, then waits for the user to click a "dial" button.
...And 13 more matches
WindowOrWorkerGlobalScope.setInterval() - Web APIs
examples example 1: basic syntax the following example demonstrates setinterval()'s basic syntax.
... console.log(a); console.log(b); } example 2: alternating two colors the following example calls the flashtext() function once a second until the stop button is pressed.
... <!doctype html> <html> <head> <meta charset="utf-8" /> <title>setinterval/clearinterval example</title> <script> var nintervid; function changecolor() { nintervid = setinterval(flashtext, 1000); } function flashtext() { var oelem = document.getelementbyid('my_box'); oelem.style.color = oelem.style.color == 'red' ?
...And 13 more matches
An overview of accessible web applications and widgets - Accessibility
example 1: markup for a tabs widget built without aria labeling.
...--> <ol> <li id="ch1tab"> <a href="#ch1panel">chapter 1</a> </li> <li id="ch2tab"> <a href="#ch2panel">chapter 2</a> </li> <li id="quiztab"> <a href="#quizpanel">quiz</a> </li> </ol> <div> <div id="ch1panel">chapter 1 content goes here</div> <div id="ch2panel">chapter 2 content goes here</div> <div id="quizpanel">quiz content goes here</div> </div> example 2: how the tabs widget might be styled visually.
... example 3: markup for the tabs widget with aria attributes added.
...And 13 more matches
Variable fonts guide - CSS: Cascading Style Sheets
for example linux oses need the latest linux freetype version, and macos prior to 10.13 does not support variable fonts.
...the reason for this is that most typefaces have very specific designs for bolder weights and italics that often include completely different characters (lower-case 'a' and 'g' are often quite different in italics, for example).
...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.
...And 13 more matches
<input type="range"> - HTML: Hypertext Markup Language
WebHTMLElementinputrange
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... see the range control with hash marks below for an example of how the options on a range are denoted in supported browsers max the greatest value in the range of permitted values.
...And 13 more matches
Functions - JavaScript
for more examples and explanations, see also the javascript guide about functions.
...however, object references are values, too, and they are special: if the function changes the referred object's properties, that change is visible outside the function, as shown in the following example: /* declare the function 'myfunc' */ function myfunc(theobject) { theobject.brand = "toyota"; } /* * declare variable 'mycar'; * create and initialize a new object; * assign reference to it to 'mycar' */ var mycar = { brand: "honda", model: "accord", year: 1998 }; /* logs 'honda' */ console.log(mycar.brand); /* pass object reference to the function */ myfunc(mycar); /* * logs 't...
...one can define "named" function expressions (where the name of the expression might be used in the call stack for example) or "anonymous" function expressions.
...And 13 more matches
Intl.DateTimeFormat.prototype.formatToParts() - JavaScript
the structure the formattoparts() method returns, looks like this: [ { type: 'day', value: '17' }, { type: 'weekday', value: 'monday' } ] possible types are the following: day the string used for the day, for example "17".
... dayperiod the string used for the day period, for example, "am", "pm", "in the morning", or "noon" era the string used for the era, for example "bc" or "ad".
... fractionalsecond the string used for the fractional seconds, for example "0" or "00" or "000".
...And 13 more matches
XUL Migration Guide - Archive of obsolete content
next, we'll look at some of the main tasks involved in migrating: working with content scripts using the sdk's supported apis how to go beyond the supported apis when necessary, by: using third party modules using the sdk's low-level apis getting direct access to xpcom finally, we'll walk through a simple example.
...in this way an extension can integrate its user interface into the browser: for example, adding menu items, buttons, and toolbars.
... my-addon/ chrome/ content/ locale/ skin/ chrome.manifest data/ lib/ package.json there are limitations on what you can do in this manifest file: for example, you can't register overlays, resource: uris, or components.
...And 12 more matches
File I/O - Archive of obsolete content
use of os.file is preferred over the examples in this article.
... createinstance(components.interfaces.nsilocalfile); file.initwithpath("/home"); note: the path should be in the "native" form (for example"c:\\windows").
... defprofrt d the root of the default profile directory (for example /root/.mozilla).
...And 12 more matches
Box Objects - Archive of obsolete content
some content nodes may have several layout objects, for example, each line of a paragraph has a separate layout object.
...a xul element, for example, will have a xulelement type of content node.
...for example changing the display property of a button element to block will cause the button layout object to be deleted and a block object to be created instead.
...And 12 more matches
Properly Using CSS and JavaScript in XHTML Documents - Archive of obsolete content
} </script> note that this example is not well formed xhtml since the use of raw < is only allowed as a part of markup in xhtml or xml.
... <style type="text/css"> <!-- body {background-color: blue; color: yellow;} --> </style> <script type="text/javascript"> <!-- var i = 0; var sum = 0; for (i = 0; i < 10; ++i) { sum += i; } alert('sum = ' + sum); // --> </script> this example illustrates that a conformant browser can ignore content inside of comments.
... in addition, this example shows how the differences between browsers in handling inline content in text/xml or application/xhtml+xml can be problematic.
...And 12 more matches
Sizing items in CSS - Learn web development
a straightforward example is an image.
...we have given the image in the example below a border so that you can see the extent of the file.
...in our example below, that border stretches to the width of the container, because it is a block level element, a behavior that should be starting to become familiar to you.
...And 12 more matches
Images in HTML - Learn web development
so for example, if your image is called dinosaur.jpg, and it sits in the same directory as your html page, you could embed the image like so: <img src="dinosaur.jpg"> if the image was in an images subdirectory, which was inside the same directory as the html page (which google recommends for seo/indexing purposes), then you'd embed it like this: <img src="images/dinosaur.jpg"> and so on.
... you could embed the image using its absolute url, for example: <img src="https://www.example.com/images/dinosaur.jpg"> but this is pointless, as it just makes the browser do more work, looking up the ip address from the dns server all over again, etc.
... note: you can find the finished example from this section running on github (see the source code too.) alternative text the next attribute we'll look at is alt.
...And 12 more matches
HTML table basics - Learn web development
LearnHTMLTablesBasics
a table allows you to quickly and easily look up values that indicate some kind of connection between different types of data, for example a person and their age, or a day of the week, or the timetable for a local swimming pool.
...look at the table below for example and find a jovian gas giant with 62 moons.
... table styling you can also have a look at the live example on github!
...And 12 more matches
Making asynchronous programming easier with async and await - Learn web development
here is a trivial example: async function hello() { return greeting = await promise.resolve("hello"); }; hello().then(alert); of course, the above example is not very useful, although it does serve to illustrate the syntax.
... let's move on and look at a real example.
... rewriting promise code with async/await let's look back at a simple fetch example that we saw in the previous article: fetch('coffee.jpg') .then(response => { if (!response.ok) { throw new error(`http error!
...And 12 more matches
Looping code - Learn web development
let's look at an example to perfectly illustrate why loops are such a good thing.
... let's say we wanted to draw 100 random circles on a <canvas> element (press the update button to run the example again and again to see different random sets): hidden code <!doctype html> <html> <head> <meta charset="utf-8"> <title>random canvas circles</title> <style> html { width: 100%; height: inherit; background: #ddd; } canvas { display: block; } body { margin: 0; } button { position: absolute; top: 5px; left: 5px; } </style> </head> <body> <button>update</button> <canvas></canvas> <script> const btn = document.queryselector('button'); const canvas = document.queryselector('canvas'); const ctx = canvas.getcontext('2d'); let ...
... let's look at a real example so we can visualize what these do more clearly.
...And 12 more matches
Inheritance in JavaScript - Learn web development
let's explore how to do this with a concrete example.
...inside here you'll find the same person() constructor example that we've been using all the way through the module, with a slight difference — we've defined only the properties inside the constructor: function person(first, last, age, gender, interests) { this.name = { first, last }; this.age = age; this.gender = gender; this.interests = interests; }; the methods are all defined on the constructor's prototype.
... for example: person.prototype.greeting = function() { alert('hi!
...And 12 more matches
Strategies for carrying out testing - Learn web development
by coding defensively, we mean trying to build in intelligent fallbacks so that if a feature or style doesn't work in a browser, the site will be able to downgrade to something less exciting that still provides an acceptable user experience — the core information is still accessible, for example, even if it doesn't look quite as nice.
...you can make this as simple or as complex as you like — for example a common approach is to have multiple grades of support level, something like: a grade: common/modern browsers — known to be capable.
... for example, if you live in western europe or north america, you will know that a lot of people use windows and mac desktops/laptops, where the main browsers are chrome, firefox, safari, ie, and edge.
...And 12 more matches
Scripting Java
for example, we can access the value of the java package: js> packages.java [javapackage java] as a handy shortcut, rhino defines a top-level variable java that is equivalent to packages.java.
... so the previous example could be even shorter: js> java [javapackage java] we can access java classes simply by stepping down the package hierarchy: js> java.io.file [javaclass java.io.file] if your scripts access a lot of different java classes, it can get awkward to use the full package name of the class every time.
...for example, we could import all of the classes in the java.io package and access class java.io.file using just the name file: js> importpackage(java.io) js> file [javaclass java.io.file] here importpackage(java.io) makes all the classes in the java.io package (such as file) available at the top level.
...And 12 more matches
nsIWebProgressListener
(see below for a description of document requests.) other types of requests, such as requests for inline content (for example images and stylesheets) are considered normal requests.
...this includes other document requests (for example corresponding to html <iframe> elements).
... for example, in the case of navigation within a single frame of a html frameset, a nsiwebprogresslistener instance attached to the nsiwebprogress of the frameset window will receive onstatechange() calls with the state_is_network flag set to indicate the start and stop of said navigation.
...And 12 more matches
Using IndexedDB - Web APIs
so for example, don't use 2.4 as a version number: var request = indexeddb.open("mytestdatabase", 2.4); // don't do this, as the version will be rounded to 2 generating handlers the first thing you'll want to do with almost all of the requests you generate is to add success and error handlers: request.onerror = function(event) { // do something with request.errorcode!
...creating or updating the version of the database when you create a new database or increase the version number of an existing database (by specifying a higher version number than you did previously, when opening a database), the onupgradeneeded event will be triggered and an idbversionchangeevent object will be passed to any onversionchange event handler set up on request.result (i.e., db in the example).
...so, for example, if you have an object store which holds a set of people, and you want to ensure that no two people have the same email address, you can use an index with the unique flag set to enforce this.
...And 12 more matches
Capabilities, constraints, and settings - Web APIs
this article discusses capabilities and constraints, as well as media settings, and includes an example we call the constraint exerciser.
... overview the process works like this (using mediastreamtrack as an example): if needed, call mediadevices.getsupportedconstraints() to get the list of supported constraints, which tells you what constrainable properties the browser knows about.
...f you need to know whether or not a given constriant is supported by the user agent, you can find out by calling navigator.mediadevices.getsupportedconstraints() to get a list of the constrainable properties which the browser knows, like this: let supported = navigator.mediadevices.getsupportedconstraints(); document.getelementbyid("framerateslider").disabled = !supported["framerate"]; in this example, the supported constraints are fetched, and a control that lets the user configure the frame rate is disabled if the framerate constraint isn't supported.
...And 12 more matches
Writing WebSocket client applications - Web APIs
note: the example snippets in this article are taken from our websocket chat client/server sample.
... see the code, then try out the example for yourself.
...these strings are used to indicate sub-protocols, so that a single server can implement multiple websocket sub-protocols (for example, you might want one server to be able to handle different types of interactions depending on the specified protocol).
...And 12 more matches
Cognitive accessibility - Accessibility
for example, dementia and alzheimer's are permanent cognitive impairments that get progressively worse.
... an example of a temporary cognitive impairment could be people affected by substances such as alcohol or drugs.
...a third example could be sleep deprivation.
...And 12 more matches
Controlling Ratios of Flex Items Along the Main Axis - CSS: Cascading Style Sheets
in the live example below for instance i have two paragraph elements that contain a string of text.
...for example, if i have a 500 pixel-wide container, flex-direction is row, and i have three flex items each 100 pixels wide, then i have 200 pixels of positive free space, which could be distributed between the items if i wanted them to fill the container.
... in the following examples i am working with flex-direction set to row, therefore the size of items will always come from their width.
...And 12 more matches
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 example, this css targets printers: @media print { ...
...this example applies styles when the user's primary input mechanism (such as a mouse) can hover over elements: @media (hover: hover) { ...
...And 12 more matches
Value definition syntax - CSS: Cascading Style Sheets
in addition to this syntax, the set of valid values can be further restricted by semantic constraints (for example, for a number to be strictly positive).
...for example: auto, smaller or ease-in.
... bold [ thin && <length> ] this example matches the following values: bold thin 2vh bold 0 thin bold thin 3.5em but not: thin bold 3em, as bold is juxtaposed with the component defined by the brackets, it must appear before it.
...And 12 more matches
Applying color to HTML elements using CSS - HTML: Hypertext Markup Language
for example, if the box's text is being rendered right-to-left, then the border-inline-start-color is applied to the right side of the border.
... as an example, you can represent the opaque color bright blue as "#0000ff" or "#00f".
... for example, a bright red that's 50% opaque can be represented as rgb(255, 0, 0, 0.5) or rgb(100%, 0, 0, 50%).
...And 12 more matches
Using the application cache - HTML: Hypertext Markup Language
how the application cache works enabling the application cache to enable the application cache for an application, include the manifest attribute in the <html> element: <html manifest="/example.appcache"> … </html> the manifest attribute references a url for a cache manifest file: a text file that lists urls that browsers should cache for your application.
...the notification bar displays a message such as: this website (example.com) is asking to store data on your computer for offline use.
... example 1: a simple cache manifest file the following is a simple cache manifest file, example.appcache, for an imaginary web site at www.example.com.
...And 12 more matches
MIME types (IANA media types) - HTTP
for example, for the mime type text, the subtype might be plain (plain text), html (html source code), or calendar (for icalendar/.ics) files.
... an optional parameter can be added to provide additional details: type/subtype;parameter=value for example, for any mime type whose main type is text, the optional charset parameter can be used to specify the character set used for the characters in the data.
...for example, multipart mime types are used when attaching multiple files to an email.
...And 12 more matches
cfx - Archive of obsolete content
cfx usage is: cfx [options] command [command-specific options] "options" are global options applicable to the tool itself or to all commands (for example --help).
... --binary-args=cmdargs pass extra arguments to the binary being executed (for example, firefox).
... for example, to pass the -jsconsole argument to firefox, which will launch the javascript error console, try the following: cfx run --binary-args -jsconsole to pass multiple arguments, or arguments containing spaces, quote them: cfx run --binary-args '-url "www.mozilla.org" -jsconsole' --extra-packages=extra_packages extra packages to include, specified as a comma-separated list of package names.
...And 11 more matches
Adding Event Handlers - Archive of obsolete content
our find files example let's add a script to the find file dialog.
...for example, you may use urls of the following form: <script src="findfile.js"/> <script src="chrome://findfiles/content/help.js"/> <script src="http://www.example.com/js/items.js"/> this tutorial does not attempt to describe how to use javascript (except as related to event handling) as this is a fairly large topic and there are plenty of other resources that are available for this.
... each event has a name, for example, 'mousemove' is the name of the event that is triggered when the user moves the mouse over a ui element.
...And 11 more matches
Commands - Archive of obsolete content
a simple way of using commands is as follows: example: simple command example 1 : source view <command id="cmd_openhelp" oncommand="alert('help!');"/> <button label="help" command="cmd_openhelp"/> in this example, instead of placing the oncommand attribute on the button, we instead place it on a command element.
... example: toggling command disabled example 2 : source view <command id="cmd_openhelp" oncommand="alert('help');"/> <button label="help" command="cmd_openhelp"/> <button label="more help" command="cmd_openhelp"/> <button label="disable" oncommand="document.getelementbyid('cmd_openhelp').setattribute('disabled','true');"/> <button label="enable" oncommand="document.getelementbyid('cmd_op...
...enhelp').removeattribute('disabled');"/> in this example, both buttons use the same command.
...And 11 more matches
Advanced styling effects - Learn web development
you can find the examples in this section at box-shadow.html (see the source code too).
... a simple box shadow let's look at a simple example to get things started.
...0,0,0,0), rgba(0,0,0,0.25)); } .multiple { box-shadow: 1px 1px 1px black, 2px 2px 1px black, 3px 3px 1px red, 4px 4px 1px red, 5px 5px 1px black, 6px 6px 1px black; } now we get this result: we've done something fun here by creating a raised box with multiple coloured layers, but you could use it in any way you want, for example to create a more realistic look with shadows based on multiple light sources.
...And 11 more matches
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.
... when you move on to learn about css layout in more detail, you will encounter flex, and various other inner values that your boxes can have, for example grid.
... examples of different display types let's move on and have a look at some examples.
...And 11 more matches
Web fonts - Learn web development
for example, most modern browsers support woff/woff2 (web open font format versions 1 and 2), the most efficient format around, but older versions of ie only support eot (embedded open type) fonts, and you might need to include an svg version of the font to support older versions of iphone and android browsers.
...this video provides a nice walkthrough: active learning: a web font example with this in mind, let's build up a basic web font example from first principles.
... it is difficult to demonstrate this using an embedded live example, so instead, we would like you to follow the steps detailed in the below sections, to get an idea of the process.
...And 11 more matches
Advanced text formatting - Learn web development
let's look at an example of a set of terms and definitions: soliloquy in drama, where a character speaks to themselves, representing their inner thoughts or feelings and in the process relaying them to the audience (but not to other characters.) monologue in drama, where a character speaks their thoughts out loud to share them with the audience and any other characters present.
...let's finish marking up our example: <dl> <dt>soliloquy</dt> <dd>in drama, where a character speaks to themselves, representing their inner thoughts or feelings and in the process relaying them to the audience (but not to other characters.)</dd> <dt>monologue</dt> <dd>in drama, where a character speaks their thoughts out loud to share them with the audience and any other characters present.</dd> <dt>aside</dt> <dd>in ...
... note that it is permitted to have a single term with multiple descriptions, for example: <dl> <dt>aside</dt> <dd>in drama, where a character shares a comment only with the audience for humorous or dramatic effect.
...And 11 more matches
Server-side web frameworks - Learn web development
the example below shows how this works in the django (python) web framework.
...for example, the flask (python) web framework adds routes to view functions using a decorator.
... urlpatterns = [ url(r'^$', views.index), # example: /best/myteamname/5/ url(r'^best/(?p<team_name>\w.+?)/(?p<team_number>[0-9]+)/$', views.best), ] make it easy to access data in the request data can be encoded in an http request in a number of ways.
...And 11 more matches
sslfnc.html
if you are performing operations that require write permission, for example s/mime operations such as adding a certificate, use nss_initreadwrite instead.
...applications may disable any cipher suites that they don't know about (for example, that they cannot present to the user via a gui).
...for example, if a client that has called nss_setdomesticpolicy establishes an ssl connection with a server for which some cipher suites are either not permitted or not enabled (such as an international version of netscape server software), ssl uses the strongest cipher suites supported by the server that are also supported by the client.
...And 11 more matches
A Web PKI x509 certificate primer
the attributes of the certificates in the verification path have valid parameters for that verification (for example the validity period of all the certificates are valid for the time the verification is being done) revocation checks are considered ok for that particular validation.
...this allows for a certificate to be used for more than one fqdn, for example you can have a certificate that is valid for both a.example.com and b.example.com basic constraints this allows certificates to be asserted as issuing certificates (it is mandatory for ca certificates).
...examples of key usages are: digitalsignature, keyencipherment, dataencipherment, keycertsign, and crlsign.
...And 11 more matches
Accessing the Windows Registry Using XPCOM
the examples in this document are all written in javascript using xpcom.
... a simple example here's a simple example showing how to read your windows productid: var wrk = components.classes["@mozilla.org/windows-registry-key;1"] .createinstance(components.interfaces.nsiwindowsregkey); wrk.open(wrk.root_key_local_machine, "software\\microsoft\\windows\\currentversion", wrk.access_read); var id = wrk.readstringvalue("productid"); wrk.close(); this example, whil...
... the desired access rights are specified using a named constant from the interface, in this example access_read.
...And 11 more matches
Standard OS Libraries
example: getcursorpos i wanted to get the mouse cursor position without using a mousemove listener, as this is a high overhead event listener.
...(msdn - getcursorpos) this example was created on windows xp sp2.
... it is a full working example; just copy & paste it to try it out.
...And 11 more matches
How whitespace is handled by HTML, CSS, and in the DOM - Web APIs
take the following minimal example: <!doctype html> <h1> hello world!
... take the following document, for example: <!doctype html> <html> <head> <title>my document</title> </head> <body> <h1>header</h1> <p> paragraph </p> </body> </html> the dom tree for this looks like so: conserving whitespace characters in the dom is useful in many ways, but there are certain places where this makes certain layouts more difficult to implement, and causes problems for developers who want to iterate throug...
...in the earlier example one of the spaces between "hello" and "world!" still exists when the page is rendered in a browser.
...And 11 more matches
Using Fetch - Web APIs
have a look at the following code: fetch('http://example.com/movies.json') .then(response => response.json()) .then(data => console.log(data)); here we are fetching a json file across the network and printing it to the console.
... // example post method implementation: async function postdata(url = '', data = {}) { // default options are marked with * const response = await fetch(url, { method: 'post', // *get, post, put, delete, etc.
... manual, *follow, error referrerpolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url body: json.stringify(data) // body data type must match "content-type" header }); return response.json(); // parses json response into native javascript objects } postdata('https://example.com/answer', { answer: 42 }) .then(data => { console.log(data); // json data parsed by `data.json()` call }); note that mode: "no-cors" only allows a limited set of headers in the request: accept accept-language content-language content-type with a value of application/x-www-form-urlencoded, multipart/form-data, or text/plain sending a request with credentials included to cause...
...And 11 more matches
Pointer events - Web APIs
for example, in the case of a pen, when the pen has physical contact with the digitizer, or at least one button is depressed while hovering.
...for example, a pen that is a down state is considered active because it can produce additional events when the pen is lifted or moved.
...examples of pointer input devices are mouse, pen/stylus, and touch contacts.
...And 11 more matches
WebGL model view projection - Web APIs
for this example, it's easiest to illustrate how clip space works by simply using model coordinate values ranging from (-1,-1,-1) to (1,1,1).
... webglbox example this example will create a custom webglbox object that will draw a 2d box on the screen.
... note: the code for each webglbox example is available in this github repo and is organized by section.
...And 11 more matches
Using CSS gradients - CSS: Cascading Style Sheets
we'll start by introducing linear gradients, then introduce features that are supported in all gradient types using linear gradients as the example, then move on to radial, conic and repeating gradients using linear gradients a linear gradient creates a band of colors that progress in a straight line.
...in this example, the colors share a color stop at the 50% mark, halfway through the gradient: <div class="striped"></div> div { width: 120px; height: 120px; } .striped { background: linear-gradient(to bottom left, cyan 50%, palegoldenrod 50%); } gradient hints by default, the gradient transitions evenly from one color to the next.
...in this example, we've moved the midpoint of the transition from the 50% mark to the 10% mark.
...And 11 more matches
<input type="datetime-local"> - HTML: Hypertext Markup Language
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...when the above value submitted to the server, for example, it will look like partydate=2017-06-01t08:30.
...And 11 more matches
<input type="number"> - HTML: Hypertext Markup Language
WebHTMLElementinputnumber
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...o the attributes commonly supported by all <input> types, inputs of type number support these attributes: attribute description list the id of the <datalist> element that contains the optional pre-defined autocomplete options max the maximum value to accept for this input min the minimum value to accept for this input placeholder an example value to display inside the field when it's empty readonly a boolean attribute indicating whether the value is read-only step a stepping interval to use when using up and down arrows to adjust the value, as well as for validation list the values of the list attribute is the id of a <datalist> element located in the same document.
...And 11 more matches
<input type="url"> - HTML: Hypertext Markup Language
WebHTMLElementinputurl
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... see the section pattern validation for details and an example.
...And 11 more matches
Assertions - JavaScript
for example, /^a/ does not match the "a" in "an a", but does match the first "a" in "an a".
...for example, /t$/ does not match the "t" in "eater", but does match it in "eat".
... examples: /\bm/ matches the "m" in "moon".
...And 11 more matches
Character classes - JavaScript
character classes distinguish kinds of characters such as, for example, distinguishing between letters and digits.
...for example, /.y/ matches "my" and "ay", but not "yes", in "yes make my day".
...for example, /\d/ or /[0-9]/ matches "2" in "b2 is the suite number".
...And 11 more matches
Search Extension Tutorial (Draft) - Archive of obsolete content
while the technical details below are important to understand, a library which encapsulates the appropriate logic is provided along with the example add-on at the end, and should be used where possible.
...the following file, for instance, would change the default keyword search engine, assuming that an engine with the name example engine is installed, as described below: // this is a localizable preference, so it must contain a url which // points at a properties file containing the preference name as a // property.
...pref("browser.search.defaultenginename", "data:text/plain,browser.search.defaultenginename=example engine"); in the case or restartless extensions, the preferences need to be changed manually, and reverted when the extension is disabled if they have not been changed in the meantime.
...And 10 more matches
Creating a Firefox sidebar extension - Archive of obsolete content
example 1.
...it is listed in example 2.
... example 2.
...And 10 more matches
Creating regular expressions for a microsummary generator - Archive of obsolete content
for example, the following regular expression matches--and looks exactly like--the beginning of the url: http:// but some characters are special in regular expressions.
... for example, a period (.) matches any character, and a period followed by an asterisk (.*) matches any combination of characters.
... here's a regular expression that matches our example url: http://cgi\.ebay\.com/ws/ebayisapi\.dll\?viewitem&item=280018439106 it looks almost the same as the url.
...And 10 more matches
OpenClose - Archive of obsolete content
a simple example: somemenu.open = true; this single line of code will open a menu referenced by the variable 'somemenu'.
...here is a complete example which uses a button to open a menu: <button label="open menu" oncommand="document.getelementbyid('editmenu').open = true;"/> <menu id="editmenu" label="edit"> <menupopup> <menuitem label="cut"/> <menuitem label="copy"/> <menuitem label="paste"/> </menupopup> </menu> this technique may be used for both menupopups that use the menu tag, the button tag and the toolbarbutton tag.
...see the popupshown event for an example of how to do this.
...And 10 more matches
Keyboard Shortcuts - Archive of obsolete content
in the example below, the file menu can be selected by pressing alt + f together (or some other key combination for a specific platform).
... example 1 : source view <menubar id="sample-menubar"> <menu id="file-menu" label="file" accesskey="f"> <menupopup id="file-popup"> <menuitem id="close-command" label="close" accesskey="c"/> </menupopup> </menu> </menubar> you can also use the accesskey attribute on buttons.
...for example, pressing ctrl + c to copy text to the clipboard.
...And 10 more matches
RDF Datasources - Archive of obsolete content
some of them are listed here with a few examples.
...using the history list example let's see an example of displaying the history list.
...example 1 : source <tree flex="1" datasources="rdf:history" ref="nc:historyroot"> <treecols> <treecol id="name" label="name" flex="1"/> <treecol id="url" label="url" flex="1"/> <treecol id="date" label="date" flex="1"/> </treecols> <template> <rule> <treechildren> <treeitem uri="rdf:*"> <treerow> <treecell label="rdf:http://home.netscape.com/nc-rdf#name"/> <treecell label="rdf:http://home.netscape.com/nc-rdf#url"/> <treecell label="rdf:http://home.netscape.com/nc-rdf#date"/> </treerow> </treeitem> </treechildren> </rule> </template> </tree> other datasources the tables below list some of the other dat...
...And 10 more matches
Tree Box Objects - Archive of obsolete content
you don't need to call the rowcountchanged() function when a row has simply changed in some way, for example if a cell's label changes.
... note: it is not necessary to run tree.boxobject.queryinterface(components.interfaces.nsitreeboxobject) as shown in the code examples on this page because: let boxobject = tree.treeboxobject; note: is equivalent to: let boxobject = tree.boxobject; boxobject.queryinterface("components.interfaces.nsitreeboxobject"); scrolling the tree you can also scroll the tree using four different methods, similar to those available for listboxes.
...here is a simple example.
...And 10 more matches
The First Install Problem - Archive of obsolete content
the solution is to encourage plugin vendors to write registry keys to the win32 system registry, like the example application.
...example: a piece of software called myapplication might create hkey_local_machine\software\mozillaplugins\@mycompany.com/myapplication,version=5.0.1/ where the plid is something the corporation that makes myapplication (mycompany inc.) determines.
...(note that the file name must still begin with "np", just as it must when the file is loaded from the .\plugins directory.) example: [hkey_local_machine\software\mozillaplugins\@mycompany.com/myapplication,version=5.01] path=c:\mycompany\myapplication\netscape\npmyapp.dll "xptpath" -- string value -- absolute path to xpt module required for scripting plug-in, if applicable example: [hkey_local_machine\software\mozillaplugins\@mycompany.com/myapplication,version=5.01] xptpath=c:\mycompany\m...
...And 10 more matches
What is RSS - Archive of obsolete content
you will not yet be creating your own rss files, but you will be seeing how rss is commonly used and simple example rss files for these common uses.
...for example: <?xml version="1.0"?> <rss version="2.0"> <channel> <title>example news site</title> <description>this is an example news site.</description> <lastbuilddate>wed, 27 jul 2005 00:30:30 -0700</lastbuilddate> <link>http://news.example.com/</link> <item> <title>news flash: i like bread</title> <guid ispermalink="false">4d4a0a12-f188...
...-4c97-908b-eea27213c2fe</guid> <pubdate>wed, 27 jul 2005 00:30:30 -0700</pubdate> <link>http://news.example.com/artcle/554</link> </item> <item> <title>big news today: birds fly</title> <guid ispermalink="false">c4a63f09-b45b-466b-8773-6ff264001ab7</guid> <pubdate>tue, 19 jul 2005 04:32:51 -0700</pubdate> <link>http://news.example.com/artcle/553</link> </item> <item> <title>fire is hot</title> <guid ispermalink="false">c1795324-d5ea-44fa-95b1-b5ce2090d4f1</guid> <pubdate>sun, 15 may 2005 13:02:08 -0700</pubdate> <link>http://news.example.com/artcle/552</link> </item> </channel> </rss> bloggers use rss to provide everyone with a list ...
...And 10 more matches
Using the Right Markup to Invoke Plugins - Archive of obsolete content
here's an example of this kind of usage for ie: <!-- ie only code --> <object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=5,0,0,0" width="366" height="142" id="myflash"> <param name="movie" value="javascript-to-flash.swf" /> <param name="quality" value="high" /> <param name="swliveconnect" value="true" /> </...
...object> in the above example, the classid attribute that goes along with the object element points to a "clsid:" urn followed by the unique identifier of an activex control (in the above example, the string beginning with "d27...").
...here is an example of this usage, once again for the macromedia flash plugin: <object type="application/x-shockwave-flash" data="javascript-to-flash.swf" width="366" height="142" id="myflash"> <param name="movie" value="javascript-to-flash.swf" /> <param name="quality" value="high" /> <param name="swliveconnect" value="true" /> <p>you need flash -- get the latest version from <a href= "http://w...
...And 10 more matches
Pseudo-classes and pseudo-elements - Learn web development
pseudo-classes are keywords that start with a colon: :pseudo-class-name simple pseudo-class example let's look at a simple example.
... if we wanted to make the first paragraph in an article larger and bold, we could add a class to that paragraph and then add css to that class, as shown in the first example below: however, this could be annoying to maintain — what if a new paragraph got added to the top of the document?
...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.
...And 10 more matches
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).
... the following firefox for android keyboard screenshot provides an example: due to the wide variety of phone number formats around the world, this type of field does not enforce any constraints on the value entered by a user (this means it may include letters, etc.).
... see below for an example (taken on firefox for android): note: just because the url is well-formed doesn't necessarily mean that it refers to a location that actually exists!
...And 10 more matches
How to structure a web form - Learn web development
for example, some screen readers such as jaws and nvda will speak the legend's content before speaking the label of each control.
... here is a little example: <form> <fieldset> <legend>fruit juice size</legend> <p> <input type="radio" name="size" id="size_1" value="small"> <label for="size_1">small</label> </p> <p> <input type="radio" name="size" id="size_2" value="medium"> <label for="size_2">medium</label> </p> <p> <input type="radio" name="size" id="size_3" value="large"> <label for="size_3">large</label> </p> </fieldset> </form> note: you can find this example in fieldset-legend.html (see it live also).
... the use case in this example is one of the most important.
...And 10 more matches
Video and audio content - Learn web development
we have provided you with sample audio and video files and example code for your own experimentation, in case you are unable to get hold of your own.
...a really simple example looks like this: <video src="rabbit320.webm" controls> <p>your browser doesn't support html5 video.
... the embedded video will look something like this: you can try the example live here (see also the source code.) using multiple source formats to improve compatibility there's a problem with the above example, which you may have noticed already if you've tried to access the live link above with an older browser like internet explorer or even an older version of safari.
...And 10 more matches
Functions — reusable blocks of code - Learn web development
every time we manipulated a text string, for example: let mytext = 'i am a string'; let newstring = mytext.replace('string', 'sausage'); console.log(newstring); // the replace() string function takes a source string, // and a target string and replaces the source string, // with the target string, and returns the newly formed string or every time we manipulated an array: let myarray = ['i', 'love', 'chocolate', 'frogs']; let madeastring = myarra...
...in our random-canvas-circles.html example (see also the full source code) from our loops article, we included a custom draw() function that looked like this: function draw() { ctx.clearrect(0,0,width,height); for (let i = 0; i < 100; i++) { ctx.beginpath(); ctx.fillstyle = 'rgba(255,0,0,0.5)'; ctx.arc(random(width), random(height), random(50), 0, 2 * math.pi); ctx.fill(); } } this function draws 100 random circles...
...the above function for example calls the random() function three times, which is defined by the following code: function random(number) { return math.floor(math.random()*number); } we needed this function because the browser's built-in math.random() function only generates a random decimal number between 0 and 1.
...And 10 more matches
A first splash into JavaScript - Learn web development
with that in mind, let's look at the example we'll be building up in this article, and review the general process of dissecting it into tangible tasks.
... example — guess the number game in this article we'll show you how to build up the simple game you can see below: top hidden code <!doctype html> <html> <head> <meta charset="utf-8"> <title>number guessing game</title> <style> html { font-family: sans-serif; } body { width: 50%; max-width: 800px; min-width: 480px; margin: 0 auto; } .lastresult { color: white; padding: 3px; } </style> </head> <body> <h1>number guessing game</h1> <p>we have selected a random number between 1 and 100.
... let's now move forward, looking at how we can turn these steps into code, building up the example, and exploring javascript features as we go.
...And 10 more matches
Introduction to the server side - Learn web development
it can also make sites easier to use by storing personal preferences and information — for example reusing stored credit card details to streamline subsequent payments.
... the request includes a url identifying the affected resource, a method that defines the required action (for example to get, delete, or post the resource), and may include additional information encoded in url parameters (the field-value pairs sent via a query string), as post data (data sent by the http post method), or in associated cookies.
... 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).
...And 10 more matches
Client-side tooling overview - Learn web development
often linters can be configured to not only report errors, but also report any violations of a specified style guide that you team might be using (for example code that is using the wrong number of spaces for indentation, or using template literals rather than regular string literals).
... prettier is a very popular example of a code formatter, which we’ll make use of later on in the module.
... bundlers/packagers these are tools that get your code ready for production, for example by “tree-shaking” to make sure only the parts of your code libraries that you are actually using are put into your final production code, or "minifying" to remove all the whitespace in your production code, making it as small as possible before it is uploaded to a server.
...And 10 more matches
IPDL Tutorial
here is a dirt-simple example of how a browser implementor might use ppluginparent.
... the parameters of the recv* methods (const nscstring& pluginpath in the example) are references to temporary objects, so copy them if you need to keep their data around.
...the following artificial example shows how these specifiers are used and how these specifiers change the generated abstract actor classes.
...And 10 more matches
WebRequest.jsm
you can use this api to implement a content policy in an add-on (for example, an ad or script blocker), as you could using nsicontentpolicy.
... some examples of using addlistener().
... see some examples of using filter.
...And 10 more matches
NSS Tools certutil
some smart cards (for example, the litronic card) can store only one key pair.
... some smart cards (for example, the litronic card) do not let you remove a public key you have generated.
... -p dbprefix specify the prefix used on the cert8.db and key3.db files (for example, my_cert8.db and my_key3.db).
...And 10 more matches
nsIHTMLEditor
example: aproperty="font", aattribute="color" avalue if aattribute is not null, the value of the attribute.
... example: aproperty="font", aattribute="color", avalue="0x00ffff" addinsertionlistener() add listener for insertion override.
... boolean breakisvisible( in nsidomnode anode ); parameters anode return value candrag() decides if a drag should be started (for example, based on the current selection and mousepoint).
...And 10 more matches
Aggregate view - Firefox Developer Tools
you can use this to filter the contents of the snapshot that are displayed, so you can quickly see, for example, how many objects of a specific class were allocated.
...for example, in the screenshot above you can see that javascript objects account for most memory, followed by strings.
... the screenshots in this section are taken from a snapshot of the monster example page.
...And 10 more matches
window.postMessage() - Web APIs
this mechanism provides control over where messages are sent; for example, if postmessage() was used to transmit a password, it would be absolutely critical that this argument be a uri whose origin is the same as the intended receiver of the message containing the password, to prevent interception of the password by a malicious third party.
... the dispatched event otherwindow can listen for dispatched messages by executing the following javascript: window.addeventlistener("message", receivemessage, false); function receivemessage(event) { if (event.origin !== "http://example.org:8080") return; // ...
...examples of typical origins are https://example.org (implying port 443), http://example.net (implying port 80), and http://example.com:8080.
...And 10 more matches
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.
... select an area for more information on that area." /> <map id="map1" name="map1"> <area shape="rect" coords="0,0,30,30" href="reference.html" alt="reference" /> <area shape="rect" coords="34,34,100,100" href="media.html" alt="audio visual lab" /> </map> see the <area> element reference page for a live interactive example.
... see also <area> h24: providing text alternatives for the area elements of image maps dialogs should be labeled for any container whose contents act as a dialog box (for example, a modal dialog asking the user to make a choice or respond to an action being taken), give it a descriptive label or name, so that assistive technology users can easily discover what its purpose is.
...And 10 more matches
CSS selectors - CSS: Cascading Style Sheets
syntax: * ns|* *|* example: * will match all the elements of the document.
... syntax: elementname example: input will match any <input> element.
... syntax: .classname example: .index will match any element that has a class of "index".
...And 10 more matches
<input type="file"> - HTML: Hypertext Markup Language
WebHTMLElementinputfile
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...see htmlinputelement.webkitdirectory for additional details and examples.
...And 10 more matches
<input type="search"> - HTML: Hypertext Markup Language
WebHTMLElementinputsearch
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... see the section specifying a pattern for details and an example.
...And 10 more matches
<input type="time"> - HTML: Hypertext Markup Language
WebHTMLElementinputtime
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...you can set a default value for the input by including a valid time in the value attribute when creating the <input> element, like so: <label for="appt-time">choose an appointment time: </label> <input id="appt-time" type="time" name="appt-time" value="13:30"> you can also get and set the date value in javascript using the htmlinputelement.value property, for example: var timecontrol = document.queryselector('input[type="time"]'); timecontrol.value = '15:30'; time value format the value of the time input is always in 24-hour format that includes leading zeros: hh:mm, regardless of the input format, which is likely to be selected based on the user's locale (or by the user agent).
...And 10 more matches
Regular expressions - JavaScript
the last example includes parentheses, which are used as a memory device.
...for example, the pattern /abc/ matches character combinations in strings only when the exact sequence "abc" occurs (all characters together and in that order).
...for example, to match a single "a" followed by zero or more "b"s followed by "c", you'd use the pattern /ab*c/: the * after "b" means "0 or more occurrences of the preceding item." in the string "cbbabbbbcdebc", this pattern will match the substring "abbbbc".
...And 10 more matches
this - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... function f1() { return this; } // in a browser: f1() === window; // true // in node: f1() === globalthis; // true in strict mode, however, if the value of this is not set when entering an execution context, it remains as undefined, as shown in the following example: function f2() { 'use strict'; // see strict mode return this; } f2() === undefined; // true in the second example, this should be undefined, because f2 was called directly and not as a method or property of an object (e.g.
...And 10 more matches
Web audio codec guide - Web media technologies
for example, if the encoder is configured to reduce the sample rate, the sample rate's effect on the output file will be reduced in kind.
... lfe channels are specifically designed to store low-frequency audio data, and are commonly used to provide audio data for subwoofers, for example.
...for example, mp3 supports one lfe channel, while aac supports up to 16.
...And 10 more matches
Namespaces crash course - SVG: Scalable Vector Graphics
for example, svg and mathml might be incorporated directly into an xhtml based scientific document.
...for example, both xhtml and svg have a <title> element.
...here is a short example.
...And 10 more matches
Introduction to using XPath in JavaScript - XPath
numbervalue stringvalue booleanvalue example the following uses the xpath expression count(//p) to obtain the number of <p> elements in an html document: var paragraphcount = document.evaluate( 'count(//p)', document, null, xpathresult.any_type, null ); alert( 'this document contains ' + paragraphcount.numbervalue + ' paragraph elements' ); although javascript allows us to convert the number to a string for display, the xpath interface...
... iterator example var iterator = document.evaluate('//phonenumber', documentnode, null, xpathresult.unordered_node_iterator_type, null ); try { var thisnode = iterator.iteratenext(); while (thisnode) { alert( thisnode.textcontent ); thisnode = iterator.iteratenext(); } } catch (e) { alert( 'error: document tree modified during iteration ' + e ); } snapshots when the specified result type in ...
... snapshots do not change with document mutations, so unlike the iterators, the snapshot does not become invalid, but it may not correspond to the current document, for example, the nodes may have been moved, it might contain nodes that no longer exist, or new nodes could have been added.
...And 10 more matches
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.
... a task example like the following: components.utils.import("resource://gre/modules/task.jsm"); task.spawn(function* () { var response = yield request("login", { username: user, password: password }); if (response.messages) { try { yield publish({ username: user, messages: response.messages }); } catch (e) { self.reporterror("publication failed", e); } } }); can be converted to a pure promise-based equivalent as such: request("login", { username: user, password: password }) .then(response => { if (response.messages) return publish({ username: user, messages: response.messages }); }) .then(null, (e) => { self.reporterror("publication failed", e); }); file io file io in add-ons shou...
...And 9 more matches
Menu - Archive of obsolete content
ArchiveMozillaJetpackUIMenu
the api is fairly comprehensive, so you may want to start by reading through some examples.
...in the future it may be a submenu of the tools menu, for example.
...for example, the items of the page's context menu change depending on what the user clicks: images have a context menu, links have a context menu, and so on.
...And 9 more matches
Multiple Queries - Archive of obsolete content
here is an example using an rdf datasource: <hbox id="photoslist" datasources="template-guide-photos3.rdf" ref="http://www.xulplanet.com/rdf/myphotos"> <template> <queryset> <query> <content uri="?start"/> <member container="?start" child="?photo"/> <triple subject="?photo" predicate="http://purl.org/dc/elements/1.1/title" object="canal"/> ...
...when used together in this example, the results are combined and only three results are shown.
...in this particular example, we could actually have used two rules instead.
...And 9 more matches
Simple Query Syntax - Archive of obsolete content
there are several attributes in the example xul content above that have values prefixed with 'rdf:'.
...for example, the label's value attribute has a value of rdf:http://purl.org/dc/elements/1.1/title'.
...for example: <label value="rdf:http://purl.org/dc/elements/1.1/title http://www.xulplanet.com/rdf/country"/> the 'rdf:' form is really equivalent to the <binding> tag in the full syntax.
...And 9 more matches
Focus and Selection - Archive of obsolete content
here is an example: example 1 : source view <button label="button 1" tabindex="2"/> <button label="button 2" tabindex="1"/> <button label="button 3" tabindex="3"/> the focus event the focus event is used to respond when the focus is given to an element.
...the following example can be used to apply a function to handle a focus event.
... example 2 : source view <script> function displayfocus(){ var elem=document.getelementbyid('sbar'); elem.setattribute('value','enter your phone number.'); } </script> <textbox id="tbox1"/> <textbox id="tbox2" onfocus="displayfocus();"/> <description id="sbar" value=""/> the focus event, when it occurs, will call the displayfocus function.
...And 9 more matches
Trees and Templates - Archive of obsolete content
the following example uses the history datasource: <tree datasources="rdf:history" ref="nc:historybydate" flags="dont-build-content"> as described in the previous section, the tree may use a tree builder for template generation instead of the normal content builder.
...the flags attribute set to the value dont-build-content, as used in the example above, indicates that the tree builder should be used.
...template-built tree example the following example demonstrates a template-built tree, in this case for the file system.
...And 9 more matches
Using Spacers - Archive of obsolete content
(java uses layout managers for example.) xul provides the capability for elements to position and resize automatically.
... our find file example the code to add a spacer is shown below.
...for example, you might want to have the find button resize instead.
...And 9 more matches
The Implementation of the Application Object Model - Archive of obsolete content
examples of these interfaces include nsidomelement, nsidomnode, nsixmlcontent, and nsicontent.
...for example, the traditional bookmarks tree view could contain anything from mail messages to local files to maps of other sites.
...an example of this feature is a downloadable file that describes the user's main bookmarks folder.
...And 9 more matches
Back to the Server: Server-Side JavaScript On The Rise - Archive of obsolete content
in addition, the jaxer “ajax server” (a project i work on at aptana) is an example of ssjs that uses not only spidermonkey, but also embeds the entire firefox browser engine in the application server such that you can do server-side dom manipulation and other ajaxy things server-side that rhino was not built to do.
... let's take a look at various ssjs implementations and some examples of putting them to use.
...the helma web application framework is an example of rhino in use.
...And 9 more matches
XForms Custom Controls - Archive of obsolete content
this is required for all examples here to run!
...for example, you might want to render images that are held inside an instance document or you would like to show a disabled trigger when its bound node becomes irrelevant rather than having it not display (the current default behavior).
...for example, in the mozilla xforms extension we will render a combobox widget when appearance='minimal' on a select1 control.
...And 9 more matches
Organizing your CSS - Learn web development
consistency can be applied in all sorts of ways, such as using the same naming conventions for classes, choosing one method of describing color, or maintaining consistent formatting (for example will you use tabs or spaces to indent your code?
... you may have used a css property in a specific way to get around older browser incompatibilities, for example: .box { background-color: red; /* fallback for older browsers that don't support gradients */ background-image: linear-gradient(to right, #ff0000, #aa0000); } perhaps you followed a tutorial to achieve something, and the css is a little non-obvious.
...} after this section we could define a few utility classes, for example a class that removes the default list style for lists we're going to display as flex items or in some other way.
...And 9 more matches
Grids - Learn web development
you will see an example with a container, which has some child items.
... simple grid example body { width: 90%; max-width: 900px; margin: 2em auto; font: .9em/1.2 arial, helvetica, sans-serif; } .container > div { border-radius: 5px; padding: 10px; background-color: rgb(207,232,220); border: 2px solid rgb(79,185,227); } <div class="container"> <div>one</div> <div>two</div> <div>three</div> <div>four</div> <div>five</div> <div>six</div> <div>seven</div>...
...the fr unit distributes space in proportion, therefore you can give different positive values to your tracks, for example if you change the definition like so: .container { display: grid; grid-template-columns: 2fr 1fr 1fr; } the first track now gets 2fr of the available space and the other two tracks get 1fr, making the first track larger.
...And 9 more matches
Styling lists - Learn web development
a simple list example to begin with, let's look at a simple list example.
...the unstyled example is available on github (check out the source code too.) the html for our list example looks like so: <h2>shopping (unordered) list</h2> <p>paragraph for reference, paragraph for reference, paragraph for reference, paragraph for reference, paragraph for reference, paragraph for reference.</p> <ul> <li>hummus</li> <li>pita</li> <li>green salad</li> <li>halloumi</li> </ul> <h2>recipe (ordered) list</h2> <p>paragraph for reference, paragraph for reference, paragraph for reference, paragraph for reference, paragraph for reference, paragraph for reference.</p> <ol> <li>toast pita, leave...
...ini, lemon juice, salt, garlic, and other ingredients.</dd> <dt>pita</dt> <dd>a soft, slightly leavened flatbread.</dd> <dt>halloumi</dt> <dd>a semi-hard, unripened, brined cheese with a higher-than-usual melting point, usually made from goat/sheep milk.</dd> <dt>green salad</dt> <dd>that green healthy stuff that many of us just use to garnish kebabs.</dd> </dl> if you go to the live example now and investigate the list elements using browser developer tools, you'll notice a couple of styling defaults: the <ul> and <ol> elements have a top and bottom margin of 16px (1em) and a padding-left of 40px (2.5em.) the list items (<li> elements) have no set defaults for spacing.
...And 9 more matches
CSS basics - Learn web development
for example, this css selects paragraph text, setting the color to red: p { color: red; } let's try it out!
...it defines the element(s) to be styled (in this example, <p> elements).
...(in this example, color is a property of the <p> elements.) in css, you choose which properties you want to affect in the rule.
...And 9 more matches
Document and website structure - Learn web development
main content: a big area in the center that contains most of the unique content of a given webpage, for example, the video you want to watch, or the main story you're reading, or the map you want to view, or the news headlines, etc.
...usually, this is contextual to what is contained in the main content (for example on a news article page, the sidebar might contain the author's bio, or links to related articles) but there are also cases where you'll find some recurring elements like a secondary navigation system.
... a "typical website" could be structured something like this: html for structuring content the simple example shown above isn't pretty, but it is perfectly fine for illustrating a typical website layout example.
...And 9 more matches
Test your skills: Links - Learn web development
the second link should be turned into a link you can click to open up an email in the user's default mail application, with the recipient set as "whales@example.com".
... note: the first link in the example has the target="_blank" attribute set on it, so that when you click on it, it opens the page in a new tab.
... this is not strictly best practice, but we've done it here so that the page doesn't open in the embedded <iframe>, getting rid of your example code in the process!
...And 9 more matches
HTML table advanced features and accessibility - Learn web development
</table> as you can infer from the brief example above, the caption is meant to contain a description of the table contents.
...we'd recommend using the <caption> element instead, however, as summary is deprecated by the html5 spec, and can't be read by sighted users (it doesn't appear on the page.) active learning: adding a caption let's try this out, revisiting an example we first met in the previous article.
...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.
...And 9 more matches
Useful string methods - Learn web development
when you create a string, for example by using let string = 'this is my string'; your variable becomes a string object instance, and as a result has a large number of properties and methods available to it.
... let's enter some examples into the browser developer console.
...this is useful for many reasons; for example, you might want to find the lengths of a series of names so you can display them in order of length, or let a user know that a username they have entered into a form field is too long if it is over a certain length.
...And 9 more matches
Working with JSON - Learn web development
"superhuman reflexes" ] }, { "name": "eternal flame", "age": 1000000, "secretidentity": "unknown", "powers": [ "immortality", "heat immunity", "inferno", "teleportation", "interdimensional travel" ] } ] } if we loaded this object into a javascript program, parsed in a variable called superheroes for example, we could then access the data inside it using the same dot/bracket notation we looked at in the javascript object basics article.
... for example: superheroes.hometown superheroes['active'] to access data further down the hierarchy, you simply have to chain the required property names and array indexes together.
... for example, to access the third superpower of the second hero listed in the members list, you'd do this: superheroes['members'][1]['powers'][2] first we have the variable name — superheroes.
...And 9 more matches
Application Translation with Mercurial
in this example, we assume firefox for desktop shall be localized and that the localization branch is aurora.
...this example uses winmerge: download and install it.
...this example uses notepad++.
...And 9 more matches
NSS tools : signtool
for example, a commercial software developer might sign the files that constitute a software product to prove that the files are indeed from a particular company.
... for example, if you are a software developer, you should test your code to make sure it is virus-free before signing it.
...if the certificate authority's certificate isn't already installed in your copy of communicator, you typically install it by clicking the appropriate link on the certificate authority's web site, for example on the page from which you initiated enrollment for your signing certificate.
...And 9 more matches
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.
... initializing standard objects collecting the arguments evaluating a script printing the result exiting the context expose java apis using java apis implementing interfaces adding java objects using javascript objects from java using javascript variables calling javascript functions javascript host objects defining host objects counter example counter's constructors class name dynamic properties defining javascript "methods" adding counter to runscript runscript: a simple embedding about the simplest embedding of rhino possible is the runscript example.
...And 9 more matches
Introduction to XPCOM for the DOM
here is some example code.
...the following example demonstrates this.
...for example, in the previous example, nothing bad will happen if ifooptr is null.
...And 9 more matches
nsICryptoHash
you can, for example, calculate the sha256 hash of a file to determine if it contains the data you think it does.
...see computing the hash of a string for an example of using this method.
...see computing the hash of a file for an example of using this method.
...And 9 more matches
Using the Screen Capture API - Web APIs
example of a window allowing the user to select a display surface to capture you can then use the captured stream, capturestream, for anything that accepts a stream as input.
... the examples below show a few ways to make use of the stream.
... for example, if you specify a width constraint for the video, it's applied by scaling the video after the user selects the area to share.
...And 9 more matches
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.
... if your code uses either of these names, like in the example below : // old method names var gain = context.creategainnode(); var delay = context.createdelaynode(); var js = context.createjavascriptnode(1024); you can simply rename the methods to look like this: // new method names var gain = context.creategain(); var delay = context.createdelay(); var js = context.createscriptprocessor(1024); the semantics of these methods remain the same in the ren...
... for example, if you have code like the below: var osc = context.createoscillator(); osc.noteon(1); osc.noteoff(1.5); var src = context.createbuffersource(); src.notegrainon(1, 0.25); src.noteoff(2); you can simply change it like this in order to port it to the standard audiocontext api: var osc = context.createoscillator(); osc.start(1); osc.stop(1.5); var src = context.createbuffersource(); src.start(...
...And 9 more matches
Accessibility documentation index - Accessibility
4 aria test cases aria, accessibility for each example we test the "expected" results with assistive technologies, for each browser that at supports wai-aria in.
... 8 forms aria, accessibility the following pages provide various techniques for improving the accessibility of web forms: 9 alerts aria, accessibility, forms, web you have a form — a contact form, for example — that you want to put some accessible error checking into.
... 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.
...And 9 more matches
Using CSS animations - CSS: Cascading Style Sheets
letting the browser control the animation sequence lets the browser optimize performance and efficiency by, for example, reducing the update frequency of animations running in tabs that aren't currently visible.
... 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.
... making text slide across the browser window this simple example styles the <p> element so that the text slides in from off the right edge of the browser window.
...And 9 more matches
Aligning Items in a Flex Container - CSS: Cascading Style Sheets
you can take a look at the code of this example below.
... we are making use of cross-axis alignment in the most simple flex example.
... we can use other values to control how the items align: align-items: flex-start align-items: flex-end align-items: center align-items: stretch align-items: baseline in the live example below, the value of align-items is stretch.
...And 9 more matches
CSS grids, logical values, and writing modes - CSS: Cascading Style Sheets
in the example below, i have two paragraphs.
... this is a very simple example of the problem with physical values and properties being used in css.
... css writing modes i’m going to introduce another specification here, that i will be using in my examples: the css writing modes specification.
...And 9 more matches
Realizing common layouts using CSS Grid Layout - CSS: Cascading Style Sheets
we will look at an example using grid-template-areas, a typical 12-column flexible grid system, and also a product listing using auto-placement.
... 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.
... this is a simple example but demonstrates how we can use a grid layout to rearrange our layout for different breakpoints.
...And 9 more matches
list-style-type - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...a, b, c, … z upper-latin is unsupported in ie7 and earlier arabic-indic -moz-arabic-indic example armenian traditional armenian numbering (ayb/ayp, ben/pen, gim/keem… bengali -moz-bengali example cambodian * example is a synonym for khmer cjk-earthly-branch -moz-cjk-earthly-branch example cjk-heavenly-stem -moz-cjk-heavenly-stem example cjk-ideographic identical to trad-chinese-informal e.g.
...And 9 more matches
Audio and video manipulation - Developer guides
having native audio and video in the browser means we can use these data streams with technologies such as <canvas>, webgl or web audio api to modify audio and video directly, for example adding reverb/compression effects to audio, or grayscale/sepia filters to video.
... for example, let's process a video to display it in greyscale.
... for (var i = 0; i < l; i++) { var grey = (frame.data[i * 4 + 0] + frame.data[i * 4 + 1] + frame.data[i * 4 + 2]) / 3; frame.data[i * 4 + 0] = grey; frame.data[i * 4 + 1] = grey; frame.data[i * 4 + 2] = grey; } this.ctx1.putimagedata(frame, 0, 0); return; } }; once the page has loaded you can call processor.doload() result this is a pretty simple example showing how to manipulate video frames using a canvas.
...And 9 more matches
<img>: The Image Embed element - HTML: Hypertext Markup Language
WebHTMLElementimg
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... the above example shows usage of the <img> element: the src attribute is required, and contains the path to the image you want to embed.
...And 9 more matches
<input type="checkbox"> - HTML: Hypertext Markup Language
WebHTMLElementinputcheckbox
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...take the following example: <form> <div> <input type="checkbox" id="subscribenews" name="subscribe" value="newsletter"> <label for="subscribenews">subscribe to newsletter?</label> </div> <div> <button type="submit">subscribe</button> </div> </form> in this example, we've got a name of subscribe, and a value of newsletter.
...And 9 more matches
<input type="image"> - HTML: Hypertext Markup Language
WebHTMLElementinputimage
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... for example, if you have a graphical button that shows an image with an icon and/or image text "login now", you should also set the alt attribute to something like login now.
...And 9 more matches
<input type="month"> - HTML: Hypertext Markup Language
WebHTMLElementinputmonth
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... when the above value is submitted to the server, for example, it will look like bday-month=1978-06.
...And 9 more matches
<link>: The External Resource Link element - HTML: Hypertext Markup Language
WebHTMLElementlink
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... to link an external stylesheet, you'd include a <link> element inside your <head> like this: <link href="main.css" rel="stylesheet"> this simple example provides the path to the stylesheet inside an href attribute, and a rel attribute with a value of stylesheet.
...And 9 more matches
<textarea> - HTML: Hypertext Markup Language
WebHTMLElementtextarea
the html <textarea> element represents a multi-line plain-text editing control, useful when you want to allow users to enter a sizeable amount of free-form text, for example a comment on a review or feedback form.
... the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...And 9 more matches
Closures - JavaScript
lexical scoping consider the following example code: function init() { var name = 'mozilla'; // name is a local variable created by init function displayname() { // displayname() is the inner function, a closure alert(name); // use variable declared in the parent function } displayname(); } init(); init() creates a local variable called name and a function called displayname().
...this is an example of lexical scoping, which describes how a parser resolves variable names when functions are nested.
... closure consider the following code example: function makefunc() { var name = 'mozilla'; function displayname() { alert(name); } return displayname; } var myfunc = makefunc(); myfunc(); running this code has exactly the same effect as the previous example of the init() function above.
...And 9 more matches
Loops and iteration - JavaScript
for example, the idea "go five steps to the east" could be expressed this way as a loop: for (let step = 0; step < 5; step++) { // runs 5 times, with values of step 0 through 4.
... example in the example below, the function contains a for statement that counts the number of selected options in a scrolling list (a <select> element that allows multiple selections).
... example in the following example, the do loop iterates at least once and reiterates until i is no longer less than 5.
...And 9 more matches
eval() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...for example, suppose you have a variable x.
...And 9 more matches
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.
... preparing the example first we need a wasm module!
...And 9 more matches
ContextMenus - Archive of obsolete content
<hbox id="container" align="center" oncontextmenu="..."> <label value="name:"/> <textbox id="name"/> </hbox> in this example, an attempt to open a context menu anywhere inside the hbox will call the event listener attached using the oncontextmenu attribute.
...this might be called while initializing a window during a load event for example.
... in the example, a context menu is attached to a grid.
...And 8 more matches
Filtering - Archive of obsolete content
for example, you wish the user to be able to select a value from a list, and the template results should be filtered based on that value.
...for example, the resulting triple for the netherlands might be: <triple subject="?photo" predicate="http://www.xulplanet.com/rdf/country" object="http://www.daml.org/2001/09/countries/iso#nl"/> this triple is then appended to the query.
...this example only adds one triple, but you could add others, or add <member> elements.
...And 8 more matches
Adding HTML Elements - Archive of obsolete content
here is an example as it might be added to the find file window: <?xml version="1.0"?> <?xml-stylesheet href="chrome://global/skin/" type="text/css"?> <window id="findfile-window" title="find files" orient="horizontal" xmlns:html="http://www.w3.org/1999/xhtml" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> then, you can use html tags as you would normally, keeping in mind ...
...this may be clearer from the examples below.
...some examples of using html elements are shown below.
...And 8 more matches
List Controls - Archive of obsolete content
for example, this list box will have four rows, one for each item.
... example 1 : source view <listbox> <listitem label="butter pecan" /> <listitem label="chocolate chip" /> <listitem label="raspberry ripple" /> <listitem label="squash swirl" /> </listbox> like with the html option element, you can assign a value for each item using the value attribute.
...the following example demonstrates these additional features: example 2 : source view <listbox rows="3"> <listitem label="butter pecan" value="bpecan" /> <listitem label="chocolate chip" value="chocchip" /> <listitem label="raspberry ripple" value="raspripple" /> <listitem label="squash swirl" value="squash" /> </listbox> the example has been changed to display only 3 rows at a time.
...And 8 more matches
Localization - Archive of obsolete content
the codes &lt; and &gt; are examples of entities which can be used to place less than and greater than signs into the text.
...the example below demonstrates the use of an entity in a button.
...(en-us.jar is the default for english.) you might have locale files in multiple languages, for example, us english (en-us) and french (fr).
...And 8 more matches
More Event Handlers - Archive of obsolete content
in the example below, currenttarget is always the vbox, whereas target would be the specific element, either the button or checkbox, that was activated.
... example 1 : source view <vbox oncommand="alert(event.currenttarget.tagname);"> <button label="ok"/> <checkbox label="show images"/> </vbox> stop event propagation once you handle an event, regardless of where in the propagation the event is, you will likely want to stop the event from being sent to further elements, essentially stopping the capturing or bubbling phases from continuing.
...to manually stop event propagation, call the event object's stoppropagation method, as in the following example.
...And 8 more matches
nsIContentPolicy - Archive of obsolete content
this interface can be very useful if you are developing a content-aware plugin (blocking ads or altering the look of content, for example), or if you want to stop or allow user-browsed urls.
... warning: do not block the caller in your implementations of shouldload() or shouldprocess() (for example, by launching a dialog to prompt the user for something).") note: in reality, much of this interface is defined in the nsicontentpolicybase interface, but for now is documented here until someone has time to split things up.
... type_image 3 indicates an image (for example, <img> elements).
...And 8 more matches
Gecko Compatibility Handbook - Archive of obsolete content
- some inline examples were removed because of technical limitations.
... they are actually replaced by ''-(example removed)-'' the goal of this handbook is to help you update websites to work with standards-based browsers and properly detect gecko.
...or use absolute paths in urls such as http://example.com/directory/...
...And 8 more matches
Getting started with CSS - Learn web development
in the text is a <span>span element</span> and also a <a href="http://example.com">link</a>.</p> <p>this is the second paragraph.
... it contains an <em>emphasized</em> element.</p> <ul> <li>item one</li> <li>item two</li> <li>item <em>three</em></li> </ul> </body> </html> note: if you are reading this on a device or an environment where you can't easily create files, then don't worry — live code editors are provided below to allow you to write example code right here in the page.
... changing the default behavior of elements when we look at a well-marked up html document, even something as simple as our example, we can see how the browser is making the html readable by adding some default styling.
...And 8 more matches
What is CSS? - Learn web development
this article explains what css is, with a simple syntax example, and also covers some key terms about the language.
...browsers, like firefox, chrome, or edge , are designed to present documents visually, for example, on a computer screen, projector or printer.
... css can be used for very basic document text styling — for example changing the color and size of headings and links.
...And 8 more matches
How do you upload your files to a web server? - Learn web development
summary if you have built a simple web page (see html basics for an example), you will probably want to put it online, on a web server.
... open the filezilla application; you should see something like this: logging in for this example, we'll suppose that our hosting provider (the service that will host our http web server) is a fictitious company "example hosting provider" whose urls look like this: mypersonalwebsite.examplehostingprovider.net.
... we have just opened an account and received this info from them: congratulations for opening an account at example hosting provider.
...And 8 more matches
From object to iframe — other embedding technologies - Learn web development
for bonus points, you could also try embedding a google map in the example: go to google maps and find a map you like.
...the live editable examples you've been using through this course are implemented using <iframe>s.
... wanted to include the mdn glossary on one of your web pages — you could try something like this: <iframe src="https://udn.realityripple.com/docs/glossary" width="100%" height="500" frameborder="0" allowfullscreen sandbox> <p> <a href="https://udn.realityripple.com/docs/glossary"> fallback link for browsers that don't support iframes </a> </p> </iframe> this example includes the basic essentials needed to use an <iframe>: allowfullscreen if set, the <iframe> is able to be placed in fullscreen mode using the full screen api (somewhat beyond scope for this article.) frameborder if set to 1, this tells the browser to draw a border between this frame and other frames, which is the default behaviour.
...And 8 more matches
Arrays - Learn web development
we'll return to this example later on in the article.
... as in previous articles, let's learn about the real basics of arrays by entering some examples into browser developer console.
...paste the following code into the console: let shopping = ['bread', 'milk', 'cheese', 'hummus', 'noodles']; shopping; in the above example, each element is a string, but in an array we can store various data types — strings, numbers, objects, and even other arrays.
...And 8 more matches
JavaScript object basics - Learn web development
object basics an object is a collection of related data and/or functionality (which usually consists of several variables and functions — which are called properties and methods when they are inside objects.) let's work through an example to understand what they look like.
...while working with this example you should have your developer tools javascript console open and ready to type in some commands.
... it is very common to create an object using an object literal when you want to transfer a series of structured, related data items in some manner, for example sending a request to the server to be put into a database.
...And 8 more matches
Introduction to cross browser testing - Learn web development
as an example, if you want to use cutting edge javascript features in your site, they might not work in older browsers.
...for example, if a site has been designed to look nice on a desktop pc, it will probably look tiny and be hard to read on a mobile device.
... so for example, you might be building an e-commerce site that serves customers in north america.
...And 8 more matches
Introducing a complete toolchain - Learn web development
toolchains and their inherent complexity as with any chain, the more links you have in your toolchain, the more complex and potentially brittle it is — for example it might be more complex to configure, and easier to break.
... for example, we could have included a tool to minimize our svg file sizes during build.
... your toolchain will depend on your own needs, but for this example of a (possible) complete toolchain, the tools that will be installed up front will be: library installation tools — for adding dependencies.
...And 8 more matches
Theme concepts
defining a theme to create a theme (in this example a simple, single image theme): create a folder in a suitable location on your computer.
...for example, we could use this image combined with a complementary background color, to create this effect in the header see details about this theme in the themes example weta_fade.
...you would use an empty or transparent image if, for example, you wanted to tile a centrally justified image, such as to create this effect here you specify the weta image like this: "images": { "theme_frame": "empty.png", "additional_backgrounds": [ "weta_for_tiling.png"] }, and the images tiling with: "properties": { "additional_backgrounds_alignment": [ "top" ], "additional_backgrounds_tiling": [ "repeat" ] }, full details of how to s...
...And 8 more matches
Chrome registration
toolbars, menu bars, progress bars, and window title bars are all examples of elements that are typically part of the chrome.
...if the above example had a packagename of camelcasepackage, you would get an error message similar to "no chrome registered for chrome://camelcasepackage/path/to/files".
...also, the path inside overridden files is relative to the overridden path, not the original one (this can be annoying and/or useful in css files, for example).
...And 8 more matches
How Mozilla's build system works
for example, a data structure defines which compiler to use, how to invoke it, which application features are enabled, and so on.
...for example, it says i want these c++ files compiled or look for additional information in these directories.
...for example, there is a tier for the netscape portable runtime (nspr), one for the javascript engine, one for the core gecko platform, one for the xul app being built, and so on.
...And 8 more matches
Performance best practices for Firefox front-end engineers
javascript code might, for example, change dom node attributes (either directly or by adding or removing classes from elements), and can also add, remove, or delete dom nodes.
... return window.getcomputedstyle(node).display; }); return display == "none"; } see detecting and avoiding synchronous reflow for a more advanced example of getting layout information, and then setting it safely, without causing flushes.
... here’s a simple example, cribbed from this blog post by paul rouget: div1.style.margin = "200px"; // line 1 var height1 = div1.clientheight; // line 2 div2.classlist.add("foobar"); // line 3 var height2 = div2.clientheight; // line 4 dosomething(height1, height2); // line 5 at line 1, we’re setting some style information on a dom node that’s going to result in a reflow - but (at just line 1...
...And 8 more matches
about:memory
single memory report files can also be loaded automatically when about:memory is loaded by appending a file query string, for example: about:memory?file=/home/username/reports.json.gz this is most useful when loading memory reports files obtained from a firefox os device.
...for example: 585 (100.0%) -- preference-service └──585 (100.0%) -- referent ├──493 (84.27%) ── strong └───92 (15.73%) -- weak ├──92 (15.73%) ── alive └───0 (00.00%) ── dead leaf nodes represent actual measurements; the value of each internal node is the sum of all its children.
...for example, preference/referent/weak/dead represents the path to the final leaf node in the example tree above.
...And 8 more matches
NSS Sample Code Sample1
this is an example program that demonstrates how to do key generation and transport between cooperating servers.
... we will add message protection (encryption and macing) examples to this program in the future.
... sample code #include <iostream.h> #include "pk11pub.h" #include "keyhi.h" #include "nss.h" // key management for keys share among multiple hosts // // this example shows how to use nss functions to create and // distribute keys that need to be shared among multiple servers // or hosts.
...And 8 more matches
Embedded Dialog API
an example of this can be found in the mfc embedding testbed application, in the method cmfcembedapp::initializewindowcreator (lxr link accurate at revision 1.20 of that file; search for the method name in later revisions).
...an mfc example is implemented in promptservice.cpp.
... a powerplant example is implemented in promptservice.cpp.
...And 8 more matches
Avoiding leaks in JavaScript XPCOM components
for example, if an object's constructor adds the object to a list that is reachable from a global variable and nothing ever removes it from the list, the object will never be destroyed since it is always reachable from the list.
...if you implement nsiobserver in javascript and register that observer (without using weak references) with a service (for example, with the observer service bug 239833 or with the pref service bug 256822), the service will do exactly what you tell it to do: notify the observer you just created until you unregister the observer.
...see one of the patches in bug 231384 for some examples.
...And 8 more matches
Creating the Component Code
in the subsequent chapters, we can begin to work on the example weblock component functionality itself.
... for example, mozilla_strict_api is a variable that shields you from certain private, non-xpcom headers.
... for example, including nsicomponentmanager.idl without mozilla_strict_api defined will include the following headers, which are not supported across versions (unfrozen): nscomponentmanagerutils.h nscomponentmanagerobsolete.h these variables are picked up by files that do not specify themselves as mozilla_strict_api.
...And 8 more matches
Mozilla internal string guide
for example: void nsfoo::reversecharacters(nsastring& str) { ...
...for example: // when passing a string to a method, use const nsastring& nsfoo::printstring(const nsastring &str); // when getting a string from a method, use nsastring& nsfoo::getstring(nsastring &result); the abstract classes are also sometimes used to store temporary references to objects.
... an example: const nsastring& str = getsomestring(); nsastring::const_iterator start, end; str.beginreading(start); str.endreading(end); constexpr auto valueprefix = u"value="_ns; if (findinreadable(valueprefix, start, end)) { // end now points to the character after the pattern valuestart = end; } checking for memory allocation failure the string classes now use infallible memory allocation,...
...And 8 more matches
nsILoginManager
for example, "http://www.bar.com".
...to not match any form logins (for example when interested in protocol logins only), specify null.
...to not match any protocol logins (for example when interested in form logins only), specify null.
...And 8 more matches
nsIProtocolHandler
if the protocol doesn't need a port (for example, the "about" protocol), this attribute is -1.
... constants constant value description uri_std 0 a standard full uri with authority component and understanding relative uris; this includes http and ftp, for example.
... uri_norelative 1<<0 the protocol doesn't support relative uris (for example, about and javascript).
...And 8 more matches
Using Objective-C from js-ctypes
a simple example is also in standard os libraries page.
... speech synthesis example let's start with the following objective-c code, which invokes the speech synthesis api to say "hello, firefox!".
... class objc_getclass(const char *name); in /usr/include/objc/objc.h, class is defined as an opaque type by the following: typedef struct objc_class *class; in this example, we need the classnsspeechsynthesizer, which is retrieved with the following code: class nsspeechsynthesizer = objc_getclass("nsspeechsynthesizer"); registering a selector selectors can be registered and retrieved with sel_registername function, also declared in /usr/include/objc/runtime.h.
...And 8 more matches
Using the CSS Typed Object Model - Web APIs
let's see how this works by creating our first example, which explores computedstylemap().
... <p> <a href="https://example.com">link</a> </p> <dl id="regurgitation"></dl> we add javascript to grab our unstyled link and return back a definition list of all the default css property values impacting the link using computedstylemap().
... .get() method / custom properties let's update our example to only retrieve a few properties and values.
...And 8 more matches
EventTarget.addEventListener() - Web APIs
for example, an event handler callback that can be used to handle both fullscreenchange and fullscreenerror might look like this: function eventhandler(event) { if (event.type == 'fullscreenchange') { /* handle a full screen toggle */ } else /* fullscreenerror */ { /* handle a full screen toggle error */ } } safely detecting option support in older versions of the dom specification, the thir...
... for example, if you want to check for the passive option: let passivesupported = false; try { const options = { get passive() { // this function will be called when the browser // attempts to access the passive property.
... examples add a simple listener this example demonstrates how to use addeventlistener() to watch for mouse clicks on an element.
...And 8 more matches
MediaDevices.getUserMedia() - Web APIs
that stream can include, for example, a video track (produced by either a hardware or virtual video source such as a camera, video recording device, screen sharing service, and so forth), an audio track (similarly, produced by a physical or virtual audio source like a microphone, a/d converter, or the like), and possibly other track types.
...here's a full example: { audio: true, video: { width: { min: 1024, ideal: 1280, max: 1920 }, height: { min: 576, ideal: 720, max: 1080 } } } an ideal value, when used, has gravity, which means that the browser will try to find the setting (and camera, if you have more than one), with the smallest fitness distance from the ideal values given.
... 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.
...And 8 more matches
WebGL best practices - Web APIs
for example, if you never want to access your shader objects directly again, just delete their handles after attaching them to a program object.
... for example, it is possible for the following to never complete without context loss: sync = glfencesync(gl_sync_gpu_commands_complete, 0); glclientwaitsync(sync, 0, gl_timeout_ignored); webgl doesn't have a swapbuffers call by default, so a flush can help fill the gap, as well.
... for example, within firefox, the only time glgeterror is checked is after allocations (bufferdata, *teximage*, texstorage*) to pick up any gl_out_of_memory errors.
...And 8 more matches
ARIA: button role - Accessibility
<div id="savechanges" tabindex="0" role="button" aria-pressed="false">save</div> the above example creates a simple button which is first in the focus order, though <button> or <input> with type="button" should be used for buttons: <button id="savechanges">save</button> note: if using role="button" instead of the semantic <button> or <input type="button"> elements, you will need to make the element focusable and have to define event handlers for click and keydown events, including the enter and space keys,...
...see the official wai-aria example code.
...in some cases, for example buttons represented by icons, the accessible name may be provided from the aria-label or aria-labelledby attributes.
...And 8 more matches
Keyboard-navigable JavaScript widgets - Accessibility
tabindex="33") yes tabindex value determines where this element is positioned in the tab order: smaller values will position elements earlier in the tab order than larger values (for example, tabindex="7" will be positioned before tabindex="11").
...(for a full description of the keyboard support that is normally expected for typical widgets, see the wai-aria authoring practices.) the example below shows this technique used with a nested menu control.
... example 2: a menu control using tabindex to control keyboard access <ul id="mb1" tabindex="0"> <li id="mb1_menu1" tabindex="-1"> font <ul id="fontmenu" title="font" tabindex="-1"> <li id="sans-serif" tabindex="-1">sans-serif</li> <li id="serif" tabindex="-1">serif</li> <li id="monospace" tabindex="-1">monospace</li> <li id="fantasy" tabindex="-1">fantasy</li> </ul> </li> <li id="mb1_menu2" tabindex="-1"> style <ul id="stylemenu" title="style" tabindex="-1"> <li id="italic" tabindex="-1">italics</li> <li id="...
...And 8 more matches
Basic concepts of flexbox - CSS: Cascading Style Sheets
you can see in the live example below how this looks.
... the live example below has flex-direction set to row-reverse.
... in the live example below try changing the first value to one of the allowable values for flex-direction - row, row-reverse, column or column-reverse, and also change the second to wrap and nowrap.
...And 8 more matches
Mastering Wrapping of Flex Items - CSS: Cascading Style Sheets
in the next example i have ten items all with a flex-basis of 160px and the ability to grow and shrink.
... 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.
...we can compare our wrapped row example above with the css grid version of that layout to see the difference.
...And 8 more matches
Typical use cases of Flexbox - CSS: Cascading Style Sheets
it forms the most simple of flexbox examples, and could be considered the ideal flexbox use case.
... in the below live example we display the items at their natural size and by using justify-content: space-between make equal amounts of space between the items.
... in the live example below try changing flex: auto to flex: 1.
...And 8 more matches
Auto-placement in CSS Grid Layout - CSS: Cascading Style Sheets
der: 2px solid #ffa94d; border-radius: 5px; background-color: #ffd8a8; padding: 1em; color: #d9480f; } .wrapper { display: grid; grid-template-columns: repeat(3, 1fr); grid-gap: 10px; } <div class="wrapper"> <div>one</div> <div>two</div> <div>three</div> <div>four</div> <div>five</div> </div> default rules for auto-placement as you can see with the above example, if you create a grid all child items will lay themselves out one into each grid cell.
...to cause all created rows to be 100 pixels tall for example you would use: * {box-sizing: border-box;} .wrapper { border: 2px solid #f76707; border-radius: 5px; background-color: #fff4e6; } .wrapper > div { border: 2px solid #ffa94d; border-radius: 5px; background-color: #ffd8a8; padding: 1em; color: #d9480f; } <div class="wrapper"> <div>one</div> <div>two</div> <div>three</div> <div>four</div> <...
... in this next example i have created a grid with three row tracks of 200 pixels height.
...And 8 more matches
Subgrid - CSS: Cascading Style Sheets
for example, if you use grid-template-columns: subgrid and the nested grid spans three column tracks of the parent, the nested grid will have three column tracks of the same size as the parent grid.
... subgrid for columns in the example below i have a grid layout with nine 1fr column tracks and four rows that are a minimum of 100px tall.
... the rows in this example are not a subgrid and so behave as a nested grid does normally.
...And 8 more matches
Basic Shapes - CSS: Cascading Style Sheets
we will cover these in the examples below.
... .shape { shape-outside: circle(50%) margin-box; } you can therefore change this in order that your shape uses the different parts of the box model, for example to use the border.
...we will see this in the following examples of basic shapes.
...And 8 more matches
Visual formatting model - CSS: Cascading Style Sheets
user agents can change the layout of the page when the viewport size changes — for example, if you resize your window, or change the orientation of a mobile device.
... some elements may generate additional boxes in addition to the principal box, for example display: list-item generates more than one box (e.g.
...this situation happens when, for example, you declare display: flex on a parent element, and directly inside there is a run of text not contained in another element.
...And 8 more matches
Getting Started - Developer guides
this article guides you through the ajax basics and gives you some simple hands-on examples to get you started.
...for a more realistic example, see step 3 of this article.
...}; next, after declaring what happens when you receive the response, you need to actually make the request, by calling the open() and send() methods of the http request object, like this: httprequest.open('get', 'http://www.example.org/some.file', true); httprequest.send(); the first parameter of the call to open() is the http request method – get, post, head, or another method supported by your server.
...And 8 more matches
<audio>: The Embed Audio element - HTML: Hypertext Markup Language
WebHTMLElementaudio
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... the above example shows simple usage of the <audio> element.
...And 8 more matches
<input type="date"> - HTML: Hypertext Markup Language
WebHTMLElementinputdate
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...for example: var datecontrol = document.queryselector('input[type="date"]'); datecontrol.value = '2017-06-01'; console.log(datecontrol.value); // prints "2017-06-01" console.log(datecontrol.valueasnumber); // prints 1496275200000, a unix timestamp this code finds the first <input> element whose type is date, and sets its value to 2017-06-01 (june 1st, 2017).
...And 8 more matches
<input type="week"> - HTML: Hypertext Markup Language
WebHTMLElementinputweek
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...when the above value is submitted to the server, for example, browsers may display it as week 01, 2017, but the submitted value will always look like week=2017-w01.
...And 8 more matches
<video>: The Video Embed element - HTML: Hypertext Markup Language
WebHTMLElementvideo
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... the above example shows simple usage of the <video> element.
...And 8 more matches
HTML documentation index - HTML: Hypertext Markup Language
WebHTMLIndex
for example, it can be used to hide elements of the page that can't be used until the login process has been completed.
...this attribute and the <style> element have mainly the purpose of allowing for quick styling, for example for testing purposes.
... 70 <big>: the bigger text element element, html, obsolete, reference, web the obsolete html big element (<big>) renders the enclosed text at a font size one level larger than the surrounding text (medium becomes large, for example).
...And 8 more matches
Browser detection using the user agent - HTTP
an example of feature detection is as follows.
...for example, in the above code snippets, using lookbehind in short-regexp notation (e.g.
...thus, in the above example, you would use new regexp("(?<=look_behind_stuff)"); instead of /(?<=look_behind_stuff)/, even in the lookbehind supported section of your code.
...And 8 more matches
Using HTTP cookies - HTTP
WebHTTPCookies
typically, it's used to tell if two requests came from the same browser — keeping a user logged-in, for example.
... get /sample_page.html http/2.0 host: www.example.org cookie: yummy_cookie=choco; tasty_cookie=strawberry note: here's how to use the set-cookie header in various server-side applications: php node.js python ruby on rails define the lifetime of a cookie the lifetime of a cookie can be defined in two ways: session cookies are deleted when the current session ends.
... for example: set-cookie: id=a3fwa; expires=wed, 31 oct 2021 07:28:00 gmt; note: when an expires date is set, the time and date set is relative to the client the cookie is being set on, not the server.
...And 8 more matches
Control flow and error handling - JavaScript
the block is delimited by a pair of curly brackets: { statement_1; statement_2; ⋮ statement_n; } example block statements are commonly used with control flow statements (if, for, while).
...for example: var x = 1; { var x = 2; } console.log(x); // outputs 2 this outputs 2 because the var x statement within the block is in the same scope as the var x statement before the block.
... for example, do not write code like this: // prone to being misread as "x == y" if (x = y) { /* statements here */ } if you need to use an assignment in a conditional expression, a common practice is to put additional parentheses around the assignment, like this: if ((x = y)) { /* statements here */ } falsy values the following values evaluate to false (also known as falsy values): false undef...
...And 8 more matches
Function.prototype.apply() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...with apply, you can also use an array literal, for example, func.apply(this, ['eat', 'bananas']), or an array object, for example, func.apply(this, new array('eat', 'bananas')).
...And 8 more matches
Promise - JavaScript
these methods also return a newly generated promise object, which can optionally be used for chaining; for example, like this: const mypromise = (new promise(myexecutorfunc)) .then(handlefulfilleda,handlerejecteda) .then(handlefulfilledb,handlerejectedb) .then(handlefulfilledc,handlerejectedc); // or, perhaps better ...
...(see throw -999 in the example, below, for a technique to handle the consequences.) on the other hand, in the absence of an immediate need, it is simpler to leave out error handling until a final .catch() statement.
... 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.
...And 8 more matches
Authoring MathML - MathML
it's recommended to convert your content mathml markup into presentation mathml before publishing it, for example with the help of the ctop.xsl stylesheet.
...for example the following function verifies the mathml support by testing the mspace element (you may replace mspace with mpadded): function hasmathmlsupport() { var div = document.createelement("div"), box; div.innerhtml = "<math><mspace height='23px' width='77px'/></math>"; document.body.appendchild(div); box = div.firstchild.firstchild.getboundingclientrect(); document.body.removechild(div); ...
...for example, here is a minimal stylesheet to use latin modern for the text and latin modern math for the mathematics: @namespace url('http://www.w3.org/1999/xhtml'); @namespace m url('http://www.w3.org/1998/math/mathml'); body, m|mtext { font-family: latin modern; } m|math { font-family: latin modern math; } you can then use the @font-face rule as usual to provide woff fallback for latin modern an...
...And 8 more matches
Web video codec guide - Web media technologies
in the example image above, note how the sky has bands of different shades of blue, instead of being a consistent gradient as the sky color changes toward the horizon.
... mosquito noise artifacts are most commonly found in mpeg video, but can occur whenever a discrete cosine transform (dct) algorithm is used; this includes, for example, jpeg still images.
... for example, level av1 level 2.0 offers a maximum frame width of 2048 pixels and a maximum height of 1152 pixels, but its maximum frame size in pixels is 147,456, so you can't actually have a 2048x1152 video at level 2.0.
...And 8 more matches
Structural overview of progressive web apps - Progressive web apps (PWAs)
the most popular approach is the app shell concept, which mixes ssr and csr in exactly the way described above, and in addition follows the "offline first" methodology which we will explain in detail in upcoming articles and use in our example application.
...for example, an offline mode with the help of service workers is just an extra trait that makes the website experience better, but it's still perfectly usable without it.
...if you want to perform an operation on the data (for example, adding a filter to a video), you no longer need to wait for all of it to be downloaded and converted to a blob (or whatever).
...And 8 more matches
Paths - SVG: Scalable Vector Graphics
WebSVGTutorialPaths
each of the commands is instantiated (for example, creating a class, naming and locating it) by a specific letter.
...for example: m x y (or) m dx dy in the following example there's only a point at (10,10).
...for example: <svg width="200" height="200" xmlns="http://www.w3.org/2000/svg"> <path d="m10 10"/> <!-- points --> <circle cx="10" cy="10" r="2" fill="red"/> </svg> there are three commands that draw lines.
...And 8 more matches
context-menu - Archive of obsolete content
for example, if your add-on needs to add a context menu item whenever the user visits a certain page, don't create the item when that page loads, and don't remove it when the page unloads.
... for example, a good use of the menu would be to show an "edit image" item when the user right-clicks an image in the page.
...for example: var context = require("sdk/context-menu").selectorcontext("img"); mymenuitem.context.add(context); mymenuitem.context.remove(context); when a menu item is bound to more than one context, it appears in the menu when all of those contexts occur.
...And 7 more matches
Bootstrapped extensions - Archive of obsolete content
there are several scenarios in which the startup() function may be called; for example: when the extension is first installed, assuming that it's both compatible with the application and is enabled.
... some examples of when the shutdown() function may be called: when the extension is uninstalled, if it's currently enabled.
... not all chrome.manifest instructions are supported in bootstrapped add-ons, for example you still cannot register xul overlays from a bootstrapped add-on.
...And 7 more matches
MCD, Mission Control Desktop, AKA AutoConfig - Archive of obsolete content
abstract this document is a concrete example of a centralized auto-configuration of mozilla apps, that are; firefox, thunderbird, mozilla suite 1.x.x, seamonkey and for the record, old netscape 4.x.
... file location (not tested since 2012 ...) in thunderbird , firefox, the javascript preference file that calls the centralized preference file is located in $install_dir_moz_app/defaults/pref, for example in thunderbird this would be repectively for windows/linux: c:\program files\mozilla thunderbird\defaults\pref /usr/lib/thunderbird/default/pref ( it used to be in /usr/lib/thunderbird-version#/default/pref as in /usr/lib/thunderbird-5/default/pref ) for the record/history purpose ...
... that prefcalls.js is now archive in omni.jar file located at the root of the mozilla apps installation, example of tb5: # jar -tvf /usr/lib/thunderbird/omni.jar | grep prefcalls.js 7499 sat nov 05 09:21:34 cet 2011 defaults/autoconfig/prefcalls.js traditionally (previous apps versions) is was in mozilla_home/default/autoconfig/prefcalls.js.
...And 7 more matches
Reading from Files - Archive of obsolete content
var file = io.getfile("home", "sample.txt"); var stream = io.newinputstream(file, "text"); this example first retrieves a file object using nsiscriptableio.getfile().
...the newinputstream method takes two arguments in this example.
...var file = io.getfile("home", "sample.txt"); var stream = io.newinputstream(file, "text"); var str = stream.readstring(20); stream.close(); in this example, a text input stream is created for the file 'sample.txt'.
...And 7 more matches
Adding Properties to XBL-defined Elements - Archive of obsolete content
the example below creates a button which generates and stores a random number.
...in this example, no content has been placed inside either the xul box or its definition in xbl, which is perfectly valid.
... this example isn't quite correct because the field is not assigned a default value.
...And 7 more matches
Advanced Rules - Archive of obsolete content
in the example above, the value of the container attribute is the variable 'list'.
...of course, the example above doesn't have any content.
...for example, a triple exists between a bookmark and its url.
...And 7 more matches
Custom Tree Views - Archive of obsolete content
the following example shows this: <tree id="my-tree" flex="1"> <treecols> <treecol id="namecol" label="name" flex="1"/> <treecol id="datecol" label="date" flex="1"/> </treecols> <treechildren/> </tree> to assign data to be displayed in the tree, the view object needs to be created which is used to indicate the value of each cell, the total number of rows plus other optional information.
... here is an example of defining such as object, which can be called whatever you want: //moz 1.8 var treeview = { rowcount : 10000, getcelltext : function(row,column){ if (column.id == "namecol") return "row "+row; else return "february 18"; }, settree: function(treebox){ this.treebox = treebox; }, iscontainer: function(row){ return false; }, isseparator: function(row){ return fa...
...lse; }, issorted: function(){ return false; }, getlevel: function(row){ return 0; }, getimagesrc: function(row,col){ return null; }, getrowproperties: function(row,props){}, getcellproperties: function(row,col,props){}, getcolumnproperties: function(colid,col,props){} }; the functions in the example not described above do not need to perform any action, but they must be implemented as the tree calls them to gather additional information.
...And 7 more matches
Manipulating Lists - Archive of obsolete content
here is an example: example 1 : source view <script> function additem(){ document.getelementbyid('thelist').appenditem("thursday", "thu"); } </script> <listbox id="thelist"/> <button label="add" oncommand="additem();"/> the appenditem() takes two arguments, the label, in this case 'thursday', and a value 'thu'.
...the new item is inserted at this index, so, in the example, the new item will be added at position 3 while the item previously at that position will now be at position 4.
...for example, to add a new item to a menulist, you can use the same syntax as for a listbox.
...And 7 more matches
Modifying a XUL Interface - Archive of obsolete content
for example, the following will add a button to a xul window: example 1 : source view <script> function addbutton(){ var abox = document.getelementbyid("abox"); var button = document.createelement("button"); button.setattribute("label","a new button"); abox.appendchild(button); } </script> <box id="abox" width="200"> <button label="add" oncommand="addbutton();"/> </box> this example has two pa...
...here is an example: example 2 : source view <hbox height="400"> <button label="copy" oncommand="this.parentnode.appendchild(this.nextsibling.clonenode(true));"/> <vbox> <button label="first"/> <button label="second"/> </vbox> </hbox> when the copy button is pressed..
...label and value properties examples here is a simple example which changes the label on a button: example 3 : source view <button label="hello" oncommand="this.label = 'goodbye';"/> when the button is pressed, the label is changed.
...And 7 more matches
More Menu Features - Archive of obsolete content
the example below creates a simple submenu inside the file menu example 1 : source view <toolbox flex="1"> <menubar id="sample-menubar"> <menu id="file-menu" label="file"> <menupopup id="file-popup"> <menu id="new-menu" label="new"> <menupopup id="new-popup"> <menuitem label="window"/> <menuitem label="message"/> </menupopup> </menu>...
... <menuitem label="open"/> <menuitem label="save"/> <menuseparator/> <menuitem label="exit"/> </menupopup> </menu> </menubar> </toolbox> adding a menu to our find files example let's add a menu to the find files dialog.
...this is similar to the example above.
...And 7 more matches
Popup Menus - Archive of obsolete content
a good example is the drop down menu that appears when you click on the little down arrows next to the back and forward buttons in a browser window.
...on the macintosh for example, the user can either press the control key and click the mouse button, or hold the mouse button down for a moment.
... also note that it is possible to open context menus without using the mouse, for example by pressing the menu key on a keyboard.
...And 7 more matches
XPCOM Interfaces - Archive of obsolete content
for example, if we wanted to create a mail application, we would need to write scripts which would connect to mail servers to retrieve and send mail.
...for example, there is a component for each menu, button and element.
... let's take an example of a file component.
...And 7 more matches
XUL Structure - Archive of obsolete content
for instance, an http url does not have any special privileges, and an error will occur if a web page tries, for example, to read a local file.
...for example, while the form controls on an html page are accessible via the document.forms property, this property isn't available for xul documents, since xul doesn't have forms in the html sense.
...for example, the messenger component has descriptions of the mail messages list window, the composition window and the address book dialogs.
...And 7 more matches
Writing Skinnable XUL and CSS - Archive of obsolete content
for example, the skin for the navigator package should contain a file called navigator.css that determines the default look of all xul windows posed from this package.
...for example, the sidebar should not import the global skin, since it could appear in messenger and in navigator (which could have two completely different color schemes).
...below are examples for each case.
...And 7 more matches
XUL accessibility guidelines - Archive of obsolete content
the firefox "bookmarks manager" provides an example of how to make trees more accessible.
...the arrowscrollbox, for example, is a non-focusable element and cannot be scrolled using a keyboard.
... the following example shows a javascript function that can be called before destroying an element to check for focus and move it if necessary.
...And 7 more matches
Common causes of memory leaks in extensions - Extensions
for example, in xul overlay code: var contentwindows = []; function inbrowserxuloverlay(contentwindow) { // forgetting or failing to pop the content window thing again contentwindows.push(contentwindow); } this will keep the content window compartments alive until the browser window is closed.
... for example: var windows = []; function injavascriptcodemodule(window) { // forgetting or failing to pop the window again windows.push(window); } both of these cases can happen if you forget to declare local variables with var or let, which means they end up belonging to the global scope.
... for example: function implicitdeclarationleak(window) { // implicit variable declaration in the js global, holding a strong ref to the document doc = window.document; } implicitly declared variables can be avoided by using ecmascript 5's strict mode.
...And 7 more matches
Debugging CSS - Learn web development
for example in firefox there are some excellent tools for working visually with css layout, allowing you to inspect and edit grid layouts, flexbox, and shapes.
...in order to do so i'll be using an example file.
...in our example the margin shorthand is used.
...And 7 more matches
Multiple-column layout - Learn web development
a basic example we will now explore how to use multiple-column layout, often referred to as multicol.
...at the bottom of the section you can see a live example of what the final code should look like.
... column-count example body { width: 90%; max-width: 900px; margin: 2em auto; font: .9em/1.2 arial, helvetica, sans-serif; } <div class="container"> <h1>simple multicol example</h1> <p> lorem ipsum dolor sit amet, consectetur adipiscing elit.
...And 7 more matches
Styling links - Learn web development
focus: a link when it has been focused (for example moved to by a keyboard user using the tab key or similar, or programmatically focused using htmlelement.focus()) — this is styled using the :focus pseudo class.
... 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.
...And 7 more matches
Other form controls - Learn web development
note: you can find a slightly more interesting example of text area usage in the example we put together in the first article of the series (see the source code also).
... block and inline: experimental values that allow resizing in the block or inline direction only (this varies depending on the directionality of your text; read handling different text directions if you want to find out more.) play with the interactive example at the top of the resize reference page for a demonstration of how these work.
... note: you can find examples of all the drop-down box types on github at drop-down-content.html (see it live also).
...And 7 more matches
Website security - Learn web development
other attacks can be mitigated through your web server configuration, for example by enabling https.
... for example, consider a site search function where the search terms are encoded as url parameters, and these terms are displayed along with the results.
... for example, a discussion board that accepts comments that contain unmodified html could store a malicious script from an attacker.
...And 7 more matches
Introduction to automated testing - Learn web development
for example, this could be every time you save a file, or at some other point.
... for example, let's first create a test directory to allow us to play without fear of breaking anything.
...for example, try adding the following to the bottom of your gulpfile.js: gulp.task('watch', function(){ gulp.watch('src/*.html', ['html']); gulp.watch('src/*.css', ['css']); gulp.watch('src/*.js', ['js']); }); now try entering the gulp watch command into your terminal.
...And 7 more matches
SVG Guidelines
for example, consider an image of a path with a gradient fill.
...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.
...And 7 more matches
Script security
for example, the objects associated with a document served from https://example.org/ can access each other, and they can also access objects served from https://example.org/foo.
...for example, code served from https://example.org/ trying to access objects from https://somewhere-else.org/ will have restricted access.
...an example of this scope is chrome-privileged javascript accessing web content.
...And 7 more matches
Sqlite.jsm
here is an example: components.utils.import("resource://gre/modules/sqlite.jsm"); try { const conn = await sqlite.openconnection({ path: "mydatabase.sqlite", sharedmemorycache: false }); // connection is the opened sqlite connection (see below for api).
... examples open, execute, close in this example, we open a connection, execute a simple statement, then close the connection.
... const conn = await sqlite.openconnection({path: "mydb.sqlite"}); const result = await conn.execute("select 1"); await conn.close(); alert("we are done!"); this isn't a terrific example because it doesn't include error handling.
...And 7 more matches
AsyncTestUtils extended framework
mozmill is an example of a testing framework that uses a nested event loop.
...for example, you would do "yield async_move_messages(...);" and be done with it.
...for example, if you pass 3, then 1 <- 2 <- 3 is what the reply chain looks like.
...And 7 more matches
nss tech note5
ck_mechanism_type ciphermech = ckm_des_cbc_pad <big>(for example)</big> choose a slot on which to to do the operation pk11slotinfo* slot = pk11_getbestslot(ciphermech, null); or pk11slotinfo* slot = pk11_getinternalkeyslot(); /* alwys returns internal slot, may not be optimal */ prepare the key if using a raw key /* turn the raw key into a secitem */ secitem keyitem; keyitem.data = /* ptr to an array of key byte...
... ck_mechanism_type digestmech = ckm_md5 <big>(for example)</big> choose a slot on which to to do the operation pk11slotinfo* slot = pk11_getbestslot(digestmech, null); or pk11slotinfo* slot = pk11_getinternalkeyslot(); /* always returns int slot, may not be optimal */ prepare the key if using a raw key /* turn the raw key into a secitem */ secitem keyitem; keyitem.data = /* ptr to an array of key bytes */...
...you can find a list of hmac mechanisms in security/nss/lib/softoken/pkcs11.c - grep for ckf_sn_vr, and choose the mechanisms that contain hmac in the name ck_mechanism_type hmacmech = ckm_md5_hmac; <big>(for example)</big> choose a slot on which to to do the operation pk11slotinfo* slot = pk11_getbestslot(hmacmech, null); or pk11slotinfo* slot = pk11_getinternalkeyslot(); /* always returns int slot, may not be optimal */ prepare the key if using a raw key /* turn the raw key into a secitem */ secitem keyitem; keyitem.type = sibuffer; keyitem.data = /* ...
...And 7 more matches
Using XPCOM Utilities to Make Things Easier
for example: ns_impl_isupports2(classname, interface1, interface2) ns_impl_isupportsn(classname, interface1, ..., interfacen) these macros automatically add the nsisupports entry for you, so you don't need to do something like this: ns_impl_isupports2(classname, interface1, nsisupports) take a close look at the above example.
...for example, ns_decl_nsifoo will declare all of the methods of nsifoo provided that it exists and that nsifoo.h was generated by the xpidl compiler.
...in c++, the string literal "xpcom", for example, consists of 6 consecutive bytes, where `x' is at byte offset zero and a null character is at byte offset 5.
...And 7 more matches
XUL Overlays
MozillaTechXULOverlays
overlays provide a general mechanism for: adding ui for additional components, as described in the example above overriding small pieces of a xul file without having to resupply the whole ui reusing particular pieces of the ui xul files and overlays work together to describe a single master document.
...the installation of a media plug-in, for example, may add new icons and menu items to the interface: in the navigatoroverlay.xul file or in a separate navigatorsspoverlay.xul file (where navigator.xul defines the basic ui for the navigator package), these new plug-in elements would be defined as a collection of elements or subtrees: <menuitem name="super stream player"/> <menupopup name="ss favorites"> <menuitem name="wave" src="mavericks.ss...
...when a component such as the "super stream player" from the examples above is registered there, overlays associated with that component are loaded automatically.
...And 7 more matches
Xray vision
the security machinery in gecko ensures that there's asymmetric access between code at different privilege levels: so for example, content code can't access objects created by chrome code, but chrome code can access objects created by content.
... for example: window.confirm() is a dom api that's supposed to ask the user to confirm an action, and return a boolean depending on whether they clicked "ok" or "cancel".
... so in the example above, chrome code calling the content's window.confirm() would get the original version of confirm(), not the redefined version.
...And 7 more matches
Autoconfiguration in Thunderbird
for more complicated setups, for example when the login name does not appear in the email address, the xml file can also be generated by the isp.
...for example, for the email address fred@example.com , the lookup is performed as (in this order): tb-install-dir/isp/example.com.xml on the harddisk check for autoconfig.example.com look up of "example.com" in the ispdb look up "mx example.com" in dns, and for mx1.mail.hoster.com, look up "hoster.com" in the ispdb try to guess (imap.example.com, smtp.example.com etc.) we may add dns srv records as s...
... how to add support for your domain classification if you are a big isp (> 100,000 users) providing email addresses solely under a few domains like "example.com" and "example.de", you may either submit the configuration to the ispdb or set up a configuration server.
...And 7 more matches
Mozilla
toolbars, menu bars, progress bars, and window title bars are all examples of elements that are typically part of the chrome.
...so for example, on kde is is desirable to fully employ the kde wallet manager, rather than any secondary replacements of kdewallet.
...here is a very simple example of the observer pattern: creating mozsearch plugins firefox 2 uses a simplified form of the opensearch format for storing search plugins.
...And 7 more matches
Initialization and Destruction - Plugins
this chapter ends with initialize and shutdown example, which includes the np_initialize and np_shutdown methods.
...for an example that shows the use of both the np_initialize and np_shutdown methods, see initialize and shutdown example.
... the arguments in the embed element are name-value pairs made up of the attribute name (for example, align) and its value (for example, top).
...And 7 more matches
Index - Firefox Developer Tools
to enable it, open the developer tool settings, and check the "memory" box under "default firefox developer tools": 40 dom allocation example this article describes a very simple web page that we'll use to illustrate some features of the memory tool.
... 43 monster example this article describes a very simple web page that we'll use to illustrate some features of the memory tool.
... 46 network monitor debugging, dev tools, firefox, guide, networking, tools, l10n:priority the network monitor shows you all the network requests firefox makes (for example, when it loads a page, or due to xmlhttprequests), how long each request takes, and details of each request.
...And 7 more matches
console - Web APIs
WebAPIConsole
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.
... console.profile() starts the browser's built-in profiler (for example, the firefox performance tool).
...you can see the resulting profile in the browser's performance tool (for example, the firefox performance tool).
...And 7 more matches
Using files from web applications - Web APIs
example: showing file(s) size the following example shows a possible use of the size property: <!doctype html> <html> <head> <meta charset="utf-8"> <title>file(s) size</title> </head> <body> <form name="uploadform"> <div> <input id="uploadinput" type="file" name="myfiles" multiple> selected files: <span id="filenum">0</span>; total size: <span id="filesize">0</span> </d...
...exactly what part of your content will accept drops may vary depending on the design of your application, but making an element receive drop events is easy: let dropbox; dropbox = document.getelementbyid("dropbox"); dropbox.addeventlistener("dragenter", dragenter, false); dropbox.addeventlistener("dragover", dragover, false); dropbox.addeventlistener("drop", drop, false); in this example, we're turning the element with the id dropbox into our drop zone.
... example: showing thumbnails of user-selected images let's say you're developing the next great photo-sharing website and want to use html to display thumbnail previews of images before the user actually uploads them.
...And 7 more matches
Streams API - Web APIs
for example, the response body returned by a successful fetch request can be exposed as a readablestream, and you can then read it using a reader created with readablestream.getreader(), cancel it with readablestream.cancel(), etc.
... more complicated uses involve creating your own stream using the readablestream() constructor, for example to process data inside a service worker.
... examples we have created a directory of examples to go along with the streams api documentation — see mdn/dom-examples/streams.
...And 7 more matches
Synchronous and asynchronous requests - Web APIs
example: send a file to the console log this is the simplest usage of asynchronous xmlhttprequest.
... example: writing a function to read an external file in some cases, you must read many external files.
... example: using a timeout you can use a timeout to prevent your code from hanging while waiting for a read to finish.
...And 7 more matches
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.
... css grid layout alignment example in this example using grid layout, there is extra space in the grid container after laying out the fixed width tracks on the inline (main) axis.
... flexbox alignment example in this example, three flex items are aligned on the main axis using justify-content and on the cross axis using align-items.
...And 7 more matches
Grid template areas - CSS: Cascading Style Sheets
for example, if i wish to create the layout shown below i can identify four main areas.
... leaving a grid cell empty we have completely filled our grid with areas in this example, leaving no white space.
... spanning multiple cells in our example each of the areas spans multiple grid cells and we achieve this by repeating the name of that grid area multiple times with white space between.
...And 7 more matches
Logical properties for sizing - CSS: Cascading Style Sheets
logical property physical property inline-size width block-size height min-inline-size min-width min-block-size min-height max-inline-size max-width max-block-size max-height width and height example the logical mappings for width and height are inline-size, which sets the length in the inline dimension and block-size, which sets the length in the block dimension.
... in the live example below i have set the writing mode to horizontal-tb.
... change it to vertical-rl and you will see that the first example — which uses width and height — remains the same size in each dimension, despite the text becoming vertical.
...And 7 more matches
background-position - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... (container width - image width) * (position x%) = (x offset value) (container height - image height) * (position y%) = (y offset value) using the x axis for an example, let's say we have an image that is 300px wide and we are using it in a container that is 100px wide, with background-size set to auto: 100px - 300px = -200px (container & image difference) so that with position percentages of -25%, 0%, 50%, 100%, 125%, we get these image-to-container edge offset values: -200px * -25% = 50px -200px * 0% = 0px -200px * 50% = -100px -200px * 100...
...And 7 more matches
Event reference
this article offers a list of events that can be sent; some are standard events defined in official specifications, while others are events used internally by specific browsers; for example, mozilla-specific events are listed so that add-ons can use them to interact with the browser.
... error a websocket connection has been closed with prejudice (some data couldn't be sent for example).
... emptied the media has become empty; for example, this event is sent if the media has already been loaded (or partially loaded), and the load() method is called to reload it.
...And 7 more matches
Audio and Video Delivery - Developer guides
.onload = function() { context.decodeaudiodata(request.response, function(buffer) { source = context.createbuffersource(); source.buffer = buffer; source.connect(context.destination); // auto play source.start(0); // start was previously noteon }); }; request.send(); } catch(e) { alert('web audio api not supported'); } in this example we retrieve an mp3 file via xhr, load it into a source and play it (try it for yourself).
...you can also choose how to make your player responsive — for example you might remove the progress bar under certain conditions.
... a quick example — first set up your audio and custom controls in html: <audio id="my-audio" src="http://jplayer.org/audio/mp3/miaow-01-tempered-song.mp3"></audio> <button id="my-control">play</button> add a bit of javascript to detect events to play and pause the audio: window.onload = function() { var myaudio = document.getelementbyid('my-audio'); var mycontrol = document.getelementbyid('my-control'); function switchstate() { if (myaudio.paused == true) { myaudio.play(); mycontrol.innerhtml = "pause"; } else { myaudio.pause(); mycontrol.innerhtml = "pl...
...And 7 more matches
<input type="radio"> - HTML: Hypertext Markup Language
WebHTMLElementinputradio
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... for example, if your form needs to ask the user for their preferred contact method, you might create three radio buttons, each with the name property set to contact but one with the value email, one with the value phone, and one with the value mail.
...And 7 more matches
<input type="text"> - HTML: Hypertext Markup Language
WebHTMLElementinputtext
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... see specifying a pattern for further details and an example.
...And 7 more matches
<sup>: The Superscript element - HTML: Hypertext Markup Language
WebHTMLElementsup
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... for example, to style the wordmark of a business or product which uses a raised baseline should be done using css (most likely vertical-align) rather than <sup>.
...And 7 more matches
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.
... <div itemscope> <img itemprop="image" src="google-logo.png" alt="google"> </div> when a string value can't be easily read and understood by a person (e.g., a long string of numbers and letters), it can be displayed using the value attribute of the data element, with the more easily-understood-by-a human-version given in the element's contents (which is not part of the structured data - see example below).
...the outer item in this example is a top-level microdata item.
...And 7 more matches
Microformats - HTML: Hypertext Markup Language
for example if they wanted to identify themselves they could use an h-card such as: html example <a class="h-card" href="http://alice.example.com">alice blogger</a> when a parser encounters this data, it will know that this page contains a "card" which describes a person or organization named alice blogger with a url of http://alice.example.com/.
... as in this example, some markup patterns require only a single microformat root class name, which parsers use to find a few generic properties such as name, url, photo.
...for example: h-card describes a person or organization h-entry describes episodic or date stamped online content like a blog post h-feed describes a stream or feed of posts you can find many more vocabularies on the microformats2 wiki.
...And 7 more matches
Redirections in HTTP - HTTP
<head> <meta http-equiv="refresh" content="0; url=https://example.com/"> </head> the content attribute should start with a number indicating how many seconds the browser should wait before redirecting to the given url.
... javascript redirections redirections in javascript are performed by setting a url string to the window.location property, loading the new page: window.location = "https://example.com/"; like html redirections, this can't work on all resources, and obviously, this will only work on clients that execute javascript.
... on the other hand, there are more possibilities: for example, you can trigger the redirect only if some conditions are met.
...And 7 more matches
Numbers and dates - JavaScript
there are caveats to using bigint, however; for example, you can't mix and match bigint and number values in the same operation, and you can't use the math object with bigint values.
...for example, the math object's pi property has the value of pi (3.141...), which you would use in an application as math.pi similarly, standard mathematical functions are methods of math.
...for example, if you want to use the trigonometric function sine, you would write math.sin(1.56) note that all trigonometric methods of math take arguments in radians.
...And 7 more matches
Groups and ranges - JavaScript
for example, /green|red/ matches "green" in "green apple" and "red" in "red apple".
... for example, [abcd] is the same as [a-d].
... for example, [abcd-] and [-abcd] match the "b" in "brisket", the "c" in "chop", and the "-" (hyphen) in "non-profit".
...And 7 more matches
String.prototype.substring() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... if indexstart is greater than indexend, then the effect of substring() is as if the two arguments were swapped; see example below.
...And 7 more matches
The "codecs" parameter in common media types - Web media technologies
for example, bt.2020/bt.2100 color, as used for hdr video, is 09.
...for example, 10-bit bt.2020 is 14.
...for example, the standard coefficients used for bt.709 are indicated using the value 01.
...And 7 more matches
Performance fundamentals - Web Performance
for example, when a user taps the screen, they expect the pixels to change in a certain way.
...for example, paper covered with printed text reflects photons to the user's eyes in some pattern.
...a television probably looks choppy and unrealistic to a hummingbird, for example.
...And 7 more matches
Progressive web app structure - Progressive web apps (PWAs)
the most popular approach is the "app shell" concept, which mixes ssr and csr in exactly the way described above, and in addition follows the "offline first" methodology which we will explain in detail in upcoming articles and use in our example application.
...for example, an offline mode with the help of service workers is just an extra trait that makes the website experience better, but it's still perfectly usable without it.
... the streams api allows developers to have direct access to data streaming from the server — if you want to perform an operation on the data (for example, adding a filter to a video), you no longer need to wait for all of it to be downloaded and converted to a blob (or whatever) — you can start right away.
...And 7 more matches
The building blocks of responsive design - Progressive web apps (PWAs)
let's look at an example.
...this is just a simple grid example, but you can apply this principle to more complex grid layouts as required.
...in the snapshot example, we ended up with slightly different code: x-card:nth-child(1) video, x-card:nth-child(2) img { width: 100%; … } this is because in our case, we do in fact want the video and image to stretch to always fill their containers no matter what — a subtle but important difference from max-width — and therefore always be the same size.
...And 7 more matches
Applying SVG effects to HTML content - SVG: Scalable Vector Graphics
<style>p { mask: url(#my-mask); }</style> in the above example, all paragraphs are masked by an svg <mask> with the id my-mask.
... example: masking for example, you can make a gradient mask for html content using svg and css code similar to the following, inside your html document: <svg height="0"> <mask id="mask-1"> <lineargradient id="gradient-1" y2="1"> <stop stop-color="white" offset="0"/> <stop stop-opacity="0" offset="1"/> </lineargradient> <circle cx="0.25" cy="0.25" r="0.25" id="circle" fill="white"/> <rect x="0.5" y="0.2" width="300" height="100" fill="url(#gradient-1)"/> </mask> </svg> .target { mask: url(#mask-1); } p { width: 300px; border: 1px solid #000; display: inline-block; } note that in the css, the mask is specified using a url to the id #mask-1, which is the id of the svg mask specified below it.
...</p> the above example would be rendered with the mask applied to it.
...And 7 more matches
page-mod - Archive of obsolete content
for example, the following add-on displays an alert whenever the user visits any page hosted at "mozilla.org": var pagemod = require("sdk/page-mod"); pagemod.pagemod({ include: "*.mozilla.org", contentscript: 'window.alert("page matches ruleset");' }); you can modify the document in your script: var pagemod = require("sdk/page-mod"); pagemod.pagemod({ include: "*.mozilla.org", contentscript: 'document.body.innerhtml = ' + ' "<h1>page matches ruleset</h1>";' }); you can supply...
... for example, the following add-on retrieves the html content of specific tags from documents that match the pattern.
... for example, if you maintain a list of workers attached to a page-mod: var workers = []; var pagemod = require("sdk/page-mod").pagemod({ include: ['*'], contentscriptwhen: 'ready', contentscriptfile: data.url('pagemod.js'), onattach: function(worker) { workers.push(worker); } }); you can remove workers when they are no longer valid by listening to detach: var workers = []; function detachw...
...And 6 more matches
ui/button/toggle - Archive of obsolete content
for example, in the screenshots above, firefox uses the small icon when the button is in the toolbar and the large icon when the button is in the menu panel.
...for example, you might want to give it a different appearance when the current page is being served over https.
...for example, suppose the browser has two windows (w1 and w2), and each window has two tabs.
...And 6 more matches
Creating custom Firefox extensions with the Mozilla build system - Archive of obsolete content
m:version>0.1</em:version> <em:targetapplication> <!-- firefox --> <description> <em:id>{ec8030f7-c20a-464f-9b0e-13a3a9e97384}</em:id> <em:minversion>1.0+</em:minversion> <em:maxversion>1.0+</em:maxversion> </description> </em:targetapplication> <!-- front-end metadata --> <em:name>my first extension</em:name> <em:description>just an example.</em:description> <em:creator>allpeers.com</em:creator> <em:homepageurl>http://www.allpeers.com/blog/</em:homepageurl> </description> </rdf> there's a detailed description of the format of the install.rdf file.
... here's an example of the makefile you need to place into your src directory: depth = ../../..
... = @srcdir@ include $(depth)/config/autoconf.mk is_component = 1 module = myextension library_name = myextension use_static_libs = 1 xpi_name = myextension cppsrcs = \ myfirstcomponent.cpp \ mysecondcomponent.cpp \ myextension.cpp \ $(null) include $(topsrcdir)/config/rules.mk extra_dso_ldopts += \ $(moz_component_libs) \ $(nspr_libs) \ $(null) in this example, the first two files contain the implementation of the extension's two components.
...And 6 more matches
The Essentials of an Extension - Archive of obsolete content
one is the email-like format in the hello world example, which should be something like <project-name>@<yourdomain>.
...for example, if you create a firefox extension, it would normally take little effort to port it to seamonkey, which has very similar features and ui.
...toolbars, menu bars, progress bars, and window title bars are all examples of elements that are typically part of the chrome.
...And 6 more matches
Installing plugins to Gecko embedding browsers on Windows - Archive of obsolete content
for example, netscape 6.0 and 6.01 do not write any of these keys into the registry, and thus these keys are not available for plugin vendors to parse for these two browsers.
...these keys are written by the installer of mozilla browsers -- the netscape 6.2 installer, for example, writes these keys to the registry, and so does the mozilla installer (for versions after mozilla 0.9.1).
...example: netscape 6 6.1\ look at the extensions subkey, e.g.
...And 6 more matches
Drag and Drop JavaScript Wrapper - Archive of obsolete content
the following is an example of calling the nsdraganddrop object.
...if we wanted to handle the other cases also, we can call the other functions, as in the following example: <description value="click and drag this text." ondraggesture="nsdraganddrop.startdrag(event,textobserver)" ondragover="nsdraganddrop.dragover(event,textobserver)" ondragexit="nsdraganddrop.dragexit(event,textobserver)" ondragdrop="nsdraganddrop.drop(event,textobserver)" /> as mentioned earlier, there is nothing special that happens during a dr...
...in the above examples, this observer is stored in the buttonobserver and textobserver variables.
...And 6 more matches
Editor Embedding Guide - Archive of obsolete content
getcommandstate "state_all"(boolean), "state_begin"(boolean), "state_end"(boolean), "state_mixed"(boolean), "state_enabled" (boolean) docommand no parameters example normal bold cmd_italics toggles italics style on selection.
... getcommandstate "state_all"(boolean), "state_begin"(boolean), "state_end"(boolean), "state_mixed"(boolean), "state_enabled" (boolean) docommand no parameters example normal italics cmd_underline toggles underline on selection.
... getcommandstate "state_all"(boolean), "state_begin"(boolean), "state_end"(boolean), "state_mixed"(boolean), "state_enabled" (boolean) docommand no parameters example normal underline cmd_tt toggles teletype style (monospace font) on selection.
...And 6 more matches
Elements - Archive of obsolete content
an explicit encoding declarations may be present to override the default, for example <?xml version="1.0" encoding="iso-8859-1"?> uri in namespace declarations is an opaque string used to uniquely identify the namespace.
... for clarity's sake, here's what the embedded xml in the previous example looks like: <?xml version="1.0"?> <bindings id="xbltestbindings" xmlns="http://www.mozilla.org/xbl"> <binding id="xbltest"><content>pass</content></binding> </bindings> only css declarations provide an easy way to attach bindings to any set of elements.
...for example, use the value 'xul:button' to create an element that is displayed like a button.
...And 6 more matches
Using XPInstall to Install Plugins - Archive of obsolete content
unlike native code installers (for example, files called setup.exe), the programming language for install operations in xpi is javascript.
...examples would be flash 6r47 on windows, which consists of a dll (called npswf32.dll) and an xpt file for scriptability (called flashplayer.xpt).
...for example, realplayer on windows consists of a plugin dll, but also the realplayer application (exe) which the plugin dll is a subset of.
...And 6 more matches
Writing to Files - Archive of obsolete content
try { var file = io.getfile("desktop", "myinfo.txt"); var stream = io.newoutputstream(file, "text"); } catch (ex) { alert(ex); } this example retrieves a file object on the desktop called 'myinfo.txt' using nsiscriptableio.getfile().
...in this example, the operations are enclosed in a try-catch block in order to capture any errors that might occur during the process.
...the newoutputstream method takes two arguments in this example.
...And 6 more matches
Positioning - Archive of obsolete content
for instance: <menupopup id="edititems" position="end_before"> <menuitem label="cut"/> <menuitem label="copy"/> <menuitem label="paste"/> </menupopup> <label value="clipboard" popup="edititems"/> in this example, a menupopup is attached to a label via the popup attribute, which will cause the popup to appear when the label is left-clicked.
... bottomright the bottom-right corner of the popup will be aligned with the specified corner or edge of the anchor element for example, a position value of bottomleft topleft means that the popup will be positioned such that the bottom-left corner of the anchor is aligned with the upper-left corner of the popup.
... the following table shows the valid values, corresponding explicit (ie, 2 word) alignment values and an example of the alignment.
...And 6 more matches
Actions - Archive of obsolete content
let's look at a simple example first.
...//www.xulplanet.com/ds/sample.rdf" ref="http://www.xulplanet.com/rdf/a"> <template> <query> <content uri="?start"/> <triple subject="?start" predicate="http://www.xulplanet.com/rdf/relateditem" object="?relateditem"/> </query> <action> <button uri="?relateditem" label="?relateditem"/> </action> </template> </vbox> in this example, we omit the <xul:rule> element around the <xul:action> as it is optional when we want to generate content unconditionally.
...here is the [example], and an image of what it looks like: the template builder iterates through the three results, processing the body of the action for each one in turn.
...And 6 more matches
Building Trees - Archive of obsolete content
here is an example (using an rdf source): <tree id="photoslist" flex="1" datasources="template-guide-photos5.rdf" ref="http://www.xulplanet.com/rdf/myphotos" flags="dont-build-content"> <treecols> <treecol id="name" label="name" flex="1"/> <treecol id="date" label="date" flex="1"/> </treecols> <template> <treechildren> <treeitem uri="rdf:*"> <treerow> <treecell label=...
...in the example above, the first cell should display the title.
...compare the example with a tree builder and the same example using a content builder.
...And 6 more matches
XML Templates - Archive of obsolete content
the ref attribute isn't currently used for xml sources, as the root of the document is always the starting point for xml queries; you should just set the ref attribute to a dummy value, for example '*' which is typically used.
... an example: <listbox datasources="people.xml" ref="*" querytype="xml"> <template> ...
... 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 ...
...And 6 more matches
Custom toolbar button - Archive of obsolete content
open the file in firefox (for example, by dragging it and dropping it in firefox, or by choosing file – open file...
... copy the name from here and paste it, to avoid typing errors: custom-toolbar-button@example.com perform the following steps in this new directory, creating two files and a directory there.
...paste it into the new file: <?xml version="1.0"?> <rdf xmlns="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:em="http://www.mozilla.org/2004/em-rdf#"> <description about="urn:mozilla:install-manifest" em:name="custom button" em:description="my custom toolbar button" em:creator="my name" em:id="custom-toolbar-button@example.com" em:version="1.0" em:homepageurl="http://developer.mozilla.org/en/docs/custom_toolbar_button" em:iconurl="chrome://custombutton/content/icon.png" > <em:targetapplication><!-- firefox --> <description em:id="{ec8030f7-c20a-464f-9b0e-13a3a9e97384}" em:minversion="1.4" em:maxversion="*" /> </em:targetapplication> <em:targetapplication><!--...
...And 6 more matches
Adding Labels and Images - Archive of obsolete content
an example is shown below: example 1 : source view <label value="this is some text"/> the value attribute can be used to specify the text that you wish to have displayed.
...if the text needs to wrap, you can place the text content inside opening and closing tags as in the following example: example 2 : <label>this is some longer text that will wrap onto several lines.</label> as with html, line breaks and extra whitespace are collapsed into a single space.
...example 3 : source view <label value="click here:" control="open-button"/> <button id="open-button" label="open"/> in the example above, clicking the label will cause the button to be focused.
...And 6 more matches
Adding Methods to XBL-defined Elements - Archive of obsolete content
for example, if the method had three parameters, there would be three parameter elements.
...for example, the following javascript function would be written as an xbl method like so: function getmaximum(num1,num2) { if (num1 <= num2) return num2; else return num1; } xbl: <method name="getmaximum"> <parameter name="num1"/> <parameter name="num2"/> <body> if (num1 &lt;= num2) return num2; else return num1; </body> </method> this function, getmaximum, returns the largest of the values, each passed as a parameter to the method.
...for example, the following code will probably fail: var element = document.createelement("my_element"); element.getmaximum() // this will fail by the way, it is safe to call methods from the constructor, other methods on the object and event handlers.
...And 6 more matches
Grids - Archive of obsolete content
ArchiveMozillaXULTutorialGrids
this should be easier to understand with an example.
... example 1 : source view <grid flex="1"> <columns> <column flex="2"/> <column flex="1"/> </columns> <rows> <row> <button label="rabbit"/> <button label="elephant"/> </row> <row> <button label="koala"/> <button label="gorilla"/> </row> </rows> </grid> two rows and two columns have been added to a grid.
...for example: example 2 : source view <grid flex="1"> <columns> <column/> <column flex="1"/> </columns> <rows> <row> <label control="doctitle" value="document title:"/> <textbox id="doctitle" flex="1"/> </row> <row> <label control="docpath" value="path:"/> <hbox flex="1"> <textbox id="docpath" flex="1"/> <button label="browse..."/> </...
...And 6 more matches
Introduction to XBL - Archive of obsolete content
for example, you might want to change how the pieces of a scroll bar function.
...for example, a binding might be attached to a scroll bar.
...the following example shows the basic skeleton of an xbl file: <?xml version="1.0"?> <bindings xmlns="http://www.mozilla.org/xbl"> <binding id="binding1"> <!-- content, property, method and event descriptions go here --> </binding> <binding id="binding2"> <!-- content, property, method and event descriptions go here --> </binding> </bindings> the bindings element is the root element of an xbl file and contains one or more binding elements.
...And 6 more matches
Vulnerabilities - Archive of obsolete content
an example is an input validation error, such as user-provided input not being properly evaluated for malicious character strings and overly long values associated with known attacks.
... another example is a race condition error that allows the attacker to perform a specific action with elevated privileges.
...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.
...And 6 more matches
Choosing Standards Compliance Over Proprietary Practices - Archive of obsolete content
for example, an organization may decide that c++, java, and javascript will be the primary coding languages.
...sure, there are other reasons -– accountability, checkpoints, and scheduling, for example.
...for example, in the accounting arena there is fasb (financial accounting standards board) and iasb (international accounting standards board).
...And 6 more matches
Handling different text directions - Learn web development
we create borders on the top, right, bottom, and left of a box, for example.
... in the example below we have a heading displayed using writing-mode: vertical-rl.
... if we look at an example this will become clearer.
...And 6 more matches
Test your skills: Selectors - Learn web development
try updating the live code below to recreate the finished example: for assessment or further work purposes, download the starting point for this task to work in your own editor or in an online editor.
... selectors two without changing the html, make the following changes to the look of the content in this example: give the element with an id of special a yellow background.
... try updating the live code below to recreate the finished example: for assessment or further work purposes, download the starting point for this task to work in your own editor or in an online editor.
...And 6 more matches
CSS selectors - Learn web development
in earlier articles you met some different selectors, and learned that there are selectors that target the document in different ways — for example by selecting an element such as h1, or a class such as .special.
...for example, if i have the same css for an h1 and also a class of .special, i could write this as two separate rules.
... h1, .special { color: blue; } in the live example below try combining the two selectors which have identical declarations.
...And 6 more matches
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 see the most important parts using the following url: http://www.example.com:80/path/to/myfile.html?key1=value1&key2=value2#somewhereinthedocument http is the protocol.
... www.example.com is the domain name.
...And 6 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 6 more matches
Sending forms through JavaScript - Learn web development
but forms can also prepare an http request to send via javascript, for example via xmlhttprequest.
... let's look at an example: <button>click me!</button> and now the javascript: const btn = document.queryselector('button'); function senddata( data ) { console.log( 'sending data' ); const xhr = new xmlhttprequest(); let urlencodeddata = "", urlencodeddatapairs = [], name; // turn the data object into an array of url-encoded key/value pairs.
...something went wrong.' ); } ); // set up our request xhr.open( 'post', 'https://example.com/cors.php' ); // add the required http header for form data post requests xhr.setrequestheader( 'content-type', 'application/x-www-form-urlencoded' ); // finally, send our data.
...And 6 more matches
Styling web forms - Learn web development
we'll walk through an example at the end of this article to give you some more ideas on basic form control styling and placement.
...to position it somewhere else, for example inside the fieldset somewhere, or near the bottom left corner, you need to rely on positioning.
... take the following example: to position the legend in this manner, we used the following css (other declarations removed for brevity): fieldset { position: relative; } legend { position: absolute; bottom: 0; right: 0; } the <fieldset> needs to be positioned too, so that the <legend> is positioned relative to it (otherwise the <legend> would be positioned relative to the <body>.) the <legend> element is very important for accessibility — it will be spoken by assistive technologies as part of the label of each form element inside the fieldset — but using a technique like the one above is fine.
...And 6 more matches
HTML basics - Learn web development
for example, content could be structured within a set of paragraphs, a list of bulleted points, or using images and data tables.
... for example, take the following line of content: my cat is very grumpy if we wanted the line to stand by itself, we could specify that it is a paragraph by enclosing it in paragraph tags: <p>my cat is very grumpy</p> anatomy of an html element let's explore this paragraph element a bit further.
...in the example above, we opened the <p> element first, then the <strong> element; therefore, we have to close the <strong> element first, then the <p> element.
...And 6 more matches
Choosing the right approach - Learn web development
single delayed operation repeating operation multiple sequential operations multiple simultaneous operations no yes (recursive callbacks) yes (nested callbacks) no code example an example that loads a resource via the xmlhttprequest api (run it live, and see the source): function loadasset(url, type, callback) { let xhr = new xmlhttprequest(); xhr.open('get', url); xhr.responsetype = type; xhr.onload = function() { callback(xhr.response); }; xhr.send(); } function displayimage(blob) { let objecturl = url.createobjecturl(blob); let image = docum...
... single delayed operation repeating operation multiple sequential operations multiple simultaneous operations yes yes (recursive timeouts) yes (nested timeouts) no code example here the browser will wait two seconds before executing the anonymous function, then will display the alert message (see it running live, and see the source code): let mygreeting = settimeout(function() { alert('hello, mr.
...falls you can use recursive settimeout() calls to run a function repeatedly in a similar fashion to setinterval(), using code like this: let i = 1; settimeout(function run() { console.log(i); i++; settimeout(run, 100); }, 100); there is a difference between recursive settimeout() and setinterval(): recursive settimeout() guarantees at least the specified amount of time (100ms in this example) will elapse between the executions; the code will run and then wait 100 milliseconds before it runs again.
...And 6 more matches
Handling text — strings in JavaScript - Learn web development
for example, both of these are okay: let sgldbl = 'would you eat a "fish supper"?'; let dblsgl = "i'm feeling blue."; sgldbl; dblsgl; however, you can't include the same quote mark inside the string if it's being used to contain them.
...let's try an example in our console.
... concatenation in context let's have a look at concatenation being used in action — here's an example from earlier in the course: <button>press me</button> const button = document.queryselector('button'); button.onclick = function() { let name = prompt('what is your name?'); alert('hello ' + name + ', nice to see you!'); } here we're using a window.prompt() function in line 4, which asks the user to answer a question via a popup dialog box then stores the text they enter inside a given ...
...And 6 more matches
Storing the information you need — Variables - Learn web development
let's look at a simple example: <button>press me</button> const button = document.queryselector('button'); button.onclick = function() { let name = prompt('what is your name?'); alert('hello ' + name + ', nice to see you!'); } in this example pressing the button runs a couple of lines of code.
... to understand why this is so useful, let's think about how we'd write this example without using a variable.
...for example: myname = 'chris'; myage = 37; try going back to the console now and typing in these lines.
...And 6 more matches
Mozilla accessibility architecture
for example, they all expose an accessible name, or text representation, of each object, and they all use an enumerated integer value from a finite list, to expose the role of an object.
... 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.
...for example, tables support nsiaccessibletable, text supports nsiaccessibletext and edit boxes support nsieditabletext., although this code has been moved into the atk specific directories because it is not currently used in windows.
...And 6 more matches
Configuring Build Options
this is useful if you choose to have multiple mozconfig files for different applications or configurations (see below for a full example).
... note that in the export example below the filename was not mozconfig.
... regardless of the name of the actual file you use, we refer to this file as the mozconfig file in the examples below.
...And 6 more matches
Following the Android Toasts Tutorial from a JNI Perspective
for example, navigating away from an email before you send it triggers a "draft saved" toast to let you know that you can continue editing later.
...the java code example above can be done with privileged javascript from firefox for android with the following code: window.nativewindow.toast.show("hello, firefox!", "short"); converting java to jni.jsm the first step is to look at the java code and see all the different types, methods, constructors, and fields that are being used.
...for example, if the class is blah.foo.bar then the signature of this will be this in slash notation with an l and ; around it.
...And 6 more matches
Localization and Plurals
for example, "1 page" vs "2 pages".
...for example, english uses plural rule 1, and localizing plurals would require a string of "plural;plurals" where the first word is the singular form and the second is the general plural form.
... examples the following are some examples for various languages and a brief thought processes.
...And 6 more matches
An overview of NSS Internals
some cryptography uses the same secret key for both encrypting and decrypting, for example password based encryption (pbe).
...a certificate contains lots of other details; for example, it contains a signature by a third party that expresses trust in the ownership relationship for the certificate.
...examples for the database files are key3.db and cert8.db, where the numbers are file version numbers.
...And 6 more matches
PKCS11 FAQ
MozillaProjectsNSSPKCS11FAQ
multipart functions, such as bulk encryption, hashing, and mac functions (for example, c_digest and c_sign) and those that require overlapped operation (c_unwrap, c_decrypt) are handled by creating new sessions.
...example: rsa private key, ca certificate, user's own certificate, user's name.
...nss never attempts to cache this information, because login state can change instantly without nss knowing about it (for example, when the user removes the card).
...And 6 more matches
Building an Account Manager Extension
we name the extension "devmo-account" and state that it is located in the chrome package "example@mozilla.org".
... components.utils.import("resource://gre/modules/xpcomutils.jsm"); //class constructor function devmoaccountmanagerextension() {}; // class definition devmoaccountmanagerextension.prototype = { name : "devmo-account", chromepackagename : "example@mozilla.org", showpanel: function(server) { //this panel is only shown for imap accounts...
...the unique component identifier (change it if you copied this example!)...
...And 6 more matches
Working with ArrayBuffers
the second code example provides a specific illustration of the operation.
... this feature is based on the following work: //github.com/realityripple/uxp/blob/master/js/src/ctypes/ctypes.cpp#3080 //github.com/realityripple/uxp/blob/master/js/src/vm/arraybufferobject.cpp#1301 example 1 - image data the following example illustrates how to transfer a byte array pointed by ctypes.uint8_t.ptr to imagedata of canvas.
... this example is based on the fact that the imagedata returned from canvasrenderingcontext2d.getimagedata is a uint8clampedarray view for an arraybuffer.
...And 6 more matches
Accessibility Inspector - Firefox Developer Tools
the name depends on the element; for example, the name of most text elements is simply their textcontent, whereas form elements' names are the contents of their associated <label>.
... actions — a list of actions that can be performed on the item, for example, a pushbutton would have "press" listed, while a link would have "jump" listed.
...this can mean different things depending on the type of the item; for example, a form input (role: entry) would have a value of whatever is entered in the input, whereas a link's value would be the url in the corresponding <a> element's href.
...And 6 more matches
AddressErrors - Web APIs
see the examples below to see how this works.
...try to avoid asking the user to make corrections to things they can't change, and there may be situations in which you need to allow validation errors to be accepted anyway (for example, if you validate addresses against a postal service database and a new home has been built and its address is not yet in the database).
... 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.
...And 6 more matches
Basic usage of canvas - Web APIs
at the end of this page, you will know how to set up a canvas 2d context and have drawn a first example in your browser.
... for example, we could provide a text description of the canvas content or provide a static image of the dynamically rendered content.
... this can look something like this: <canvas id="stockgraph" width="150" height="150"> current stock price: $3.15 + 0.15 </canvas> <canvas id="clock" width="150" height="150"> <img src="images/clock.png" width="150" height="150" alt=""/> </canvas> telling the user to use a different browser that supports canvas does not help users who can't read the canvas at all, for example.
...And 6 more matches
Traversing an HTML table with JavaScript and DOM Interfaces - Web APIs
example: creating an html table dynamically (sample1.html) html <input type="button" value="generate a table." onclick="generate_table()"> javascript function generate_table() { // get the reference for the body var body = document.getelementsbytagname("body")[0]; // creates a <table> element and a <tbody> element var tbl = document.createelement("table"); var tblbody = document.createele...
... example: setting the background color of a paragraph getelementsbytagname(tagnamevalue) is a method available in any dom element or the root document element.
...dy elements (there will only be one), // and then select the zeroth (or first) such element mybody = document.getelementsbytagname("body")[0]; // now, get all the p elements that are descendants of the body mybodyelements = mybody.getelementsbytagname("p"); // get the second item of the list of p elements myp = mybodyelements[1]; myp.style.background = "rgb(255,0,0)"; } in this example, we set the myp variable to the dom object for the second p element inside the body: first, we get a list of all the body elements via mybody = document.getelementsbytagname("body")[0] since there is only one body element in any valid html document, this list will have only one item, which we retrieve by selecting the first element in that list using [0].
...And 6 more matches
HTMLImageElement.alt - Web APIs
it will be read aloud or sent to the touch device, for example, to support visually impaired users.
... 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.
...And 6 more matches
HTML Drag and Drop API - Web APIs
the setdata() method is used to add an item to the drag data, as shown in the following example.
...however, an application may define a custom image with the setdragimage() method, as shown in the following example.
... // note: change "example.gif" to a real image url or the image // will not be created and the default drag image will be used.
...And 6 more matches
Intersection Observer API - Web APIs
for example, if you want to be informed every time a target's visibility passes backward or forward through each 25% mark, you would specify the array [0, 0.25, 0.5, 0.75, 1] as the list of thresholds when creating the observer.
... threshold example <template id="boxtemplate"> <div class="samplebox"> <div class="label topleft"></div> <div class="label topright"></div> <div class="label bottomleft"></div> <div class="label bottomright"></div> </div> </template> <main> <div class="contents"> <div class="wrapper"> </div> </div> </main> .contents { position: absolute; width: 700px; height: 1725px; } .wra...
... a simple example this simple example causes a target element to change its color and transparency as it becomes more or less visible.
...And 6 more matches
Microdata DOM API - Web APIs
microdata becomes even more useful when scripts can use it to expose information to the user, for example offering it in a form that can be used by other applications.
... code example this sample shows how the getitems() method can be used to obtain a list of all the top-level microdata items of a particular type given in the document: var cats = document.getitems("http://example.com/feline"); once an element representing an item has been obtained, its properties can be extracted using the properties idl attribute.
... code example this sample gets the first item of type "http://example.net/user" and then pops up an alert using the "name" property from that item.
...And 6 more matches
Using the Notifications API - Web APIs
typically, system notifications refer to the operating system's standard notification mechanism: think for example of how a typical desktop system or mobile device broadcasts notifications.
... 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.
...And 6 more matches
Using Service Workers - Web APIs
sync try { const value = myfunction(); console.log(value); } catch(err) { console.log(err); } async myfunction().then((value) => { console.log(value); }).catch((err) => { console.log(err); }); in the first example, we have to wait for myfunction() to run and return value before any more of the code can execute.
... in the second example, myfunction() returns a promise for value, then the rest of the code can carry on running.
... now for a real example — what if we wanted to load images dynamically, but we wanted to make sure the images were loaded before we tried to display them?
...And 6 more matches
Basic Concepts of Multicol - CSS: Cascading Style Sheets
this guide explains how the specification works with some common use case examples.
...this happens in the same way that content is fragmented into pages when we work with css paged media, for example by creating a print stylesheet.
... in the below example we use the column-count property to create three columns on the .container element.
...And 6 more matches
Using feature queries - CSS: Cascading Style Sheets
you may not test for a bare property name such as display; the rule requires a property name and a value: @supports (property: value) { css rules to apply } if you want to check if a browser supports the row-gap property, for example, you would write the following feature query.
...a good example would be the display property.
... testing for lack of support in addition to asking the browser if it supports a feature, you can test for the opposite by adding in the not keyword: @supports not (property: value) { css rules to apply } the css inside the following example feature query will run if the browser does not support row-gap.
...And 6 more matches
Relationship of flexbox to other layout methods - CSS: Cascading Style Sheets
you can change the live example below to these modes in order to see what happens to the flex layout.
...for example, if an item is floated and then its parent becomes a flex container.
... in this next live example the child elements have been floated, and then their container has had display: flex added.
...And 6 more matches
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.
... they may not match exactly due to browser implementation inconsistencies, but in many cases the first example will match the second.
...And 6 more matches
Layout using named grid lines - CSS: Cascading Style Sheets
once you work through some examples it should become clearer and easier to work with.
... giving lines multiple names you may want to give a line more than one name, perhaps it denotes the sidebar-end and the main-start for example.
... while you can choose any name, if you append -start and -end to the lines around an area, as i have in the example above, grid will create you a named area of the main name used.
...And 6 more matches
Line-based placement with CSS Grid - CSS: Cascading Style Sheets
a basic example as a very simple example we can take a grid with 3 column tracks and 3 row tracks.
... 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.
...this means that our initial, long-hand, example would look like this: * {box-sizing: border-box;} .wrapper { border: 2px solid #f76707; border-radius: 5px; background-color: #fff4e6; display: grid; grid-template-columns: repeat(3, 1fr); grid-template-rows: repeat(3, 100px); } .wrapper > div { border: 2px solid #ffa94d; border-radius: 5px; background-color: #ffd8a8; padding: 1em; color: #d9480f; } <div 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-start: 1; grid-row-start: 1; grid-row-end: 4; } .box2 { grid-column-start: 3; grid-row-start: 1; grid-row-end: 3; } .box3...
...And 6 more matches
Overview of CSS Shapes - CSS: Cascading Style Sheets
you could for example float an item left, which would cause the text to wrap round the right and bottom of the item in a rectangular fashion.
... in the following example i have an image floated left.
... basic shapes the value circle(50%) is an example of a basic shape.
...And 6 more matches
CSS values and units - CSS: Cascading Style Sheets
for example, the value of grid-area can be a <custom-ident>, so if we had a grid area named content we would use it without quotes: .item { grid-area: content; } in comparison, a data type that is a <string>, such as a string value of the content property, must be quoted: .item::after { content: "this is my content."; } while you can generally create any name you want, including using emojis, the...
...for example, if you wanted to include a background image, you might use either of the following.
... numbers a <number> represents a real number, which may or may not have a decimal point with a fractional component, for example 0.255, 128 or -1.2.
...And 6 more matches
<angle> - CSS: Cascading Style Sheets
WebCSSangle
it is used, for example, in <gradient>s and in some transform functions.
... the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...And 6 more matches
box-decoration-break - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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; } ...
...And 6 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.
... example html date and time strings string date and/or time 2005-06-07 june 7, 2005 [details] 08:45 8:45 am [details] 08:45:25 8:45 am and 25 seconds [details] 0033-08-04t03:40 3:40 am on august 4, 33 [details] 1977-04-01t14:00:30 30 seconds after 2:00 pm on april 1, 1977 [details] 1901-01-01t00:00z midnight utc on january 1, 1901 [details] 1901-01-01t00:00:01-04:00 1 second past midnight eastern standard time (est) on january 1, 1901 [details] basics before looking at the various formats of date and time related strings used by html elements, it is helpful to understand a few fundamental facts about the way they're defined.
...for example, the first thursday of 1953 was on january 1, so that week—beginning on monday, december 29—is considered the first week of the year.
...And 6 more matches
<bdi>: The Bidirectional Isolate element - HTML: Hypertext Markup Language
WebHTMLElementbdi
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...in this algorithm, characters are given an implicit directionality: for example, latin characters are treated as ltr while arabic characters are treated as rtl.
...And 6 more matches
<input type="button"> - HTML: Hypertext Markup Language
WebHTMLElementinputbutton
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... in this example, s is specified as the access key (you'll need to press s plus the particular modifier keys for your browser/os combination; see accesskey for a useful list of those).
...And 6 more matches
<input type="password"> - HTML: Hypertext Markup Language
WebHTMLElementinputpassword
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... specifics of how the entry process works may vary from browser to browser; mobile devices, for example, often display the typed character for a moment before obscuring it, to allow the user to be sure they pressed the key they meant to press; this is helpful given the small size of keys and the ease with which the wrong one can be pressed, especially on virtual keyboards.
...And 6 more matches
CSP: base-uri - HTTP
examples: http://*.example.com: matches all attempts to load from any subdomain of example.com using the http: url scheme.
... mail.example.com:443: matches all attempts to access port 443 on mail.example.com.
... https://store.example.com: matches all attempts to access store.example.com using https:.
...And 6 more matches
CSP: default-src - HTTP
examples: http://*.example.com: matches all attempts to load from any subdomain of example.com using the http: url scheme.
... mail.example.com:443: matches all attempts to access port 443 on mail.example.com.
... https://store.example.com: matches all attempts to access store.example.com using https:.
...And 6 more matches
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.
... mail.example.com:443: matches all attempts to access port 443 on mail.example.com.
... https://store.example.com: matches all attempts to access store.example.com using https:.
...And 6 more matches
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.
... mail.example.com:443: matches all attempts to access port 443 on mail.example.com.
... https://store.example.com: matches all attempts to access store.example.com using https:.
...And 6 more matches
CSP: script-src - HTTP
examples: http://*.example.com: matches all attempts to load from any subdomain of example.com using the http: url scheme.
... mail.example.com:443: matches all attempts to access port 443 on mail.example.com.
... https://store.example.com: matches all attempts to access store.example.com using https:.
...And 6 more matches
An overview of HTTP - HTTP
WebHTTPOverview
most of the time the user-agent is a web browser, but it can be anything, for example a robot that crawls the web to populate and maintain a search engine index.
...between the client and the server there are numerous entities, collectively called proxies, which perform different operations and act as gateways or caches, for example.
...this immediately has the prospect of being problematic for users attempting to interact with certain pages coherently, for example, using e-commerce shopping baskets.
...And 6 more matches
Array.prototype.forEach() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...(for sparse arrays, see example below.) callback is invoked with three arguments: the value of the element the index of the element the array object being traversed if a thisarg parameter is provided to foreach(), it will be used as callback's this value.
...And 6 more matches
String.prototype.normalize() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...for example, the code point for "a" is given as u+0041.
...And 6 more matches
String.prototype.replace() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...above.) for example, if /(\a+)(\b+)/, was given, p1 is the match for \a+, and p2 for \b+.
...And 6 more matches
String.prototype.split() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... for example, a string containing tab separated values (tsv) could be parsed by passing a tab character as the separator, like this: mystring.split("\t").
...And 6 more matches
Operator precedence - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... as another example, the unique exponentiation operator has right-associativity, whereas other arithmetic operators have left-associativity.
...And 6 more matches
Populating the page: how browsers work - Web Performance
if you navigate to https://example.com, the html page is located on the server with ip address of 93.184.216.34.
... <!doctype html> <html> <head> <meta charset="utf-8"/> <title>my simple page</title> <link rel="stylesheet" src="styles.css"/> <script src="myscript.js"></script> </head> <body> <h1 class="heading">my page</h1> <p>a paragraph with a <a href="https://example.com/about">link</a></p> <div> <img src="myimage.jpg" alt="image description"/> </div> <script src="anotherscript.js"></script> </body> </html> this response for this initial request contains the first byte of data received.
... in our example above, the request is definitely less than 14kb, but the linked resources aren't requested until the browser encounters the links during parsing, described below.
...And 6 more matches
Media - Progressive web apps (PWAs)
for example, you are probably reading this on a device with a display.
... example a document on a website has a navigation area that contains the primary site menu.
...for example, in html, you have the option to specify the media type with a media attribute in the link element.
...And 6 more matches
Basic Transformations - SVG: Scalable Vector Graphics
an example: <svg width="30" height="10"> <g fill="red"> <rect x="0" y="0" width="10" height="10" /> <rect x="20" y="0" width="10" height="10" /> </g> </svg> all following transformations are summed up in an element's transform attribute.
... <svg width="40" height="50" style="background-color:#bff;"> <rect x="0" y="0" width="10" height="10" transform="translate(30,40)" /> </svg> the example will render a rectangle, translated to the point (30,40) instead of (0,0).
...use the rotate() transformation for this: <svg width="31" height="31"> <rect x="12" y="-10" width="20" height="20" transform="rotate(45)" /> </svg> this example shows a square that is rotated by 45 degrees.
...And 6 more matches
Using templates and slots - Web Components
let's look at a trivial quick example: <template id="my-paragraph"> <p>my paragraph</p> </template> this won't appear in your page until you grab a reference to it with javascript and then append it to the dom, using something like the following: let template = document.getelementbyid('my-paragraph'); let templatecontent = template.content; document.body.appendchild(templatecontent); although trivial, you can already start to s...
... so for example: <template id="my-paragraph"> <style> p { color: white; background-color: #666; padding: 5px; } </style> <p>my paragraph</p> </template> now we can use it by just adding it to our html document: <my-paragraph></my-paragraph> note: templates are well-supported in browsers; the shadow dom api is supported by default in firefox (version 63 onwards), chrome, oper...
... so, if we want to add a slot into our trivial example, we could update our template's paragraph element like this: <p><slot name="my-text">my default text</slot></p> if the slot's content isn't defined when the element is included in the markup, or if the browser doesn't support slots, <my-paragraph> just contains the fallback content "my default text".
...And 6 more matches
Compiling a New C/C++ Module to WebAssembly - WebAssembly
prerequisites get the emscripten sdk, using these instructions: https://emscripten.org/docs/getting_started/downloads.html compiling an example with the environment set up, let's look at how to use it to compile a c example to emscripten.
... first we need an example to compile.
... take a copy of the following simple c example, and save it in a file called hello.c in a new directory on your local drive: #include <stdio.h> int main(int argc, char ** argv) { printf("hello world\n"); } now, using the terminal window you used to enter the emscripten compiler environment, navigate to the same directory as your hello.c file, and run the following command: emcc hello.c -s wasm=1 -o hello.html the options we’ve passed in with the command are as follows: -s wasm=1 — specifies that we want wasm output.
...And 6 more matches
Interacting with page scripts - Archive of obsolete content
in this example a page script adds a string variable foo to the window: <!doctype html"> <html> <head> <script> window.foo = "hello from page script" </script> </head> </html> the content script can see this object if it uses unsafewindow.foo instead of window.foo: // main.js var tabs = require("sdk/tabs"); var mod = require("sdk/page-mod"); var self = require("sdk/self"); var pageurl = self...
... here's an example.
...ript> var works = document.getelementbyid("works"); works.addeventlistener("click", function() { alert(clonedcontentscriptobject.greeting); }, false); var fails = document.getelementbyid("fails"); fails.addeventlistener("click", function() { alert(assignedcontentscriptobject.greeting); }, false); </script> </body> </html> if you run the example, clicking "i will work" displays the value of "greeting" in an alert.
...And 5 more matches
tabs - Archive of obsolete content
usage open a tab you can open a new tab, specifying various properties including location: var tabs = require("sdk/tabs"); tabs.open("http://www.example.com"); track tabs you can register event listeners to be notified when tabs open, close, finish loading dom content, or are made active or inactive: var tabs = require("sdk/tabs"); // listen for tab openings.
...by setting the url property you can load a new page in the tab: var tabs = require("sdk/tabs"); tabs.on('activate', function(tab) { tab.url = "http://www.example.com"; }); run scripts in a tab you can attach a content script to the page hosted in a tab, and use that to access and manipulate the page's content (see the modifying the page hosted by a tab tutorial): var tabs = require("sdk/tabs"); tabs.on('activate', function(tab) { var worker = tab.attach({ contentscript: 'self.port.emit("html", document.body.innerhtml);' }); worker.port.on("h...
... here's an example converting from a high-level tab to a xul tab and then back the other way: var { modelfor } = require("sdk/model/core"); var { viewfor } = require("sdk/view/core"); var tabs = require("sdk/tabs"); var tab_utils = require("sdk/tabs/utils"); function maphighleveltolowlevel(tab) { // get the xul tab that corresponds to this high-level tab var lowleveltab = viewfor(tab); // now we can, for e...
...And 5 more matches
url - Archive of obsolete content
for example: var url = require("sdk/url").url("https://developer.mozilla.org/add-ons?example=true&visible=yes#top"); console.log(url.scheme); // https userpass the username:password part of the url, null if not present.
...for example: var url = require("sdk/url").url("https://developer.mozilla.org/add-ons?example=true&visible=yes#top"); console.log(url.host); // developer.mozilla.org port the port number of the url, null if none was specified.
...for example: var url = require("sdk/url").url("https://developer.mozilla.org/add-ons?example=true&visible=yes#top"); console.log(url.path); // /add-ons?example=true&visible=yes#top hostname the domain of the url, as a string.
...And 5 more matches
/loader - Archive of obsolete content
the example above overlays the base path '' with a different mapping for 'toolkit/' prefixed modules.
...for example in the sdk, the loader is loaded at bootstrap as a jsm module but is then exposed as a pseudo-module to avoid the overhead of subsequent loads: let loadermodule = cu.import('resource://gre/modules/commonjs/toolkit/loader.js'); let loader = loadermodule.loader({ modules: { // overlay `toolkit/loader` so that `require('toolkit/loader')` // will return our `loadermodule`.
...for example, unload of a loader won't trigger unload hooks on pseudo-modules.
...And 5 more matches
util/match-pattern - Archive of obsolete content
example pattern example matching urls example non-matching urls "http://example.com/" http://example.com/ http://example.com http://example.com/foo https://example.com/ http://foo.example.com/ wildcards a single asterisk matches any url with an http, https, or ftp scheme.
... example pattern example matching urls example non-matching urls "*" http://example.com/ https://example.com/ ftp://example.com/ http://bar.com/foo.js http://foo.com/ file://example.js resource://me/my-addon/data/file.html data:text/html,hi there a domain name prefixed with an asterisk and dot matches any url of that domain or a subdomain, using any of http, https, ftp.
... example pattern example matching urls example non-matching urls "*.example.com" http://example.com/ http://foo.example.com/ https://example.com/ http://example.com/foo ftp://foo.example.com/ ldap://example.com http://example.foo.com/ a url followed by an asterisk matches that url and any url prefixed with the pattern.
...And 5 more matches
Localization - Archive of obsolete content
using localized strings in html this example uses the action button api, which is only available from firefox 29 onwards.
... to reference localized strings from html, add a data-l10n-id attribute to the html tag where you want the localized string to appear, and assign the identifier to it: <html> <body> <h1 data-l10n-id="hello_id"></h1> </body> </html> then you can use this html file to build your interface, for example inside a panel: var button = require("sdk/ui/button/action").actionbutton({ id: "localized-hello", label: "localized hello", icon: "./icon-16.png", onclick: function() { hello.show(); } }); var hello = require("sdk/panel").panel({ height: 75, width: 150, contenturl: require("sdk/self").data.url("my-panel.html") }); given locale files for "en-us" and "fr" which provide translations of hello_id, the panel will now display "hello!" or "bonjour !", according to the curr...
...for example, english has two forms: a singular form for "one", and a plural form for "everything else, including zero": one tomato no tomatoes two tomatoes but russian has different forms for numbers ending in 1 (except 11), numbers ending in 2-4 (except 12-14) and other numbers: один помидор // one tomato два помидора // two tomatoes пять помидоров // five to...
...And 5 more matches
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.
...And 5 more matches
A XUL Bestiary - Archive of obsolete content
in the example above, the chrome is simply a skin file to be loaded into the xul file, but the chrome can also be used to load whole chromes, as when a <menuitem> in one window brings up a new chrome: <menuitem value="mozilla help" oncommand="window.opendialog('chrome://help/content/help.xul', '_blank', 'chrome,all,dialog=no')" /> in this exam...
...when you invoke mozilla from the command line with the -chrome flag, you can specify a chrome just as you would in the previous example: mozilla -chrome chrome://help/content/help.xul brings up the help package mentioned in the previous example as a "stand-alone" chrome.
...for example, if you want to create a different skin for the navigator package, you can create a subdirectory underneath navigator/skin/ whose contents will be loaded instead of default's.
...And 5 more matches
Introduction to XUL - Archive of obsolete content
note that the above example is using an implicit xul namespace.
... this is optional; other examples in this document will on occasion belabor the namespace issue by declaring each use explicitly.
... an example window below is a complete sample xul document that describes a window with a menu bar and an html content area.
...And 5 more matches
MenuItems - Archive of obsolete content
for the "open" item in this example, this command can be invoked by using the "accel" modifier key and pressing 'o'.
...in this example we use an image that is 16px wide and 32px high.
...<menuitem label="show toolbar" accesskey="t" type="checkbox" oncommand="changetoolbarstate();"/> in this example, we show the toolbar when the menuitem is checked and hide the toolbar otherwise.
...And 5 more matches
Panels - Archive of obsolete content
for example, the following panel displays a textbox for entering a name.
... <?xml-stylesheet href="chrome://global/skin" type="text/css"?> <window xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <button label="details" type="panel"> <panel id="search-panel"> <label control="name" value="name:"/> <textbox id="name"/> </panel> </button> </window> many panels will be associated with a button, as in this example.
...for other types of elements, you need to use a different technique as in the following example.
...And 5 more matches
Additional Navigation - Archive of obsolete content
here is an example triple that we could use in the photos example: <query> <content uri="?start"/> <member container="?start" child="?photo"/> <triple subject="?photo" predicate="http://purl.org/dc/elements/1.1/title" object="canal"/> </query> this new triple has a static value for the object attribute instead of a variable reference.
...the resulting data will look like the following: (?start = http://www.xulplanet.com/rdf/myphotos, ?photo = http://www.xulplanet.com/ndeakin/images/t/canal.jpg) here is the example.
...for instance, in the original example, we could start at node d and navigate upwards to a and c.
...And 5 more matches
Sorting Results - Archive of obsolete content
for instance, the photos are listed in the same order in this example as they appear in the seq in the datasource.
...<treecol id="name" label="name" sort="?name" flex="1"/> <treecol id="date" label="date" sort="?date" flex="1"/> in this example, the first column will be sorted by the ?name variable and the second column by the ?date variable.
...here is a complete example of sorting a tree.
...And 5 more matches
Special Condition Tests - Archive of obsolete content
for example, the bookmarks toolbar in a web browser might display buttons at the first level, but menus and submenus for content below that.
...here is a previous example, rewritten to use the parent matching syntax: <vbox datasources="people.xml" ref="*" querytype="xml"> <template> <query expr="*"/> <rule parent="vbox"> <action> <groupbox uri="?"> <caption label="?name"/> </groupbox> </action> </rule> <rule> <action> <label uri="?" value="?name"/> </action> </rule> </template> </vbo...
...the result can be seen if you try the example.
...And 5 more matches
Static Content - Archive of obsolete content
tax-ns#type" object="?start"/> <triple subject="?country" predicate="http://purl.org/dc/elements/1.1/title" object="?countrytitle"/> </query> <action> <menupopup> <menuitem uri="?country" label="?countrytitle" value="?country"/> </menupopup> </action> </template> </menulist> the only difference between the previous example and this one is that the menulist element has some additional content added before the template.
...one interesting thing about this example is that only one menupopup will be created, even though there are two in the code, one outside the template and another one inside the action body.
...this becomes useful when using multiple rules and we'll see some examples of this later.
...And 5 more matches
Broadcasters and Observers - Archive of obsolete content
example 1 : source view <command id="my_command" label="open"/> <button command="my_command"/> <checkbox label="open in a new window" command="my_command"/> in this example, the button does not have a label attribute, however it is attached to a command that does.
...we would need to disable the back command on the menu, the back button on the toolbar, the keyboard shortcut (alt+left for example) and any back commands on popup menus.
...for example, a command would be used for an action such as back, cut or delete.
...And 5 more matches
Content Panels - Archive of obsolete content
a good example is a step-by-step wizard that guides you through a number of screens, asking a set of questions.
... iframe example example 1 : source view <toolbox> <toolbar id="nav-toolbar"> <toolbarbutton label="back" /> <toolbarbutton label="forward" /> <textbox id="urlfield" /> </toolbar> </toolbox> <iframe id="content-body" src="http://www.mozilla.org/index.html" flex="1" /> the example here has created a very simple interface for a web browser.
...this example isn't functionally complete.
...And 5 more matches
Creating Dialogs - Archive of obsolete content
var somefile=document.getelementbyid('enterfile').value; window.opendialog("chrome://findfile/content/showdetails.xul","showmore", "chrome",somefile); in this example the dialog showdetails.xul is displayed.
...for example: var fl = window.arguments[0]; document.getelementbyid('thefile').value = fl; this is an effective way to pass values to the new window.
... example dialog source view <?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" ondialogaccept="return dook();" ondialogcancel="return docancel();"> <script> function dook(){ alert("you ...
...And 5 more matches
Tree View Details - Archive of obsolete content
example of hierarchical custom view let's put this together into a simple example that takes an array and constructs a tree from it.
...for example, if the liquids row was opened, the corresponding array from childdata, which in this case contains only the single mercury child, will be inserted into the visibledata array after liquids but before gases.
...in this example, we will only need one function of the box object, to be able to redraw the tree when items are added or removed.
...And 5 more matches
XUL Accesskey FAQ and Policies - Archive of obsolete content
for example, an apply button may have the letter a underlined.
...for example, here's how we add an accesskey to a xul button: <button label="apply instantly" accesskey="a" /> apply instantly - or - <button label="apply instantly" accesskey="a" /> apply instantly in mozilla, we use dtd's for one more layer of abstraction, for purposes of internationalization.
... the above example should say: <button label="apply instantly" accesskey="&applyinstantly.accesskey" /> (always use accesskey instead of akey).
...And 5 more matches
XUL Application Packaging - Archive of obsolete content
required name example: name=testapplication version specifies the application version number.
... required see toolkit version format for version numbering details example: version=0.1 buildid specifies a unique build identifier.
... required example: buildid=20060201 id specifies the unique application id required the application id, like extension ids, can be formatted either like an email applicationname@vendor.tld or a uuid {12345678-1234-1234-1234-123456789abc}.
...And 5 more matches
Obsolete: XPCOM-based scripting for NPAPI plugins - Archive of obsolete content
an interface definition (.idl) file describing the plugin scriptable interface should be added to the project (see example 1).
...this class should also inherit from nsiclassinfo and implement its methods to be able to request all necessary privileges from the mozilla security manager (see example 2).
... two new cases for the above mentioned new variables should be added to the plugin implementation of npp_getvalue (see example 3).
...And 5 more matches
Tiles and tilemaps overview - Game development
this set of articles covers the basics of creating tile maps using javascript and canvas (although the same high level techniques could be used in any programming language.) besides the performance gains, tilemaps can also be mapped to a logical grid, which can be used in other ways inside the game logic (for example creating a path-finding graph, or handling collisions) or to create a level editor.
...these data objects (map object example) should include: tile size: the size of each tile in pixels across / pixels down.
...a high-level algorithm could be: for (var column = 0; column < map.columns; column++) { for (var row = 0; row < map.rows; row++) { var tile = map.gettile(column, row); var x = column * map.tilesize; var y = row * map.tilesize; drawtile(tile, x, y); } } you can read more about this and see an example implementation in square tilemaps implementation: static maps.
...And 5 more matches
Plug-in Development Overview - Gecko Plugin API Reference
a mime type is made up of a major type (such as application or image) and a minor type, for example, image/jpeg.
...until your new mime type is registered, preface its name with "x-", for example, image/x-nwim.
...f the embedded resource of the plug-in dll should contain the following set of string/value pairs: mimetype: for mime types fileextents: for file extensions fileopenname: for file open template productname: for plug-in name filedescription: for description language: for language in use in the mime types and file extensions strings, multiple values are separated by the "|" character, for example: video/quicktime|audio/aiff|image/jpeg the version stamp will be loaded only if it has been created with the language set to "us english" and the character set to "windows multilingual" in your development environment.
...And 5 more matches
Overflowing content - Learn web development
css tries to avoid "data loss" let's consider two examples that demonstrate the default behavior of css when there is overflow.
... the first example is a box that has been restricted by setting a height.
... the second example is a word in a box.
...And 5 more matches
Attribute selectors - Learn web development
presence and value selectors these selectors enable the selection of an element based on the presence of an attribute alone (for example href), or on various different matches against the value of the attribute.
... selector example description [attr] a[title] matches elements with an attr attribute (whose name is the value in square brackets).
... [attr=value] a[href="https://example.com"] matches elements with an attr attribute whose value is exactly value — the string inside the quotes.
...And 5 more matches
Test your skills: Writing Modes and Logical Properties - Learn web development
task one the box in the example is displayed with a horizontal writing mode.
...your example should look like the image below.
... try updating the live code below to recreate the finished example: for assessment or further work purposes, download the starting point for this task to work in your own editor or in an online editor.
...And 5 more matches
Test your skills: Grid Layout - Learn web development
try updating the live code below to recreate the finished example: for assessment or further work purposes, download the starting point for this task to work in your own editor or in an online editor.
... grid layout two in this example we already have a grid defined.
... try updating the live code below to recreate the finished example: additional questions: can you now cause the first item to display on top without changing the order of items in the source?
...And 5 more matches
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.
...And 5 more matches
Debugging HTML - Learn web development
prerequisites: html familiarity, as covered in, for example, getting started with html, html text fundamentals, and creating hyperlinks.
...for example, the following shows an error reported when trying to compile a simple program written in the rust language.
... first, download our debug-example demo and save it locally.
...And 5 more matches
General asynchronous programming concepts - Learn web development
mac users, for example, sometimes experience this as the spinning rainbow-colored cursor (or "beachball" as it is often called).
... let's look at a couple of examples that show what we mean by blocking.
... in our simple-sync.html example (see it running live), we add a click event listener to a button so that when clicked, it runs a time-consuming operation (calculates 10 million dates then logs the final one to the console) and then adds a paragraph to the dom: const btn = document.queryselector('button'); btn.addeventlistener('click', () => { let mydate; for(let i = 0; i < 10000000; i++) { let date = new date(); mydate = date } console.log(mydate); let pelem = document.createelement('p'); pelem.textcontent = 'this is a newly-added paragraph.'; document.body.appendchild(pelem); }); when running the example, open your javascript console then click the button — you'll notice that the paragraph does not appear until after the dates have finished being calculated and the ...
...And 5 more matches
Video and Audio APIs - Learn web development
the htmlmediaelement api part of the html5 spec, the htmlmediaelement api provides features to allow you to control video and audio players programmatically — for example htmlmediaelement.play(), htmlmediaelement.pause(), etc.
...let's go through an example, adding features as we go.
... our finished example will look (and function) something like the following: getting started to get started with this example, download our media-player-start.zip and unzip it into a new directory on your hard drive.
...And 5 more matches
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).
...you already have half of a famous quote inside a variable called quotestart; we would like you to: look up the other half of the quote, and add it to the example inside a variable called quoteend.
... try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor.
...And 5 more matches
Package management basics - Learn web development
a simple example of a useful dependency that your project might need is some code to calculate relative dates as human-readable text.
... for example, if your project relied on webpack with a certain configuration, you'd want to ensure that if you installed that project on another machine or returned to it much later on, the configuration would still work.
...many projects will use npm, and we’ll stick to this in our examples throughout the rest of the module.
...And 5 more matches
The Firefox codebase: CSS Guidelines
some examples to avoid: absolutely positioned elements hardcoded values such as: vertical-align: -2px; .
... example: use option[checked], not option[checked="true"].
... using descendant selectors is good practice for performance when possible: for example: .autocomplete-item[selected] > .autocomplete-item-title would be more efficient than .autocomplete-item[selected] .autocomplete-item-title overriding css before overriding any css rules, check whether overriding is really needed.
...And 5 more matches
Eclipse CDT
to rebuild for changes in an individual directory (for example, to take account of some changes that you yourself made) select "index > freshen all files" on that directory.
... to rebuild the entire index (for example when you pull from mozilla-central) select "index > rebuild" on the project root.
...for example, changing the find next command to cmd-g/ctrl-g is not sufficient.
...And 5 more matches
Displaying Places information using views
the following example uses the built-in tree view to display bookmarks whose titles or urls contain "mozilla".
... <tree type="places" place="place:terms=mozilla&amp;onlybookmarked=1&amp;querytype=1"> <treecols> <treecol id="title" label="my bookmarks" flex="1" primary="true" /> </treecols> <treechildren /> </tree> the next example does the same as the last but uses javascript to set the tree's place attribute: var histserv = cc["@mozilla.org/browser/nav-history-service;1"].
... 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.
...And 5 more matches
Using JavaScript code modules
for example: components.utils.import("resource://app/my_module.jsm"); alert(foo()); // displays "foo" alert(bar.size + 3); // displays "6" alert(dummy); // displays "dummy is not defined" because 'dummy' was not exported from the module note: when you're testing changes to a code module, be sure to change the application's build id (e.g., the version) before your next test run; otherwise...
... the url for a code module as you can see from the example above, you need a url to import a code module.
... (the url in the example is "resource://app/my_module.jsm".) code modules can only be loaded using a chrome: (), resource:, or file: url.
...And 5 more matches
XPCOMUtils.jsm
mycomponent.prototype = { // properties required for xpcom registration: classdescription: "unique text description", classid: components.id("{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}"), contractid: "@example.com/xxx;1", // [optional] custom factory (an object implementing nsifactory).
... classinfo: xpcomutils.generateci( {classid: components.id("{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}"), contractid: "@example.com/xxx;1", classdescription: "unique text description", interfaces: [components.interfaces.nsiobserver, components.interfaces.nsimyinterface, "nsifoo", "nsibar"], flags: ci.nsiclassinfo.singleton}), // ...component implementation...
... example for this is seen at bottom of this page here.
...And 5 more matches
MathML Demo: <mtable> - tables and matrices
as a visual aid, the examples deliberately draw attention to the math axis and the baseline: ----------------------- this is the math axis .....................
... example of \begin{matrix} ---...
... example of \begin{smallmatrix} ---...
...And 5 more matches
Leak-hunting strategies and tips
a good general pattern for finding and fixing leaks is to start with a task that you want not to leak (for example, reading email).
...seeing a leaked globalwindowimpl, nsxulpdglobalobject, nsxbldocglobalobject, or nsxpcwrappedjs is a sign that there could be significant numbers of js objects leaked.) for example, start with bringing up the mail window and closing the window without doing anything.
...see bug 106860 and bug 84136 for examples.
...And 5 more matches
Memory reporting
a simple example imagine a simple string class with the following data fields: class mystring { private: char *mbuffer; // heap-allocated size_t mlen; // ...
...for example, sizeof doesn't appear anywhere.
... an example involving inheritance things are a little trickier when inheritance is involved.
...And 5 more matches
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.
...for example, assume your development machine is called intercept.
...the following examples show the output from commonly used combinations of options.
...And 5 more matches
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.
...for example, assume your development machine is called intercept.
...the following examples show the output from commonly used combinations of options.
...And 5 more matches
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.
... for example, assume your development machine is called intercept.
... the following examples show the output from commonly used combinations of options.
...And 5 more matches
NSS tools : ssltap
MozillaProjectsNSStoolsssltap
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.
...for example, assume your development machine is called intercept.
...the following examples show the output from commonly used combinations of options.
...And 5 more matches
Hacking Tips
step next a few times, so that the "code" variable gets generated print code->code_, which is the address of the code disassembly code read at this address (using x/ni address, where n is the number of instructions you would like to see) here is an example.
...our test run using -s: ./jit_test.py -s $js_shell saved-stacks/async.js insert 'rr' before the shell invocation: rr $js_shell -f $js_src/jit-test/lib/prolog.js --js-cache $js_src/jit-test/.js-cache -e "const platform='linux2'; const libdir='$js_src/jit-test/lib/'; const scriptdir='$js_src/jit-test/tests/saved-stacks/'" -f $js_src/jit-test/tests/saved-stacks/async.js (note that the above is an example; simply setting js_shell and js_src will not work).
...for example in '[rr 28496 607198]reftest test-start | file:///home/bgirard/mozilla-central/tree/image/test/reftest/bmp/bmpsuite/b/wrapper.html?badpalettesize.bmp' z would be 607198.
...And 5 more matches
Index
in particular, it has more and better code examples!
...see js_setprototype or js_setparent in js/src/jsobj.cpp for an example.
... 144 jsprincipalstranscoder advanced, constructor, needsexample, reference, spidermonkey jsprincipalstranscoder is the type of a security callback that can be configured using js_setprincipalstranscoderjsapi 1.8 and earlier or js_setruntimesecuritycallbacksadded in spidermonkey 1.8.1.
...And 5 more matches
Redis Tips
this document is a collection of some examples and tips for using redis, the open-source data structure server.
... things are strings, mostly as you can see from that last example, the values pointed to by keys are strings or they are nil.
... for example, here's some node code: var redis = require("redis"), client = redis.createclient({ ...
...And 5 more matches
Components.utils.Sandbox
system principal to specify the system principal, you can create it using code like: cc["@mozilla.org/systemprincipal;1"].createinstance(ci.nsiprincipal); content principal you can specify a content principal for a particular origin in one of three ways: as an nsiprincipal, for example by using the nodeprincipal property of a dom node as an nsidomwindow, such as that returned by the dom window property as a string uri like "http://www.example.com/" (discouraged) when possible, specify a window or an nsiprincipal object instead of using a string uri.
... example of obtaining content principal from the window: var principal = gbrowser.selectedtab.linkedbrowser.contentprincipal; var sandbox = components.utils.sandbox(principal); expanded principal an expanded principal is specified as an array of the principals it subsumes.
...for example the content principal above can be made expanded/extended like so: var principal = [gbrowser.selectedtab.linkedbrowser.contentprincipal]; // this is now an expanded (aka extended) principal var sandbox = components.utils.sandbox(principal); null principal you can create a null principal using code like: cc["@mozilla.org/nullprincipal;1"].createinstance(ci.nsiprincipal); from firefox 37 onwards, you can also specify the null principal by simply passing null as the principal argument.
...And 5 more matches
nsIChannel
for example, queryinterfacing to nsihttpchannel allows response headers to be retrieved for the corresponding http transaction.
... note: the content type can often be wrongly specified (for example wrong file extension, wrong mime type, wrong document type stored on a server and so on.), and the caller most likely wants to verify with the actual data.
...this is used in the case of a redirect or uri "resolution" (for example resolving a resource: uri to a file: uri) so that the original pre-redirect uri can still be obtained.
...And 5 more matches
nsIWebBrowserPersist
persist_flags_no_conversion 16 do not run the incoming data through a content converter for example to decompress it.
... persist_flags_autodetect_apply_conversion 16384 let the webbrowserpersist decide whether the incoming data is encoded and whether it needs to go through a content converter, for example to decompress it.
... encode_flags_preformatted 16 wrap even if when not doing formatted output (for example for text fields).
...And 5 more matches
nsIZipWriter
(a forward slash is '/') detail: this azipentry is very important, this example demonstrates its usage: var zw = cc['@mozilla.org/zipwriter;1'].createinstance(ci.nsizipwriter); var myzipfile = fu.file('c:\\myzipfile.zip'); //this file will be creatd in c drive var pr = {pr_rdonly: 0x01, pr_wronly: 0x02, pr_rdwr: 0x04, pr_create_file: 0x08, pr_append: 0x10, pr_truncate: 0x20, pr_sync: 0x40, pr_excl: 0x80}; zw.open(xpi, pr.pr_wronly | pr.pr_create_file | pr.pr_truncate); //x...
...pi file is created if not there, if it is there it is truncated/deleted var filetoaddtozip = fileutils.file('c:\\add this file.txt'); var saveinzipas = 'blah.txt'; zw.addentryfile(saveinzipas, ci.nsizipwriter.compression_none, filetoaddtozip, false); in the above example, the file ("add this file.txt") located at "c:\add this file.txt" will be added to the zip file "c:\myzipfile.zip", however in the zip file this file ("add this file.txt") will be named "blah.txt".
... if saveinzipas was equal to "add this file.txt" then in the zip file it will also be named "add this file.txt" further detail: this example gives futher detail on the importance of forward slashes var filetoaddtozip = fileutils.file('c:\\add this file.txt'); var saveinzipas = 'sub folder/blah.txt'; //do not use backward slash for example do not do: 'sub folder\\blah.txt'.
...And 5 more matches
Setting HTTP request headers
// adds "x-hello: world" header to the request httpchannel.setrequestheader("x-hello", "world", false); in the example code above we have a variable named httpchannel which points to an object implementing nsihttpchannel.
...in our example code, the http request header that we added is named x-hello and the value of this http request header is world.
...(in our example, our made up http header is x-hello and not hello because we correctly added the x- in front of our name.) no longer the case: http://tools.ietf.org/html/rfc6648 notifications the question that may be coming to your mind right now is, how do you get the nsihttpchannel when an http request is made.
...And 5 more matches
Using js-ctypes
on windows, for example, you might load the system user32 library like this: var lib = ctypes.open("user32.dll"); on mac os x, you can load the core foundation library from the core foundation framework like this: var corefoundation = ctypes.open("/system/library/frameworks/corefoundation.framework/corefoundation"); the returned object is a library object that you use to declare functions and data types for use with t...
...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.
...And 5 more matches
Plug-in Development Overview - Plugins
a mime type is made up of a major type (such as application or image) and a minor type, for example, image/jpeg.
...until your new mime type is registered, preface its name with "x-", for example, image/x-nwim.
...f the embedded resource of the plug-in dll should contain the following set of string/value pairs: mimetype: for mime types fileextents: for file extensions fileopenname: for file open template productname: for plug-in name filedescription: for description language: for language in use in the mime types and file extensions strings, multiple values are separated by the "|" character, for example: video/quicktime|audio/aiff|image/jpeg the version stamp will be loaded only if it has been created with the language set to "us english" and the character set to "windows multilingual" in your development environment.
...And 5 more matches
Streams - Plugins
seekable streams support random access (for example, local files or http servers that support byte-range requests).
...the browser can write a smaller amount of data if desired or necessary (for example, if only 8k of data is available in a network buffer).
...in the example above, suppose that the plug-in allocates an 8k buffer and returns 8192 from npp_writeready.
...And 5 more matches
URLs - Plugins
for example, a null target does not make sense for some url types (such as mailto).
... if a request is not completed successfully (for example, because the url is invalid or an http server is down), the browser should call npp_urlnotify as soon as possible.
... here's an example of getting a url: a plug-in instance draws a button that acts like a link to another web page.
...And 5 more matches
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.
... audio or photo editor with offline access or local cache (great for performance and speed) the app can write to files in place (for example, overwriting just the id3/exif tags and not the entire file).
...And 5 more matches
HTMLMediaElement.play() - Web APIs
this may happen, for example, if the browser requires the user to explicitly start media playback by clicking a "play" button.
... notsupportederror the media source (which may be specified as a mediastream, mediasource, blob, or file, for example) doesn't represent a supported media format.
...for example, a site should not present a user interface that assumes playback has begun automatically, but should instead update their ui based on whether the returned promise is resolved or rejected.
...And 5 more matches
The HTML DOM API - Web APIs
interacting with the contents of 2d images and the context of an html <canvas>, for example to draw on top of them.
... for example, consider a document with two elements, one of which has two more elements nested inside it: while the document interface is defined as part of the dom specification, the html specification significantly enhances it to add information specific to using the dom in the context of a web browser, as well as to using it to represent html documents specifically.
...properties added by htmlelement include for example hidden and innertext.
...And 5 more matches
Recommended Drag Types - Web APIs
for example: event.datatransfer.setdata("text/plain", "this is text to drag"); dragging text in textboxes and selections on web pages is done automatically by the browser, so you do not need to handle it yourself.
...for example: var dt = event.datatransfer; dt.setdata("text/uri-list", "https://www.mozilla.org"); dt.setdata("text/plain", "https://www.mozilla.org"); as usual, set the text/plain type last, as a fallback for the text/uri-list type.
... for example, this sample text/uri-list data contains two links and a comment: http://www.mozilla.org #a second link http://www.example.com when retrieving a dropped link, ensure you handle when multiple links are dragged, including any comments.
...And 5 more matches
Web-based protocol handlers - Web APIs
an example is the mailto: protocol: <a href="mailto:webmaster@example.com">web master</a> web authors can use a mailto: link when they want to provide a convenient way for users to send an email, directly from the webpage.
...for example: navigator.registerprotocolhandler("web+burger", "http://www.google.co.uk/?uri=%s", "burger handler"); where the parameters are: the protocol.
...for example, http://example.com/homepage.html can register a protocol handler for http://example.com/handle_mailto/%s, but not for http://example.org/handle_mailto/%s.
...And 5 more matches
Pointer Lock API - Web APIs
it is ideal for first person 3d games, for example.
... more than that, the api is useful for any applications that require significant mouse input to control movements, rotate objects, and change entries, for example allowing users to control the viewing angle simply by moving the mouse around without any button clicking.
...other examples include apps for viewing maps or satellite imagery.
...And 5 more matches
RTCIceServers.urls - Web APIs
WebAPIRTCIceServerurls
examples let's look a few examples of varying complexity.
... a single ice server this example creates a new rtcpeerconnection which will use a stun server at stunserver.example.org to negotiate connections.
... mypeerconnection = new rtcpeerconnection({ iceservers: [ { urls: "stun:stunserver.example.org" } ] }); notice that only the urls property is provided; the stun server doesn't require authentication, so this is all that's needed.
...And 5 more matches
Using the Resource Timing API - Web APIs
an application can use the timing metrics to determine, for example, the length of time it takes to fetch a specific resource such as an xmlhttprequest, <svg>, image, script, etc.).
...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.
...And 5 more matches
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.
... there is also a construct you’ll use called a controller — each reader has an associated controller that allows you to control the stream (for example, to cancel it if wished).
...And 5 more matches
Using Touch Events - Web APIs
touchcancel - fired when a touch point has been disrupted in an implementation-specific manner (for example, too many touch points are created).
...this interface's attributes include the state of several modifier keys (for example the shift key) and the following touch lists: touches - a list of all of the touch points currently on the screen.
...another potential factor is time; for example, the time elapsed between the touch's start and the touch's end, or the time lapse between two consecutive taps intended to create a double-tap gesture.
...And 5 more matches
Matrix math for the web - Web APIs
the live examples use a collection of utility functions available under a global object named mdn.
...the easiest example is to multiply a single point by the identity matrix.
... multiplying a matrix and a point in our example code we have defined a function to multiply a matrix and a point — multiplymatrixandpoint(): // point • matrix function multiplymatrixandpoint(matrix, point) { // give a simple variable name to each part of the matrix, a column and row number let c0r0 = matrix[ 0], c1r0 = matrix[ 1], c2r0 = matrix[ 2], c3r0 = matrix[ 3]; let c0r1 = matrix[ 4], c1r1 = matrix[ 5], c2r1 = matrix[ 6], c3r1...
...And 5 more matches
A simple RTCDataChannel sample - Web APIs
in this example, we will open an rtcdatachannel connection linking two elements on the same page.
...we'll cover the mechanics of accomplishing the connection and transmitting and receiving data, but we will save the bits about locating and linking to a remote computer for another example.
...similarly, this example uses arrow functions to simplify syntax.
...And 5 more matches
Writing WebSocket servers - Web APIs
this means that you don't have to bloat your server code with cookie and authentication handlers (for example).
...for example, let's assume that your server is listening on example.com, port 8000, and your socket server responds to get requests at example.com/chat.
...for example, example.com/chat could invoke a multiuser chat app, while /game on the same server might invoke a multiplayer game.
...And 5 more matches
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.
...for example, a classic arcade game such as pac-man takes place on a fixed game map, so the camera remains fixed a set distance above the map, always pointed straight down at the game world.
...And 5 more matches
WindowOrWorkerGlobalScope.setTimeout() - Web APIs
example the following example sets up two simple buttons in a web page and hooks them to the settimeout() and cleartimeout() routines.
... html <p>live example</p> <button onclick="delayedalert();">show an alert box after two seconds</button> <p></p> <button onclick="clearalert();">cancel alert before it happens</button> javascript var timeoutid; function delayedalert() { timeoutid = window.settimeout(window.alert, 2*1000, 'that was really slow!'); } function clearalert() { window.cleartimeout(timeoutid); } result see also cleartimeout() example.
...example: var intervalid = settimeout(function() { myfunc('one', 'two', 'three'); }, 1000); the above example can also be written with the help of an arrow function: var intervalid = settimeout(() => { myfunc('one', 'two', 'three'); }, 1000); yet another possibility is to use function's bind.
...And 5 more matches
Operable - Accessibility
for example, if you press enter/return on a focused button to open an options window, you should be able to close that window again and return to the main content using the keyboard.
...for example, purchases sometimes need to be completed within a time limit for security reasons.
...examples include scrolling text and videos.
...And 5 more matches
system - CSS: Cascading Style Sheets
for example, if the original symbols provided were "◽" and "◾", on each successive pass, they will become "◽◽" and "◾◾", "◽◽◽" and "◾◾◾" and so on.
...] | [ 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: ➀ o...
...ne ➁ two ➂ three 4 four 5 five css <ul> <li>one</li> <li>two</li> <li>three</li> <li>four</li> <li>five</li> </ul> @counter-style circled-digits { system: fixed; symbols: ➀ ➁ ➂; suffix: ' '; } ul { list-style: circled-digits; } result symbolic counter if your browser supports it, this example will render a list like this: a.
...And 5 more matches
Coordinate systems - CSS: Cascading Style Sheets
for example, when a mouse event occurs, the position of the mouse as specified in the event's offsetx and offsety properties are given relative to the top-left corner of the node to which the event has been delivered.
... on a desktop computer, for example, the mouseevent.clientx and mouseevent.clienty properties indicate the position of the mouse cursor at the moment the event occurred, relative to the top-left corner of the browser window.
...this means that the position of a given point within a document will change if the containing window is moved, for example, or if the user's screen geometry changes (by changing display resolution or by adding or removing monitors to their system).
...And 5 more matches
Box alignment in CSS Grid Layout - CSS: Cascading Style Sheets
in the following example, i have four grid areas within my grid.
... in this next example, i am using the align-self property, to demonstrate the different alignment values.
... auto normal start end center stretch baseline first baseline last baseline you can see the same example as used for align-items, below.
...And 5 more matches
Basic concepts of CSS Scroll Snap - CSS: Cascading Style Sheets
the below example demonstrates scroll snapping along the y axis, with scroll-snap-align used on the section element to dictate the point the scrolling should stop.
...in the example below you can change the value between mandatory and proximity to see the effect this has on the scroll experience.
...in the below example you can change the value of scroll-snap-align to see how this changes the scroll behavior.
...And 5 more matches
Shapes From Images - CSS: Cascading Style Sheets
as a simple example, i have an image of a star with a solid red area and an area which is fully transparent.
... in the example below i am using a similar image to the initial example, however in this image the background of the star is not fully transparent, it has a 20% opacity as created in my graphics programme.
... using images with generated content in the above example i have both used the image as the value of shape-outside and also added it to the page.
...And 5 more matches
<color> - CSS: Cascading Style Sheets
currentcolor example html <div style="color:blue; border: 1px dashed currentcolor;"> the color of this text is blue.
...for example, #ff0000 is equivalent to #ff0000ff.
...for example, #f09 is the same color as #ff0099.
...And 5 more matches
Adapting to the new two-value syntax of display - CSS: Cascading Style Sheets
for example, an <h1> or a <p> are block-level by default, and a <span> is inline-level.
...for example to make a heading inline we would use the following css: h1 { display: inline; } more recently we have gained css grid layout and flexbox.
... as an example, when we use display: flex we create a block-level container, with flex children.
...And 5 more matches
font-size - CSS: Cascading Style Sheets
WebCSSfont-size
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...for example, if a parent element is set to 16px and its child element is set to larger, the child element displays larger than the parent element in the page.
...And 5 more matches
User input and controls - Developer guides
modern web user input goes beyond simple mouse and keyboard: think of touchscreens for example.
... 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.
...for example if you want to add controls when any key gets pressed, you need to add an event listener on the window object: window.addeventlistener("keydown", handlekeydown, true); window.addeventlistener("keyup", handlekeyup, true); where handlekeydown and handlekeyup are the functions implementing the controls about the keydown and keyup events.
...And 5 more matches
HTML attribute: accept - HTML: Hypertext Markup Language
examples when set on a file input type, the native file picker that opens up should only enable selecting files of the correct file type.
... <p> <label for="soundfile">select an audio file:</label> <input type="file" id="soundfile" accept="audio/*"> </p> <p> <label for="videofile">select a video file:</label> <input type="file" id="videofile" accept="video/*"> </p> <p> <label for="imagefile">select some images:</label> <input type="file" id="imagefile" accept="image/*" multiple> </p> note the last example allows you to select multiple iamges.
...for example: .jpg, .pdf, or .doc.
...And 5 more matches
HTML attribute reference - HTML: Hypertext Markup Language
formtarget <button>, <input> if the button/input is a submit button (type="submit"), this attribute specifies the browsing context (for example, tab, window, or inline frame) in which to display the response that is received after submitting the form.
...for example used by the server to identify the fields in form submits.
...for example, to set an <input> element's maxlength to 42 using the content attribute, you have to call setattribute("maxlength", "42") on that element.
...And 5 more matches
<input type="color"> - HTML: Hypertext Markup Language
WebHTMLElementinputcolor
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... providing a default color you can update the simple example above to set a default value, so that the color well is pre-filled with the default color and the color picker (if any) will also default to that color: <input type="color" value="#ff0000"> if you don't specify a value, the default is #000000, which is black.
...And 5 more matches
<select>: The HTML Select element - HTML: Hypertext Markup Language
WebHTMLElementselect
the html <select> element represents a control that provides a menu of options: the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... the above example shows typical <select> usage.
...And 5 more matches
<tr>: The Table Row element - HTML: Hypertext Markup Language
WebHTMLElementtr
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...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.
...And 5 more matches
Preloading content with rel="preload" - HTML: Hypertext Markup Language
a simple example might look like this (see our js and css example source, and also live): <head> <meta charset="utf-8"> <title>js and css preload example</title> <link rel="preload" href="style.css" as="style"> <link rel="preload" href="main.js" as="script"> <link rel="stylesheet" href="style.css"> </head> <body> <h1>bouncing balls</h1> <canvas></canvas> <script src="main.js" defer></script> ...
...this example is trivial, as the browser probably discovers the <link rel="stylesheet"> and <script> elements in the same chunk of html as the preloads, but the benefits can be seen much more clearly the later resources are discovered and the larger they are.
... for example: resources that are pointed to from inside css, like fonts or images.
...And 5 more matches
CSP: form-action - HTTP
examples: http://*.example.com: matches all attempts to load from any subdomain of example.com using the http: url scheme.
... mail.example.com:443: matches all attempts to access port 443 on mail.example.com.
... https://store.example.com: matches all attempts to access store.example.com using https:.
...And 5 more matches
CSP: img-src - HTTP
examples: http://*.example.com: matches all attempts to load from any subdomain of example.com using the http: url scheme.
... mail.example.com:443: matches all attempts to access port 443 on mail.example.com.
... https://store.example.com: matches all attempts to access store.example.com using https:.
...And 5 more matches
CSP: navigate-to - HTTP
examples: http://*.example.com: matches all attempts to load from any subdomain of example.com using the http: url scheme.
... mail.example.com:443: matches all attempts to access port 443 on mail.example.com.
... https://store.example.com: matches all attempts to access store.example.com using https:.
...And 5 more matches
A re-introduction to JavaScript (JS tutorial) - JavaScript
see this example: console.log(3 / 2); // 1.5, not 1 console.log(math.floor(3 / 2)); // 1 so an apparent integer is in fact implicitly a float.
... let a; let name = 'simon'; the following is an example of scope with a variable declared with let: // myletvariable is *not* visible out here for (let myletvariable = 0; myletvariable < 5; myletvariable++) { // myletvariable is only visible in here } // myletvariable is *not* visible out here const allows you to declare variables whose values are never intended to change.
... var a; var name = 'simon'; an example of scope with a variable declared with var: // myvarvariable *is* visible out here for (var myvarvariable = 0; myvarvariable < 5; myvarvariable++) { // myvarvariable is visible to the whole function } // myvarvariable *is* visible out here if you declare a variable without assigning any value to it, its type is undefined.
...And 5 more matches
Indexed collections - JavaScript
for example, consider an array called emp, which contains employees' names indexed by their numerical employee number.
...the following example illustrates this behavior.
...for example: let emp = [] emp[0] = 'casey jones' emp[1] = 'phil lesh' emp[2] = 'august west' note: if you supply a non-integer value to the array operator in the code above, a property will be created in the object representing the array, instead of an array element.
...And 5 more matches
The arguments object - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... for example, if a function is passed 3 arguments, you can access them as follows: arguments[0] // first argument arguments[1] // second argument arguments[2] // third argument each argument can also be set or reassigned: arguments[1] = 'new value'; the arguments object is not an array.
...And 5 more matches
Date.parse() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... this function is useful for setting date values based on string values, for example in conjunction with the settime() method and the date object.
...And 5 more matches
Object.defineProperty() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...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.
...And 5 more matches
String.prototype.indexOf() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... so, for example: 'undefined'.indexof() will return 0, as undefined is found at position 0 in the string undefined.
...And 5 more matches
String.prototype.slice() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...(for example, if beginindex is -3 it is treated as str.length - 3.) if beginindex is greater than or equal to str.length, slice() returns an empty string.
...And 5 more matches
delete operator - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... the following snippet gives a simple example: var employee = { age: 28, name: 'abc', designation: 'developer' } console.log(delete employee.name); // returns true console.log(delete employee.age); // returns true // when trying to delete a property that does // not exist, true is returned console.log(delete employee.salary); // returns true non-configurable properties when a property is marked as non-configurable, delete wo...
...And 5 more matches
switch - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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.
...And 5 more matches
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 milliseco...
...for example, #fb0 expands to #ffbb00.
...an rgb start-function is the case-insensitive string "rgb(", for example "rgb(" or "rgb(".
...And 5 more matches
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.c...
... for example, about:blank is often used as a url of new, empty popup windows into which the parent script writes content (e.g.
... for example, assume a script from the document at http://store.company.com/dir/other.html executes the following: document.domain = "company.com"; afterward, the page can pass the same-origin check with http://company.com/dir/page.html (assuming http://company.com/dir/page.html sets its document.domain to "company.com" to indicate that it wishes to allow that - see document.domain for more).
...And 5 more matches
passwords - Archive of obsolete content
you can then use the credentials to access their related service (for example, by logging into a web site).
...for example, if the realm for a credential is "user registration", then its "site" field will look something like: addon:jid0-01mbbfyu0zaxcfub1jykoostkic (user registration) html form credential if a web service uses html forms to authenticate its users, then the corresponding credential is an html form credential.
... so: given a form at http://www.example.com/login with the following html: <form action="http://login.example.com/foo/authenticate.cgi"> <div>please log in.</div> <label>username:</label> <input type="text" name="uname"> <label>password:</label> <input type="password" name="pword"> </form> the corresponding values for the credential (excluding username and password) should be: url: "http://www.example.com...
...And 4 more matches
platform/xpcom - Archive of obsolete content
for example, the add-on below implements the nsiobserver interface to listen for and log all topic notifications: var { class } = require('sdk/core/heritage'); var { unknown } = require('sdk/platform/xpcom'); var { cc, ci } = require('chrome') var observerservice = cc['@mozilla.org/observer-service;1'].
... for example, this add-on defines a subclass of unknown called helloworld that implements a function called hello.
... in this example the helloworld component is available to javascript only, so we use the technique documented under the "using wrappedjsobject" section of how to build an xpcom component in javascript.
...And 4 more matches
preferences/service - Archive of obsolete content
example: var name = "extensions.checkcompatibility.nightly"; require("sdk/preferences/service").set(name, false); get(name, defaultvalue) gets the application preference name.
... example: var name = "extensions.checkcompatibility.nightly"; var nightlycompatchk = require("sdk/preferences/service").get(name); has(name) parameters name : string preference name.
... defaultvalue example: var name = "extensions.checkcompatibility.nightly"; if (require("sdk/preferences/service").has(name)) { // ...
...And 4 more matches
jpm - Archive of obsolete content
for example, in an ubuntu or debian terminal window, enter sudo apt-get install nodejs nodejs-legacy npm.
... for example, to pass the -jsconsole argument to firefox and launch the browser console, try the following: jpm run --binary-args -jsconsole to pass multiple arguments, or arguments containing spaces, quote them: jpm run --binary-args '-url mzl.la -jsconsole' --debug run the add-on debugger attached to the add-on.
... for example, to pass the -jsconsole argument to firefox, which will launch the browser console, try the following: jpm test --binary-args -jsconsole to pass multiple arguments, or arguments containing spaces, quote them: jpm test --binary-args '-url mzl.la -jsconsole' --debug run the add-on debugger attached to the add-on.
...And 4 more matches
Bookmarks - Archive of obsolete content
this article offers examples for how to perform common bookmark management tasks using the bookmarks service.
...for example, to create a new folder in the bookmarks menu: var menufolder = bmsvc.bookmarksmenufolder; // bookmarks menu folder var newfolderid = bmsvc.createfolder(menufolder, "folder name here", bmsvc.default_index); this code locates the bookmarks menu's folder, then creates a new folder named "folder name here" in it.
... var ios = components.classes["@mozilla.org/network/io-service;1"] .getservice(components.interfaces.nsiioservice); var uri = ios.newuri("http://google.com/", null, null); var newbkmkid = bmsvc.insertbookmark(newfolderid, uri, bmsvc.default_index, ""); this example instantiates the nsiioservice and uses it to create an nsiuri referring to the google web site, then calls nsinavbookmarksservice.insertbookmark() to create a new bookmark to google, placing it at the end of the bookmarks folder referenced by newbkmkid.
...And 4 more matches
Finding window handles - Archive of obsolete content
another technique is to use the accessibility framework, see for example http://developer.mozilla.org/en/docs..._of_interfaces another way to find a window handle...
... 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.
... var gdkwindow = ctypes.structtype('gdkwindow'); var gpointer = ctypes.voidptr_t; var gtkwindow = ctypes.structtype('gtkwindow'); var gtkwidget = ctypes.structtype('gtkwidget'); /***** this part is from the gdkwindow* to gtkwindow* example above var gdkwindowptrstring = basewindow.nativehandle; var gdkwinptr = gdkwindow.ptr(ctypes.uint64(gdkwindowptrstring)); var gdk = ctypes.open('libgdk-x11-2.0.so.0'); var gdk_window_get_user_data = gdk.declare('gdk_window_get_user_data', ctypes.default_abi, ctypes.void_t, gdkwindow.ptr, gpointer.ptr); var gptr = gpointer(); gdk_window_get_user_data(gdkwinptr, gptr.address()); var gtkwinptr = c...
...And 4 more matches
Miscellaneous - Archive of obsolete content
t application and version // get the name of the application running us services.appinfo.name; // returns "firefox" for firefox services.appinfo.version; // returns "2.0.0.1" for firefox version 2.0.0.1 retrieving the version of an extension as specified in the extension's install.rdf components.utils.import("resource://gre/modules/addonmanager.jsm"); addonmanager.getaddonbyid("extension-guid@example.org", function(addon) { // this is an asynchronous callback function that might not be called immediately alert("my extension's version is " + addon.version); }); restarting firefox/thunderbird/seamonkey_2.0 for firefox 3 see onwizardfinish around here: http://mxr.mozilla.org/seamonkey/sou...pdates.js#1639 for firefox 2 see around here: http://mxr.mozilla.org/mozilla1.8/so...pdates.js#16...
... example for firefox: services.startup.quit(services.startup.eforcequit|services.startup.erestart); mouse and keyboard detecting mouse wheel events when scrolling the mouse wheel on an element, the dommousescroll event fires.
...r currentvalue = element.value; var beforetext = currentvalue.substring(0, element.selectionstart); var aftertext = currentvalue.substring(element.selectionend, currentvalue.length); element.value = beforetext + snippet + aftertext; element.focus(); //put the cursor after the inserted text element.setselectionrange(selectionend, selectionend); } inserttext(document.getelementbyid("example"), "the text to be inserted"); disabling javascript programmatically // disable js in the currently active tab from the context of browser.xul gbrowser.docshell.allowjavascript = false; if this isn't your browser, you should save the value and restore it when finished.
...And 4 more matches
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.
... for the maxversion it is generally permissible to use a * in place of the minor version of the application you support, for example 2.0.0.* would mean that you support any minor update to version 2 of the application.
...below is an example update manifest.
...And 4 more matches
Security best practices in extensions - Archive of obsolete content
for example, if you load a chrome url, this means the content has been registered with firefox and has full access.
... content from a domain (such as http://www.example.com) can only access that same domain.
...there are ways to get around the content/chrome security barrier, if for example, you want a web page to send a notification to the add-on (or vice versa).
...And 4 more matches
Supporting private browsing mode - Archive of obsolete content
var pbs = components.classes["@mozilla.org/privatebrowsing;1"] .getservice(components.interfaces.nsiprivatebrowsingservice); var inprivatebrowsingmode = pbs.privatebrowsingenabled; if (!inprivatebrowsingmode) { /* save private information */ } in the above example, we only save the user's private information if not in private browsing mode.
...var pbs = components.classes["@mozilla.org/privatebrowsing;1"] .getservice(components.interfaces.nsiprivatebrowsingservice); var oldprivatemode = pbs.privatebrowsingmode; pbs.privatebrowsingenabled = true; /* this is all private */ pbs.privatebrowsingenabled = oldprivatemode; in this example, we save the current state of the private browsing mode setting in the oldprivatemode variable, then turn on private browsing by setting its value to true.
... this allows us to, for example, work with the places database without affecting its contents.
...And 4 more matches
Anonymous Content - Archive of obsolete content
for example, the html file upload control appears in most browsers as a composite widget consisting of a text field and a button.
... for example, on the html file upload control, the anonymous textfield can be set up to automatically inherit the value attribute from the bound element.
... <xbl:binding id="fileuploadcontrol"> <xbl:content> <html:input type="text" xbl:inherits="value"/> <html:input type="button" value="browse..."/> </xbl:content> </xbl:binding> each entry in the inherits list can either simply list an attribute (such as value in the example above), or it can specify an = separated pair consisting of the attribute on the anonymous content that should be tied to the attribute on the bound element.
...And 4 more matches
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.
...todo: simple example of a xul document and a tree you can think of a document as an in-memory representation of valid html or well-formed xml such as xhtml or xul.
...examples: using dom methods this section demonstrates the use of appendchild(), createelement(), insertbefore(), and removechild() dom methods.
...And 4 more matches
Tooltips - Archive of obsolete content
<toolbarbutton label="back" tooltiptext="go back one page"/> in this example, a back button on a toolbar is given additional text to appear on a tooltip.
...for example, in the following, a toolbar has a tooltip set for it.
...it conveys no additional information to the user, so it shouldn't be used as in this example.
...And 4 more matches
Anonymous Content - Archive of obsolete content
declaring scrollbar example the example below shows how a scrollbar might be declared (it has been simplified a bit from the real thing): <bindings xmlns="http://www.mozilla.org/xbl" xmlns:xul="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <binding id="scrollbarbinding"> <content> <xul:scrollbarbutton type="decrement"/> <xul:slider flex="1"> <xul:thumb/> </xul:slid...
...filename input field example another example, this time for a field for entering a filename: <binding id="fileentry"> <content> <textbox/> <button label="browse..."/> </content> </binding> attaching this binding to an element will cause it to contain a field for entering text, followed by a browse button.
...for example, take this xul fragment, assuming it is bound to the scrollbar xbl earlier: <scrollbar/> <scrollbar> <button label="overridden"/> </scrollbar> the first scroll bar, because it has no content of its own, will have its content generated from a binding definition declared in an xbl file.
...And 4 more matches
Box Model Details - Archive of obsolete content
here, we'll find out some more details with some examples.
...example 1 : source view <hbox flex="1"> <button label="left" style="min-width: 100px;" flex="1"/> <spacer flex="1"/> <button label="right" style="min-width: 100px;" flex="1"/> </hbox> in the example above, all three elements will resize themselves as they are all flexible.
...example 2 : source view <hbox flex="1" align="top"> <button label="left" style="min-width: 100px;" flex="1"/> <spacer flex="1"/> <button label="right" style="min-width: 100px;" flex="1"/> </hbox> summary of the box model to achieve complicated layouts, you will generally need to add nested boxes, specify minimum and maximum sizes on some elements, and make certain elements flexible.
...And 4 more matches
Input Controls - Archive of obsolete content
the following example shows some textboxes: example 1 : source view <label control="some-text" value="enter some text"/> <textbox id="some-text"/> <label control="some-password" value="enter a password"/> <textbox id="some-password" type="password" maxlength="8"/> multiline textbox the textbox examples above will create text inputs that can only be used for entering one line of text.
... example 2 : source view <textbox multiline="true" value="this is some text that could wrap onto multiple lines."/> like the html textarea, you can use the rows and cols attributes to set the size.
... our find files example let's add a search entry field to the find file dialog.
...And 4 more matches
Skinning XUL Files by Hand - Archive of obsolete content
css2, for example, gives you control over the absolute positioning of any element within its parent element.
...for example, when a button is defined as follows: <button class="plain" label="push me" /> then the following very simple style definition applies to that button.
...if you create a style in your custom stylesheet for a button with a particular id, for example, some of the more basic style information for buttons in the global skin may take precedence over your new style and cause it not to be applied.
...And 4 more matches
Styling a Tree - Archive of obsolete content
set the property on a row or cell, as in the following example: <treerow properties="makeitblue"> css selectors for the tree the style sheet can take this property and use it to change the appearance of the row for unread messages or labels.
...the example below sets the background color to grey for rows that have the 'readonly' and 'unread' properties.
...this property, along with the even property allow you to set, for example, alternating colors for each row.
...And 4 more matches
The Box Model - Archive of obsolete content
thus, the two lines below are equivalent: <vbox></vbox> <box orient="vertical"></box> the following example shows how to place three buttons vertically.
... example 1 : source view <vbox> <button id="yes" label="yes"/> <button id="no" label="no"/> <button id="maybe" label="maybe"/> </vbox> the three buttons here are oriented vertically as was indicated by the box.
...login prompt example you can add as many elements as you want inside a box, including other boxes.
...And 4 more matches
Using nsIXULAppInfo - Archive of obsolete content
this is useful, for example, for extensions that support several mozilla-based applications or several versions of a single application.
...the following sections provide a few examples of using nsixulappinfo from javascript.
...for example, one of unfrozen functions you're relying on was changed.
...And 4 more matches
XUL Event Propagation - Archive of obsolete content
when the mouse moves over the button, for example, the "hover" event is raised.
...this is the case in the example code in the diagram, where the onclick event listener for the button element handles the click event by displaying a simple alert dialog: <button value="click me" onclick="alert('thank you')" /> the opposite of event bubbling is event capturing.
...in the example above, when the menuitem raises the "command" event, indicating that it has been selected, the menupopup, the menu itself, the parent box, or the root window element itself can all take advantage of this.
...And 4 more matches
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 e...
...for example, for a menuitem in a menu you can add the following css rule when you want to use the value none: menupopup > menuitem, menupopup > menu { max-width: none; } default type: boolean if true, the tooltip is used as the default popup for displaying tooltips in the window.
...And 4 more matches
Creating XULRunner Apps with the Mozilla Build System - Archive of obsolete content
for the purposes of this article i'm using dave townsend's mccoy as an example.
...for example, you may be fixing bugs in xulrunner, applying patches from bugzilla that aren't yet checked into the main repository or making your own changes to deploy as part of a customized xulrunner build.
...for example, you might want to set it to "xulrunner" now and run make to ensure that everything is set up correctly so far.
...And 4 more matches
Building a Theme - Archive of obsolete content
an example of the content within a typical xpi file for a theme: example.xpi: /install.rdf /chrome.manifest /preview.png /icon.png /chrome/ browser/ communicator/ global/ mozapps/ we'll want to create a file structure similar to the one above for our t...
... create the install manifest open the file called install.rdf that you created at the top of your extension's folder hierarchy and put this inside: <?xml version="1.0"?> <rdf xmlns="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:em="http://www.mozilla.org/2004/em-rdf#"> <description about="urn:mozilla:install-manifest"> <em:id>sample@example.net</em:id> <em:version>1.0</em:version> <em:type>4</em:type> <!-- target application this theme can install into, with minimum and maximum supported versions.
...-13a3a9e97384}</em:id> <em:minversion>29.0</em:minversion> <em:maxversion>39.*</em:maxversion> </description> </em:targetapplication> <!-- front end metadata --> <em:name>my theme</em:name> <em:internalname>sample</em:internalname> <em:description>a test extension</em:description> <em:creator>your name here</em:creator> <em:homepageurl>http://www.example.com/</em:homepageurl> </description> </rdf> sample@example.net - the id of the extension.
...And 4 more matches
Audio for Web games - Game development
for more passive audio auto play, for example background music that starts as soon as a game loads, one trick is to detect any user initiated event and start playback then.
... concurrent audio playback a requirement of many games is the need to play more than one piece of audio at the same time; for example, there might be background music playing along with sound effects for various things happening in the game.
... note: concurrent audio playback is tested using our concurrent audio test example, where we attempt to play three pieces of audio at the same time using the standard audio api.
...And 4 more matches
Hoisting - MDN Web Docs Glossary: Definitions of Web-related terms
conceptually, for example, a strict definition of hoisting suggests that variable and function declarations are physically moved to the top of your code, but this is not in fact what happens.
... learn more technical example one of the advantages of javascript putting function declarations into memory before it executes any code segment is that it allows you to use a function before you declare it in your code.
... for example: function catname(name) { console.log("my cat's name is " + name); } catname("tiger"); /* the result of the code above is: "my cat's name is tiger" */ the above code snippet is how you would expect to write the code for it to work.
...And 4 more matches
Images, media, and form elements - Learn web development
in the example below we have two boxes, both 200 pixels in size: one contains an image which is smaller than 200 pixels — it is smaller than the box and doesn't stretch to fill it.
... try adding max-width: 100% to the <img> element in the example above.
...for example, you may want to size an image so it completely covers a box.
...And 4 more matches
Type, class, and ID selectors - Learn web development
in the example below we have used the span, em and strong selectors.
...in the following example we have used the universal selector to remove the margins on all elements.
...for example, if i wanted to select the first child of any descendant element of <article> , no matter what element it was, and make it bold, i could use the :first-child selector, which we will learn more about in the lesson on pseudo-classes and pseudo-elements, as a descendant selector along with the <article> element selector: article :first-child { } this could be confused however with article:first-...
...And 4 more matches
Test your skills: Flexbox - Learn web development
the finished example should look like the image below.
... try updating the live code below to recreate the finished example: for assessment or further work purposes, download the starting point for this task to work in your own editor or in an online editor.
... try updating the live code below to recreate the finished example: additional questions: can you now make the first item twice the size of the other items?
...And 4 more matches
Test your skills: floats - Learn web development
try updating the live code below to recreate the finished example: for assessment or further work purposes, download the starting point for this task to work in your own editor or in an online editor.
... float two in this example the element with a class of float should be floated left.
... try updating the live code below to recreate the finished example: for assessment or further work purposes, download the starting point for this task to work in your own editor or in an online editor.
...And 4 more matches
Supporting older browsers - Learn web development
you should also consider the type of devices and the way people use your site, for example, you may expect a higher than an average number of mobile devices.
...for example, take a look at the page for grid-template-columns.
...this means that there is a definition for what happens if a floated item, for example, is also a grid item using css grid layout.
...And 4 more matches
How much does it cost to do something on the Web? - Learn web development
many editors are free, for example atom, brackets, bluefish, textwrangler, eclipse, netbeans, and visual studio code.
...for example, sublime text is cheap, but comes with many free plugins that can greatly extend its functionality.
... media editors if you want to include video or audio into your website, you can either embed online services (for example youtube, vimeo, or dailymotion), or include your own videos (see below for bandwidth costs).
...And 4 more matches
Mozilla splash page - Learn web development
alternatively, you could use an online tool such as glitch to create your example.
... note: the example html file contains quite a lot of css, to style the page.
... 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.
...And 4 more matches
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).
... try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor.
...are you for real?" try updating the live code below to recreate the finished example.
...And 4 more matches
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.
... try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor.
...And 4 more matches
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.
... try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor.
...And 4 more matches
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).
... try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor.
... try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor.
...And 4 more matches
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).
... try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor.
... try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor.
...And 4 more matches
Introduction to client-side frameworks - Learn web development
working directly with the dom, as in this example, requires understanding many things about how the dom works: how to make elements; how to change their properties; how to put elements inside of each other; how to get them on the page.
...the biggest example of this is in client-side routing, as mentioned earlier.
...this rfc serves as a great example of the kind of research you should do for yourself when planning to use a front-end framework.
...And 4 more matches
Accessibility information for UI designers and developers
calculating this ratio is easiest done with a tool, for example lea verou's contrast ratio.
...for example, add text labels or texture in addition to color differences.
... for example, in this chart, it helps to add labels besides the colored chart lines:people who cannot see the difference between the colors, can use the labels instead.
...And 4 more matches
Creating reftest-based unit tests
for example, the html 4.01 specification at the w3c specifies that text inside of a <blockquote> will be indented, but it does not specify the number of pixels of the indentation.
... creating reftest-based unit tests your first reftest it is a silly example, but this will step you through creating your first reftest.
...here is an example.
...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
How to implement a custom autocomplete search component
because creating an xpcom component in order to build a custom autocomplete source can be enough to discourage some developers, below is an example javascript xpcom component called "simple-autocomplete" that implements the necessary interfaces.
... 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.
...so, get a uuid from http://www.famkruithof.net/uuid/uuidgen, for example, and paste it in.
...And 4 more matches
CustomizableUI.jsm
for example, if there is a need to create a button with dynamically assignable tooltip, the node for static tooltip should be deleted as soon as the widget will be created, and node-reference to popup tooltip element has to be added.
... examples createwidget - button type this is likely the code you need for your widget.
...this example here uses nsistylesheetservice to do so.
...And 4 more matches
Using the viewport meta tag to control layout on mobile browsers
for example, if a mobile screen has a width of 640px, pages might be rendered with a virtual viewport of 980px, and then it will be shrunk down to fit into the 640px space.
... enter viewport meta tag however, this mechanism is not so good for pages that are optimized for narrow screens using media queries — if the virtual viewport is 980px for example, media queries that kick in at 640px or 480px or less will never be used, limiting the effectiveness of such responsive design techniques.
...for example, safari's documentation says the content is a "comma-delimited list," but existing browsers and web pages use any mix of commas, semicolons, and spaces as separators.
...And 4 more matches
Profiling with the Firefox Profiler
so, for example, when a thread is blocked, like 'geckomain [tab]', on a thread like 'geckomain [default]', we can see what's occurring on the latter thread that is preventing it from responding to the former.
...there are os-specific waiting functions like ntwaitformultipleobjects seen in the example above taken on windows or mach_msg_trap on macos.
...for example:in the results above we can see that we're spending ~287 milliseconds in startup::xre_initchildprocess, 194 ms of which are spent in pvsync::msg_notify and all child functions that it calls.
...And 4 more matches
TPS Tests
te the environment source %path%/bin/activate run some tests note that the testfile is not a path, it should only be the filename from services/sync/tests/tps/ runtps --debug --testfile %test_file_name% --binary %firefox_binary_path% additionally, omitting a --testfile parameter will cause it to run all tps tests listed in services/sync/tests/tps/all_tests.json an example on osx, for running just the test_sync.js testfile against a locally built firefox (where the mozconfig set the objdir to obj-ff-artifact): runtps --debug --testfile test_sync.js --binary obj-ff-artifact/dist/nightly.app/contents/macos/firefox running tps against stage, or dev fxa tps can be configured using the $tps_venv_path/config.json file.
...for example, a (partial) tps config for testing against stage might look like: { // ...
...} note that in this example, the foobar@restmail.net account must be registered on stage, otherwise authentication will fail (and the whole test will fail as well.
...And 4 more matches
Manipulating bookmarks using Places
this article offers examples for how to perform common bookmark management tasks using the bookmarks service.
...for example, to create a new folder in the bookmarks menu: var menufolder = bmsvc.bookmarksmenufolder; // bookmarks menu folder var newfolderid = bmsvc.createfolder(menufolder, "folder name here", bmsvc.default_index); this code locates the bookmarks menu's folder, then creates a new folder named "folder name here" in it.
... var ios = components.classes["@mozilla.org/network/io-service;1"] .getservice(components.interfaces.nsiioservice); var uri = ios.newuri("http://google.com/", null, null); var newbkmkid = bmsvc.insertbookmark(newfolderid, uri, bmsvc.default_index, ""); this example instantiates the nsiioservice and uses it to create an nsiuri referring to the google web site, then calls nsinavbookmarksservice.insertbookmark() to create a new bookmark to google, placing it at the end of the bookmarks folder referenced by newbkmkid.
...And 4 more matches
Component Internals
a web browser that embeds gecko, for example, may initialize xpcom at startup through the embedding apis.
...this is how the api is used, for example, in the gecko runtime environment (gre).
...an application, for example, could provide a "registration-less" component directory whose components are automatically registered at startup and unregistered at shutdown.
...And 4 more matches
Setting up the Gecko SDK
for example, the headers for networking are all located in the necko directory, and the headers that xpcom requires are in the xpcom directory.
...(this example uses "samplegeckoproject" as the project name and c:\ as its location.).
... assuming you are using the example location for your project, these paths are the following: c:\gecko-sdk\embedstring\include c:\gecko-sdk\xpcom\include c:\gecko-sdk\nspr\include c:\gecko-sdk\string\include under the c++ language category, disable exception handling.
...And 4 more matches
nsIFile
for example, c:\ does not have a parent.
... example, this could return "/home/user/foo.txt" or "c:\images\my.jpeg" permissions unsigned long the value of this attribute is a unix-style file permission mask for this nsifile.
...there are problems that affect platforms on which a path does not fully specify a file because two volumes can have the same name (for example mac).
...And 4 more matches
nsIIOService
inherits from: nsisupports last changed in gecko 1.2 this interface duplicates many of the nsiprotocolhandler methods in a protocol handler independent way (for example newuri() inspects the scheme in order to delegate creation of the new uri to the appropriate protocol handler).
...for example for an image load, it's the document in which the image will be loaded.
...for example for loads from a webworker, pass the principal of that worker.
...And 4 more matches
nsITextInputProcessor
for example, the implementation of this interface manages modifier state and composition state, initializes dom events from minimum information, and doesn't dispatch some events if they are not necessary.
... the following example sets "foo-bar-buzz", "bar" is selected clause to convert, and caret position is the end of the selected clause: // first, sets composition string.
...for example: tip.setpendingcompositionstring("a"); tip.appendclausetopendingcomposition("a".length, tip.attr_raw_clause); tip.setcaretposition("a".length); // this means that the first composition character is inputted by a keypress of "a" key.
...And 4 more matches
nsITreeView
cyclecell() called on the view when a cell in a non-selectable cycling column (for example, unread/flag/and so on.) is clicked.
... see getrowproperties() for an example.
... see getrowproperties() for an example.
...And 4 more matches
nsIWindowMediator
example: of window listener object and how to register then unregister.
... this example below waits for listens to when a window opens, and then after that window opens it adds event listener to listen to when the window completes loading, after that it fires a function.
...inish loading let domwindow = awindow.queryinterface(ci.nsiinterfacerequestor).getinterface(ci.nsidomwindowinternal || ci.nsidomwindow); domwindow.addeventlistener("load", function () { domwindow.removeeventlistener("load", arguments.callee, false); //this removes this load function from the window //window has now loaded now do stuff to it //as example this will add a function to listen to tab select and will fire alert in that window if (domwindow.gbrowser && domwindow.gbrowser.tabcontainer) { domwindow.gbrowser.tabcontainer.addeventlistener('tabselect', function () { domwindow.alert('tab was selected') }, false); } }, false); }, onclosewindow: function...
...And 4 more matches
nsIZipReader
example demonstrating this function: list contents of xpi and read file contents extract() extracts a zip entry into a local file specified by outfile.
...for example, because '*' matches any string and '*z*' matches any string containing a 'z', '*~*z*' will match all strings except those containing a 'z'.
... example demonstrating this function: list contents of xpi and read file contents getentry() returns a nsizipentry describing a specified zip entry.
...And 4 more matches
Declaring types
for example, to define a new 32-bit integer variable with the value 5: var i = ctypes.int32_t(5); you can then pass a pointer to this value to a c function that requires a pointer to a 32-bit integer, like this: some_c_function(i.address()); declaring new primitive types there are times when you want to create new types that are simply new names for existing primitive types.
... for example, on windows, you may wish to be able to use the windows-standard dword type name for unsigned 32-bit integers.
... { fieldn: typen } ] example for example, to support the c tm structure using js-ctypes, you would use the following code: const struct_tm = new ctypes.structtype("tm", [ { "tm_sec": ctypes.int }, { "tm_min": ctypes.int }, { "tm_hour": ctypes.int }, { "tm_mday": ctypes.int }, { "tm_mon": ctypes.in...
...And 4 more matches
Edit fonts - Firefox Developer Tools
they are used by a descendant of the inspected element, for example, when it is a container for other elements which have text content with fonts applied.
... example: if 1rem is equivalent to 10 pixels, when you change the unit of measurement from rem to px, 2rem becomes 20px.
... example: if the font is 20 pixels high and the line-height is 1.5em, when you change the unit of measure from em to px, the value will become 30px.
...And 4 more matches
Examine and edit CSS - Firefox Developer Tools
in the following example, a spelling error, "background-colour" instead of "background-color" has made the rule invalid: rule display it displays each rule as in a stylesheet, with a list of selectors followed by a list of property:value; declarations.
...for example, searching for "color" will highlight declarations containing border-bottom-color and background-color as well as just color.: if you enclose the search query in backticks, like this: `color`, the search is restricted to exact matches: expanding shorthand properties shorthand properties can be expanded to display their related longhand properties by clicking the arrow besides them.
...for example: viewing and changing classes on an element with an element selected in the html pane, you can click the .cls button in the rules pane toolbar, to display the classes defined on that element.
...And 4 more matches
Waterfall - Firefox Developer Tools
so if you see a sign of a performance problem - a drop in the frame rate, for example - you can go to the waterfall to see what the browser was doing at that point in the recording.
... event type for example, "click" or "message".
... event phase for example, "target" or "capture".
...And 4 more matches
Console messages - Firefox Developer Tools
synchronous and asynchronous reflows if a change is made that invalidates the current layout — for example, the browser window is resized or some javascript modifies an element's css — the layout is not recalculated immediately.
...for example, code like this will cause an immediate, synchronous, reflow, when it calls window.getcomputedstyle(thing).height: var thing = document.getelementbyid("the-thing"); thing.style.display = "inline-block"; var thingheight = window.getcomputedstyle(thing).height; because of this, it's a good idea to avoid interleaving write and read calls to an element's styles when manipulating the dom, because ev...
...for example, "warnings (25)".
...And 4 more matches
AudioNode - Web APIs
WebAPIAudioNode
examples include: an audio source (e.g.
...the exact processing done varies from one audionode to another but, in general, a node reads its inputs, does some audio-related processing, and generates new values for its outputs, or simply lets the audio pass through (for example in the analysernode, where the result of the processing is accessed separately).
...for example, if your graph has a latency of 500ms, when the source node plays a sound, it will take half a second until that sound can be heard on your speakers (or even longer because of latency in the underlying audio device).
...And 4 more matches
Background Tasks API - Web APIs
for example, anything which might affect layout should be avoided.
... example in this example, we'll take a look at how you can use requestidlecallback() to run time-consuming, low-priority tasks during time the browser would otherwise be idle.
... in addition, this example demonstrates how to schedule updates to the document content using requestanimationframe().
...And 4 more matches
Document.cookie - Web APIs
WebAPIDocumentcookie
;domain=domain (e.g., 'example.com' or 'subdomain.example.com').
... 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.
...startswith('test2')) .split('=')[1]; function alertcookievalue() { alert(cookievalue); } <button onclick="alertcookievalue()">show cookie value</button> example #3: do something only once in order to use the following code, please replace all occurrences of the word dosomethingonlyonce (the name of the cookie) with a custom name.
...And 4 more matches
Document.evaluate() - Web APIs
WebAPIDocumentevaluate
null is the most common and will create a new xpathresult example var headings = document.evaluate("/html/body//h2", document, null, xpathresult.any_type, null); /* search the document for all h2 elements.
...*/ var thisheading = headings.iteratenext(); var alerttext = "level 2 headings in this document are:\n"; while (thisheading) { alerttext += thisheading.textcontent + "\n"; thisheading = headings.iteratenext(); } alert(alerttext); // alerts the text of all h2 elements note, in the above example, a more verbose xpath is preferred over common shortcuts such as //h2.
... generally, more specific xpath selectors as in the above example usually gives a significant performance improvement, especially on very large documents.
...And 4 more matches
Dragging and Dropping Multiple Items - Web APIs
this function similarly to setdata() var dt = event.datatransfer; dt.mozsetdataat("text/plain", "data to drag", 0); dt.mozsetdataat("text/plain", "second data to drag", 1); this example adds two items to be dragged.
...for example: var dt = event.datatransfer; dt.mozsetdataat("text/uri-list", "url1", 0); dt.mozsetdataat("text/plain", "url1", 0); dt.mozsetdataat("text/uri-list", "url2", 1); dt.mozsetdataat("text/plain", "url2", 1); dt.mozsetdataat("text/uri-list", "url3", 2); dt.mozsetdataat("text/plain", "url3", 2); // [item1] data=url1, index=0 // [item2] data=url2, index=1 // [item3] data=url3, index=2 after ...
...the following example retrieves a set of files being dragged and adds them to an array.
...And 4 more matches
PaymentAddress - Web APIs
the exact size and content varies by country or location and can include, for example, a street name, house number, apartment number, rural delivery route, descriptive instructions, or post office box number.
...some examples of valid country values: "us", "gb", "cn", or "jp".
... paymentaddress.dependentlocality read only a domstring giving the dependent locality or sublocality within a city, for example, a neighborhood, borough, district, or uk dependent locality.
...And 4 more matches
Using the Payment Request API - Web APIs
this article is a guide to making use of the payment request api, with examples and suggested best practices.
... so for example, you could create a new paymentrequest instance like so: var request = new paymentrequest(buildsupportedpaymentmethoddata(), buildshoppingcartdetails()); the functions invoked inside the constructor simply return the required object parameters: function buildsupportedpaymentmethoddata() { // example supported payment methods: return [{ supportedmethods:...
... 'basic-card', data: { supportednetworks: ['visa', 'mastercard'], supportedtypes: ['debit', 'credit'] } }]; } function buildshoppingcartdetails() { // hardcoded for demo purposes: return { id: 'order-123', displayitems: [ { label: 'example item', amount: {currency: 'usd', value: '1.00'} } ], total: { label: 'total', amount: {currency: 'usd', value: '1.00'} } }; } starting the payment process once the paymentrequest object has been created, you call the paymentrequest.show() method on it to initiate the payment request.
...And 4 more matches
Selection.setBaseAndExtent() - Web APIs
so for example, if the value is 0 the whole node is included.
...so for example, if the value is 0 the whole node is excluded.
...for example, shift + ➡︎ would cause the selection to narrow from the beginning rather than grow at the end.
...And 4 more matches
Using server-sent events - Web APIs
for example: const evtsource = new eventsource("ssedemo.php"); if the event generator script is hosted on a different origin, a new eventsource object should be created with both the url and an options dictionary.
... for example, assuming the client script is on example.com: const evtsource = new eventsource("//api.example.com/ssedemo.php", { withcredentials: true } ); once you've instantiated your event source, you can begin listening for messages from the server by attaching a handler for the message event: evtsource.onmessage = function(event) { const newelement = document.createelement("li"); const eventlist = document.getelementbyid("list"); newelement.innerhtml = "message: " + event.data; eventlist.appendchild(newelement); } this code listens for incoming messages (that is, notices from the server that do not have an event field on them) and appends the message text to a list in the document's html.
...this limit is per browser + domain, which means that you can open 6 sse connections across all of the tabs to www.example1.com and another 6 sse connections to www.example2.com (per stackoverflow).
...And 4 more matches
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.
... the following example uses the default value of scope (by omitting it).
...And 4 more matches
Touch events - Web APIs
touchlist represents a group of touches; this is used when the user has, for example, multiple fingers on the surface at the same time.
... example this example tracks multiple touchpoints at a time, allowing the user to draw in a <canvas> with more than one finger at a time.
...its responsibility in this example is to update the cached touch information and to draw a line from the previous position to the current position of each touch.
...And 4 more matches
Background audio processing using AudioWorklet - Web APIs
throughout the remainder of this article, we'll look at these steps in more detail, with examples (including working examples you can try out on your own).
... the example code found on this page is derived from this working example which is available on glitch.
... the example creates an oscillator node and adds white noise to it using an audioworkletnode before playing the resulting sound out.
...And 4 more matches
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.
... basic concepts to extract data from your audio source, you need an analysernode, which is created using the audiocontext.createanalyser() method, for example: var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); var analyser = audioctx.createanalyser(); this node is then connected to your audio source at some point between your source and your destination, for example: source = audioctx.createmediastreamsource(stream); source.connect(analyser); analyser.connect(distortion); distortion.connect(audioctx.destination); note: you don't need to connect the analyser's output to another node for it to work, as long as the input is connected to the source, either directly or via another node.
... so for example, say we are dealing with an fft size of 2048.
...And 4 more matches
Generating HTML - Web APIs
the second example will transform the input document (example2.xml), which again contains information about an article, into an html document.
... figure 2 xml file :(example2.xml)view example | view source xml document (example2.xml): <?xml version="1.0"?> <?xml-stylesheet type="text/xsl" href="example2.xsl"?> <myns:article xmlns:myns="http://devedge.netscape.com/2002/de"> <myns:title>my article</myns:title> <myns:authors> <myns:author company="foopy corp.">mr.
... figure 3 : xsl stylesheet with 2 namespaces (example2.xsl) xsl stylesheet (example2.xsl): <?xml version="1.0"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/xsl/transform" xmlns:myns="http://devedge.netscape.com/2002/de"> <xsl:output method="html"/> ...
...And 4 more matches
Using the alert role - Accessibility
the alert role is most useful for information that requires the user's immediate attention, for example: an invalid value was entered into a form field the user's login session is about to expire the connection to the server was lost, local changes will not be saved because of its intrusive nature, the alert role must be used sparingly and only in situations where the user's immediate attention is required.
... 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.
... <h2 role="alert">your form could not be submitted because of 3 validation errors.</h2> example 2: dynamically adding an element with the alert role this snippet dynamically creates an element with an alert role and adds it to the document structure.
...And 4 more matches
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.
...aria-details has been updated so that it can support multiple ids — this makes sense, for example you can easily envisage having multiple comments relating to the same bit of text.
...And 4 more matches
Perceivable - Accessibility
for example, it can be spoken by a screenreader, converted to large print, or represented on a braille display.
... 1.2.8 provide an alternative for prerecorded media (aaa) for all content that features video, a descriptive text transcript should be provided, for example a script of the movie you are watching.
... 1.2.9 provide a transcript for live audio (aaa) for any live audio content being broadcast, a descriptive text should be provided, for example a script of the play or musical you are listening to.
...And 4 more matches
Understandable - Accessibility
you don't need to set a different language for words or phrases that are the same regardless of language (for example proper names, technical terms that aren't part of a specific language).
...for example, focusing a navigation menu option should not change the displayed page — it should be activated before the display changes.
...for example, if pressing a button causes the application to exit the current view, the user should be asked to confirm this action, save their work if appropriate, etc.
...And 4 more matches
@supports - CSS: Cascading Style Sheets
WebCSS@supports
the following example returns true if the browser's transform-origin property considers 5% 5% valid: @supports (transform-origin: 5% 5%) {} function syntax the second basic supports condition is a supports function, the syntax for these is supported by all browsers, but the functions themselves are still being standardized.
...the following example returns true if the browser supports the child combinator: @supports selector(a > b) {} the not operator the not operator can precede any expression to create a new expression, resulting in the negation of the original one.
... the following example returns true if the browser's transform-origin property doesn't consider 10em 10em 10em valid: @supports not (transform-origin: 10em 10em 10em) {} as with any operator, the not operator can be applied to a declaration of any complexity.
...And 4 more matches
Spanning and Balancing Columns - CSS: Cascading Style Sheets
for example, a heading nested directly inside the container could become a spanner, as could a heading nested inside a section nested inside the multicol container.
... in the example below, the h2 element is set to column-span: all and spans all of the columns.
... in this second example, the heading is inside an <article> element, yet still spans the content as expected.
...And 4 more matches
Block and inline layout in normal flow - CSS: Cascading Style Sheets
for example, by describing vertical distance between block boxes.
... in the example below, the paragraphs have a top margin of 20px and a bottom margin of 40px.
... in the following example, we have three inline boxes created by a paragraph with a <strong> element inside it.
...And 4 more matches
content - CSS: Cascading Style Sheets
WebCSScontent
/* keywords that cannot be combined with other values */ content: normal; content: none; /* <image> values */ content: url("http://www.example.com/test.png"); content: linear-gradient(#e66465, #9198e5); /* alt text for generated content, added in the level 3 specification */ content: url("http://www.example.com/test.png") / "this is the alt text"; /* values below can only be applied to generated content using ::before and ::after */ /* <string> value */ content: "prefix"; /* <counter> values */ content: counter(chapter_counter); content: counters(section_counter, "."); /* attr() value linked to the html attribute value */ content: attr(value str...
...non-latin characters must be encoded using their unicode escape sequences: for example, \000a9 represents the copyright symbol.
...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.
...And 4 more matches
cursor - CSS: Cascading Style Sheets
WebCSScursor
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... for example, this specifies two images using <url> values, providing <x><y> coordinates for the second one, and falling back to the progress keyword value if neither image can be loaded: cursor: url(one.svg), url(two.svg) 5 5, progress; values <url> a url(…) or a comma separated list url(…), url(…), …, pointing to an image file.
...And 4 more matches
display - CSS: Cascading Style Sheets
WebCSSdisplay
some values of display are fully defined in their own individual specifications; for example the detail of what happens when display: flex is declared is defined in the css flexible box model specification.
...this will result in expected behavior; for example if you specify an element to be block, you would expect that the children of that element would participate in block and inline normal flow layout.
...this will result in expected behavior; for example if you specify an element to be display: grid, you would expect that the box created on the grid container would be a block level box.
...And 4 more matches
font-variation-settings - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...are the registered axes along with their corresponding css properties: axis tag css property "wght" font-weight "wdth" font-stretch "slnt" (slant) font-style: oblique + angle "ital" font-style: italic "opsz" font-optical-sizing custom axes can be anything the font designer wants to vary in their font, for example ascender or descender heights, the size of serifs, or anything else they can imagine.
...And 4 more matches
writing-mode - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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.
...And 4 more matches
Cross-browser audio basics - Developer guides
this article provides: a basic guide to creating a cross-browser html5 audio player with all the associated attributes, properties, and events explained a guide to custom controls created using the media api basic audio example the code below is an example of a basic audio implementation using html5: <audio controls> <source src="audiofile.mp3" type="audio/mpeg"> <source src="audiofile.ogg" type="audio/ogg"> <!-- fallback for non supporting browsers goes here --> <p>your browser does not support html5 audio, but you can still <a href="audiofile.mp3">download the music</a>.</p> </audio> note: you can also use an mp4 file instead of mp3.
... html5 audio in detail now we've looked at a basic example, let's now explore the different aspects of html5 audio in more detail.
... for example, mediaelement.js includes flash fallbacks, which are used something like this: <audio controls> <source src="audiofile.mp3" type="audio/mpeg"> <source src="audiofile.ogg" type="audio/ogg"> <!-- fallback for non supporting browsers goes here --> <a href="audiofile.mp3">download audio</a> <object width="320" height="30" type="application/x-shockwave-flash" data="mediaelement-flash-video.
...And 4 more matches
Setting up adaptive streaming media sources - Developer guides
here's a simple example that provides an audio track representation and four separate video representations.
... <?xml version="1.0" encoding="utf-8"?> <mpd xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" xmlns="urn:mpeg:dash:schema:mpd:2011" xsi:schemalocation="urn:mpeg:dash:schema:mpd:2011 dash-mpd.xsd" type="static" mediapresentationduration="pt654s" minbuffertime="pt2s" profiles="urn:mpeg:dash:profile:isoff-on-demand:2011"> <baseurl>http://example.com/ondemand/</baseurl> <period> <!-- english audio --> <adaptationset mimetype="audio/mp4" codecs="mp4a.40.5" lang="en" subsegmentalignment="true" subsegmentstartswithsap="1"> <representation id="1" bandwidth="64000"> <baseurl>elephantsdream_aac48k_064.mp4.dash</baseurl> </representation> </adaptationset> <!-- video --> <adaptationset mimetype="video/mp4" codecs="avc1.42401e" subsegmentalignment...
... <?xml version="1.0"?> <mpd xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" xmlns="urn:mpeg:dash:schema:mpd:2011" xsi:schemalocation="urn:mpeg:dash:schema:mpd:2011" profiles="urn:mpeg:dash:profile:isoff-main:2011" type="static" mediapresentationduration="pt0h9m56.46s"> <baseurl> http://example.com/segments </baseurl> <period start="pt0s"> <adaptationset bitstreamswitching="true"> <representation id="0" codecs="avc1" mimetype="video/mp4" width="320" height="240" startwithsap="1" bandwidth="46986"> <segmentbase> <initialization sourceurl="main/news100/1.m4s" range="0-862"/> </segmentbase> <segmentlist duration="1"> ...
...And 4 more matches
Overview of events and handlers - Developer guides
button event handler demo for example, browser <button> elements are intended to emit events named 'click' in response to a mouse click or, when displayed in touch sensitive surfaces, to a finger tap.
... we could define in the html page a button as: <button id="buttonone">click here to emit a 'click' event</button> and, in our javascript code, we could first define a function to listen to that 'click' event: var example_click_handler = function (ev){ var objkind = (ev instanceof event) ?
...: "objectprototype"; alert("we got a click event at " + ev.timestamp + " with an argument object derived from: " + objkind ); }; and second register our function with the the button object, either on the scripting side using the dom (document object model) representation of the html page: var buttondomelement = document.queryselector('#buttonone'); buttondomelement.addeventlistener('click', example_click_handler); or within the html page by adding the function as the value of the 'onclick' attribute, although this second approach is usually only used in very simple web pages.
...And 4 more matches
Rich-Text Editing in Mozilla - Developer guides
examples please note: the example files are still being migrated from another site.
...--fumble 18:13, 24 apr 2005 (pdt) example 1 the first example is an html document setting its own designmode to "on".
... figure 2 : first example html: <body contenteditable="true" onload="load()"> javascript: function load(){ window.document.designmode = "on"; } example 2 the second example is a simple rich text editing page, where text can be bolded/italicized/underlined, new links can be added and the color of text changed.
...And 4 more matches
Making content editable - Developer guides
here's a simple example which creates a <div> element whose contents the user can edit.
...most commands affect the document's selection by, for example, applying a style to the text (bold, italics, etc), while others insert new elements (like adding a link) or affect an entire line (indenting).
...for example, even something as simple as what happens when you press enter/return to create a new line of text inside an editable element was handled differently across the major browsers (firefox inserted <br> elements, ie/opera used <p>, chrome/safari used <div>).
...And 4 more matches
Index - Developer guides
WebGuideIndex
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.
... 11 media buffering, seeking, and time ranges apps, buffer, html5, timeranges, video, buffering, seeking sometimes it's useful to know how much <audio> or <video> has downloaded or is playable without delay — a good example of this is the buffered progress bar of an audio or video player.
... 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.
...And 4 more matches
<h1>–<h6>: The HTML Section Heading elements - HTML: Hypertext Markup Language
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... usage notes heading information may be used by user agents, for example, to construct a table of contents for a document automatically.
...And 4 more matches
<em>: The Emphasis element - HTML: Hypertext Markup Language
WebHTMLElementem
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...<em> and <i> are a common example, since they both italicize text.
...And 4 more matches
<input type="reset"> - HTML: Hypertext Markup Language
WebHTMLElementinputreset
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... a simple reset button we'll begin by creating a simple reset button: <form> <div> <label for="example">type in some sample text</label> <input id="example" type="text"> </div> <div> <input type="reset" value="reset the form"> </div> </form> this renders like so: try entering some text into the text field, and then pressing the reset button.
...And 4 more matches
<input type="submit"> - HTML: Hypertext Markup Language
WebHTMLElementinputsubmit
this label is likely to be something along the lines of "submit" or "submit query." here's an example of a submit button with a default label in your browser: <input type="submit"> additional attributes in addition to the attributes shared by all <input> elements, submit button inputs support the following attributes: attribute description formaction the url to which to submit the form's data; overrides the form's action attribute, if any formenctype ...
... a simple submit button we'll begin by creating a form with a simple submit button: <form> <div> <label for="example">let's submit some text</label> <input id="example" type="text" name="text"> </div> <div> <input type="submit" value="send"> </div> </form> this renders like so: try entering some text into the text field, and then submitting the form.
... in this example, s is specified as the access key (you'll need to press s plus the particular modifier keys for your browser/os combination.
...And 4 more matches
<sub>: The Subscript element - HTML: Hypertext Markup Language
WebHTMLElementsub
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... for example, using <sub> to style the name of a company which uses altered baselines in their wordmark would not be appropriate; instead, css should be used (likely the vertical-align property, such as vertical-align: sub or, to more precisely control the baseline shift, vertical-align: -25%.
...And 4 more matches
<summary>: The Disclosure Summary element - HTML: Hypertext Markup Language
WebHTMLElementsummary
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... examples below are some examples showing <summary> in use.
...And 4 more matches
itemscope - HTML: Hypertext Markup Language
in each of the following examples, the vocabulary is from schema.org.
... note: find more about itemtype attributes at http://schema.org/thing simple example html the following example specifies the itemscope attribute.
... the example specifies the itemtype as "http://schema.org/movie", and specifies three related itemprop attributes.
...And 4 more matches
CSP: child-src - HTTP
examples: http://*.example.com: matches all attempts to load from any subdomain of example.com using the http: url scheme.
... mail.example.com:443: matches all attempts to access port 443 on mail.example.com.
... https://store.example.com: matches all attempts to access store.example.com using https:.
...And 4 more matches
CSP: connect-src - HTTP
examples: http://*.example.com: matches all attempts to load from any subdomain of example.com using the http: url scheme.
... mail.example.com:443: matches all attempts to access port 443 on mail.example.com.
... https://store.example.com: matches all attempts to access store.example.com using https:.
...And 4 more matches
CSP: font-src - HTTP
examples: http://*.example.com: matches all attempts to load from any subdomain of example.com using the http: url scheme.
... mail.example.com:443: matches all attempts to access port 443 on mail.example.com.
... https://store.example.com: matches all attempts to access store.example.com using https:.
...And 4 more matches
CSP: frame-src - HTTP
examples: http://*.example.com: matches all attempts to load from any subdomain of example.com using the http: url scheme.
... mail.example.com:443: matches all attempts to access port 443 on mail.example.com.
... https://store.example.com: matches all attempts to access store.example.com using https:.
...And 4 more matches
CSP: manifest-src - HTTP
examples: http://*.example.com: matches all attempts to load from any subdomain of example.com using the http: url scheme.
... mail.example.com:443: matches all attempts to access port 443 on mail.example.com.
... https://store.example.com: matches all attempts to access store.example.com using https:.
...And 4 more matches
CSP: media-src - HTTP
examples: http://*.example.com: matches all attempts to load from any subdomain of example.com using the http: url scheme.
... mail.example.com:443: matches all attempts to access port 443 on mail.example.com.
... https://store.example.com: matches all attempts to access store.example.com using https:.
...And 4 more matches
CSP: object-src - HTTP
examples: http://*.example.com: matches all attempts to load from any subdomain of example.com using the http: url scheme.
... mail.example.com:443: matches all attempts to access port 443 on mail.example.com.
... https://store.example.com: matches all attempts to access store.example.com using https:.
...And 4 more matches
CSP: prefetch-src - HTTP
examples: http://*.example.com: matches all attempts to load from any subdomain of example.com using the http: url scheme.
... mail.example.com:443: matches all attempts to access port 443 on mail.example.com.
... https://store.example.com: matches all attempts to access store.example.com using https:.
...And 4 more matches
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.
... mail.example.com:443: matches all attempts to access port 443 on mail.example.com.
... https://store.example.com: matches all attempts to access store.example.com using https:.
...And 4 more matches
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.
... mail.example.com:443: matches all attempts to access port 443 on mail.example.com.
... https://store.example.com: matches all attempts to access store.example.com using https:.
...And 4 more matches
CSP: style-src - HTTP
examples: http://*.example.com: matches all attempts to load from any subdomain of example.com using the http: url scheme.
... mail.example.com:443: matches all attempts to access port 443 on mail.example.com.
... https://store.example.com: matches all attempts to access store.example.com using https:.
...And 4 more matches
CSP: worker-src - HTTP
examples: http://*.example.com: matches all attempts to load from any subdomain of example.com using the http: url scheme.
... mail.example.com:443: matches all attempts to access port 443 on mail.example.com.
... https://store.example.com: matches all attempts to access store.example.com using https:.
...And 4 more matches
Content-Security-Policy-Report-Only - HTTP
examples this header reports violations that would have occurred.
... sample violation report let's consider a page located at http://example.com/signup.html.
... it uses the following policy, disallowing everything but stylesheets from cdn.example.com.
...And 4 more matches
Upgrade - HTTP
WebHTTPHeadersUpgrade
for example, it can be used by a client to upgrade a connection from http 1.1 to http 2.0, or an http or https connection into a websocket.
... for example, the client might send a get request as shown, listing the preferred protocols to switch to (in this case "example/1" and "foo/2"): get /index.html http/1.1 host: www.example.com connection: upgrade upgrade: example/1, foo/2 note: connection: upgrade must be set whenever upgrade is sent.
... the server can choose to ignore the request, for any reason, in which case it should just respond as though the upgrade header had not been sent (for example, with a  200 ok).
...And 4 more matches
Quantifiers - JavaScript
for example, /bo*/ matches "boooo" in "a ghost booooed" and "b" in "a bird warbled", but nothing in "a goat grunted".
...for example, /a+/ matches the "a" in "candy" and all the "a"'s in "caaaaaaandy".
...for example, /e?le?/ matches the "el" in "angel" and the "le" in "angle." if used immediately after any of the quantifiers *, +, ?, or {}, makes the quantifier non-greedy (matching the minimum number of times), as opposed to the default, which is greedy (matching the maximum number of times).
...And 4 more matches
Text formatting - JavaScript
for example: const firststring = '2 + 2'; // creates a string literal value const secondstring = new string('2 + 2'); // creates a string object eval(firststring); // returns the number 4 eval(secondstring); // returns the string "2 + 2" a string object has one property, length, that indicates the number of utf-16 code units in the string.
... for example, the following code assigns hellolength the value 13, because "hello, world!" has 13 characters, each represented by one utf-16 code unit.
...for example, a string containing the single character u+1f600 "emoji grinning face" will have length 2.
...And 4 more matches
Inheritance and the prototype chain - JavaScript
it is, for example, fairly trivial to build a classic model on top of a prototypal model.
...a); console.log(a.a); // print 1 console.log(b.a); // print 1 b.a=5; console.log(a.a); // print 1 console.log(b.a); // print 5 delete b.a; console.log(a.a); // print 1 console.log(b.a); // print 1(b.a value 5 is deleted but it showing value from its prototype chain) delete a.a; console.log(a.a); // print undefined console.log(b.a); // print undefined the new operator has a shorter chain in this example: function graph() { this.vertices = [4,4]; } var g = new graph(); console.log(g.vertices); // print [4,4] g.vertices = 25; console.log(g.vertices); // print 25 delete g.vertices; console.log(g.vertices); // print undefined with the class keyword ecmascript 2015 introduced a new set of keywords implementing classes.
...to give you a concrete example, let's take the above graph example code to illustrate it: console.log(g.hasownproperty('vertices')); // true console.log(g.hasownproperty('nope')); // false console.log(g.hasownproperty('addvertex')); // false console.log(g.__proto__.hasownproperty('addvertex')); // true hasownproperty is the only thing in javascript which deals with properties and does not traverse the prototype chain.
...And 4 more matches
Function.prototype.call() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... examples using call to chain constructors for an object you can use call to chain constructors for an object (similar to java).
...And 4 more matches
Intl.Collator() constructor - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...examples: a ≠ b, a = á, a = a.
...And 4 more matches
JSON.stringify() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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)) // '"2...
...And 4 more matches
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).
... the example then displays the constructor property for the object thetree.
... function tree(name) { this.name = name } let thetree = new tree('redwood') console.log('thetree.constructor is ' + thetree.constructor) this example displays the following output: thetree.constructor is function tree(name) { this.name = name } changing the constructor of an object the following example shows how to modify the constructor value of generic objects.
...And 4 more matches
Proxy - JavaScript
for example, this code defines a simple target with just two properties, and an even simpler handler with no properties: const target = { message1: "hello", message2: "everyone" }; const handler1 = {}; const proxy1 = new proxy(target, handler1); because the handler is empty, this proxy behaves just like the original target: console.log(proxy1.message1); // hello console.log(proxy1.message2); // everyone to customise the proxy...
... 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.
... obj[prop] : 37; } }; const p = new proxy({}, handler); p.a = 1; p.b = undefined; console.log(p.a, p.b); // 1, undefined console.log('c' in p, p.c); // false, 37 no-op forwarding proxy in this example, we are using a native javascript object to which our proxy will forward all operations that are applied to it.
...And 4 more matches
RegExp - JavaScript
for example, if you use literal notation to construct a regular expression used in a loop, the regular expression won't be recompiled on each iteration.
... the constructor of the regular expression object—for example, new regexp('ab+c')—results in runtime compilation of the regular expression.
... for example, the following are equivalent: let re = /\w+/ let re = new regexp('\\w+') perl-like regexp properties note that several of the regexp properties have both long and short (perl-like) names.
...And 4 more matches
parseInt() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...(for example, a radix of 10 converts from a decimal number, 8 converts from octal, 16 from hexadecimal, and so on.) for radices above 10, letters of the english alphabet indicate numerals greater than 9.
...And 4 more matches
Property accessors - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...a method is simply a property that can be called (for example, if it has a reference to a function instance as its value).
...And 4 more matches
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.
... for example, the following: async function foo() { return 1 } ...is equivalent to: function foo() { return promise.resolve(1) } the body of an async function can be thought of as being split by zero or more await expressions.
... for example: async function foo() { await 1 } ...is equivalent to: function foo() { return promise.resolve(1).then(() => undefined) } code after each await expression can be thought of as existing in a .then callback.
...And 4 more matches
JavaScript typed arrays - JavaScript
this is useful for canvas data processing, for example.
...this is useful when dealing with different types of data, for example.
... 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.
...And 4 more matches
Media container formats (file types) - Web media technologies
for example, an ogg file with only an opus audio track is sometimes referred to as an opus file, and might even have the extension .opus.
...a good example of this is the mp3 audio file, which is in fact an mpeg-1 container with a single audio track encoded using mpeg-1 audio layer iii encoding.
...for example, firefox 3.5 and 3.6 support ogg, but not webm.
...And 4 more matches
Image file type and format guide - Web media technologies
for example, an rgb color depth of 8 indicates that each of the red, green, and blue components are represented by an 8-bit value.
...for example, apng is one of the formats supported when creating animated stickers for apple's imessage application (and the messages application on ios).
...for instance, this example defines an drawing area with initial size 100 by 100 units, containing a line drawn diagonally through the box: <svg viewbox="0 0 100 100" xmlns="http://www.w3.org/2000/svg"> <line x1="0" y1="80" x2="100" y2="20" stroke="black" /> </svg> svg can be used in web content in two ways: you can directly write the <svg> element within the html, containing svg elements to draw the image.
...And 4 more matches
Introduction to progressive web apps - Progressive web apps (PWAs)
for example, web apps are more discoverable than native apps; it's a lot easier and faster to visit a website than to install an application, and you can also share web apps by simply sending a link.
...for example: a decrease in loading times after the app has been installed, thanks to caching with service workers, along with saving precious bandwidth and time.
... you can check the list at pwa.rocks for more examples.
...And 4 more matches
Progressive loading - Progressive web apps (PWAs)
previous overview: progressive web apps in previous articles we covered apis that help us make our js13kpwa example a progressive web app: service workers, web manifests, notifications and push.
... to fix that we can, for example, add defer to javascript files: <script src="app.js" defer></script> they will be downloaded and executed after the document itself has been parsed, so it won't block rendering the html structure.
...we could go even further and move everything from style.css to the <style> tag in the <head> of index.html — this would improve performance even more, but for the readability of the example we will skip that approach too.
...And 4 more matches
Making PWAs work offline with Service workers - Progressive web apps (PWAs)
in this article, we look at how it is used in our js13kpwa example (see the source code also).
... 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', '/pw...
...And 4 more matches
How to make PWAs re-engageable using Notifications and Push - Progressive web apps (PWAs)
create a notification the example app creates a notification out of the available data — a game is picked at random, and the chosen one feeds the notification with the content: it sets the game's name as the title, mentioning the author in the body, and showing the image as an icon: function randomnotification() { var randomitem = math.floor(math.random()*games.length); var notiftitle = games[randomitem].name; var ...
... 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).
...And 4 more matches
Mobile first - Progressive web apps (PWAs)
for example: if you are serving different styling and layout information for different viewport sizes, etc., it makes more sense to include the narrow screen/mobile styling as the default styling before any media queries are encountered, rather than having desktop/wider screen styling first.
... a simple example to demonstrate the concepts, i wanted to cover in this article, i created a very simple app containing a nav menu, heading and single column of text.
... you can see my mobile first example running live, or grab the code to play with it on github.
...And 4 more matches
Gradients in SVG - SVG: Scalable Vector Graphics
basic example <svg width="120" height="240" version="1.1" xmlns="http://www.w3.org/2000/svg"> <defs> <lineargradient id="gradient1"> <stop class="stop1" offset="0%"/> <stop class="stop2" offset="50%"/> <stop class="stop3" offset="100%"/> </lineargradient> <lineargradient id="gradient2" x1="0" x2="0" y1="0" y2="1"> <stop offset="0%" stop-color="red"/> ...
...#rect1 { fill: url(#gradient1); } .stop1 { stop-color: red; } .stop2 { stop-color: black; stop-opacity: 0; } .stop3 { stop-color: blue; } ]]></style> </defs> <rect id="rect1" x="10" y="10" rx="15" ry="15" width="100" height="100"/> <rect x="10" y="120" rx="15" ry="15" width="100" height="100" fill="url(#gradient2)"/> </svg> screenshotlive sample above is an example of a linear gradient being applied to a <rect> element.
...the two methods have been intermixed for the purposes of this example.
...And 4 more matches
Types of attacks - Web security
this can be used, for example, to steal login credentials or to get the user's unwitting permission to install a piece of malware.
... wikipedia mentions a good example for csrf.
... in this situation, someone includes an image that isn’t really an image (for example in an unfiltered chat or forum), instead it really is a request to your bank’s server to withdraw money: <img src="https://bank.example.com/withdraw?account=bob&amount=1000000&for=mallory"> now, if you are logged into your bank account and your cookies are still valid (and there is no other validation), you will transfer money as soon as you load the html that contains this image.
...And 4 more matches
Using shadow DOM - Web Components
as an example, consider the following html fragment: <!doctype html> <html> <head> <meta charset="utf-8"> <title>simple dom example</title> </head> <body> <section> <img src="dinosaur.png" alt="a red tyrannosaurus rex: a two legged dinosaur standing upright like a human, with small arms, and a large head with lots of sharp teeth."> <p>here we will add a link to the <a href=...
... you can affect the nodes in the shadow dom in exactly the same way as non-shadow nodes — for example appending children or setting attributes, styling individual nodes using element.style.foo, or adding style to the entire shadow dom tree inside a <style> element.
...think for example of a <video> element, with the default browser controls exposed.
...And 4 more matches
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.
... example: defining a custom node-specific evaluatexpath() utility function // evaluate an xpath expression aexpression against a given dom node // or document object (anode), returning the results as an array // thanks wanderingstan at morethanwarm dot mail dot com for the // initial work.
... sample usage assume we have the following xml document (see also how to create a dom tree and parsing and serializing xml): example: an xml document to use with the custom evaluatexpath() utility function <?xml version="1.0"?> <people> <person first-name="eric" middle-initial="h" last-name="jung"> <address street="321 south st" city="denver" state="co" country="usa"/> <address street="123 main st" city="arlington" state="ma" country="usa"/> </person> <person first-name="jed" last-name="brown"> <address st...
...And 4 more matches
Index - XSLT: Extensible Stylesheet Language Transformations
WebXSLTIndex
6 advanced example xslt this advanced example sorts several divs based on their content.
... the example allows sorting the content multiple times, alternating between ascending and descending order.
... 7 basic example xslt the basic example will load an xml file and apply a xsl transformation on it.
...And 4 more matches
Content Scripts - Archive of obsolete content
almost all the examples presented in this guide are available as complete, but minimal, add-ons in the addon-sdk-content-scripts repository on github.
... for example, consider a page that adds a variable foo to the window object using a page script: <!doctype html"> <html> <head> <script> window.foo = "hello from page script" </script> </head> </html> another script loaded into the page after this script will be able to access foo.
... this insulation means that, for example, if a web page loads the jquery library, then the content script won't be able to see the jquery object added by the library - but the content script can add its own jquery object, and it won't clash with the page script's version.
...And 3 more matches
page-worker - Archive of obsolete content
in this example we fetch the first paragraph of a page from wikipedia, then the first paragraph of a different page: var getfirstparagraph = "var paras = document.getelementsbytagname('p');" + "console.log(paras[0].textcontent);" + "self.port.emit('loaded');" pageworker = require("sdk/page-worker").page({ contentscript: getfirstparagraph, contenturl: "http://...
...with contentscript you pass the script as a string, as in the examples above.
... for example, the content script might read some content and send it back to the main add-on, which could store it using the simple-storage api.
...And 3 more matches
panel - Archive of obsolete content
for example, here's an add-on whose content script intercepts mouse clicks on links inside the panel, and sends the target url to the main add-on code.
... " var t = event.target;" + " if (t.nodename == 'a')" + " self.port.emit('click-link', t.tostring());" + "}, false);" var mypanel = require("sdk/panel").panel({ contenturl: "http://www.bbc.co.uk/mobile/index.html", contentscript: myscript }); mypanel.port.on("click-link", function(url) { console.log(url); }); mypanel.show(); this example uses contentscript to supply the script as a string.
... getting user input note: this example uses the action button api, which is only available from firefox 29 onwards.
...And 3 more matches
system - Archive of obsolete content
usage querying your environment using the system module you can access environment variables (such as path), find out which operating system your add-on is running on and get information about the host application (for example, firefox or fennec), such as its version.
... for example: // get firefox profile path var profilepath = require('sdk/system').pathfor('profd'); // get os temp files directory (/tmp) var temps = require('sdk/system').pathfor('tmpd'); // get os desktop path for an active user (~/desktop on linux // or c:\documents and settings\username\desktop on windows).
...for example: "msvc", "n32", "gcc2", "gcc3", "sunc", "ibmc" var system = require("sdk/system"); console.log("compiler = " + system.compiler); build an identifier for the specific build, derived from the build date.
...And 3 more matches
widget - Archive of obsolete content
for example, in the future firefox may allow the user to drag widgets from the add-on bar to other toolbars.
... for example, this widget contains an image, so it looks like a simple icon: require("sdk/widget").widget({ id: "mozilla-icon", label: "my mozilla widget", contenturl: "http://www.mozilla.org/favicon.ico" }); you can make contenturl point to an html or icon file which you have packaged inside your add-on.
...ta.url() method of the self module: var data = require("sdk/self").data; require("sdk/widget").widget({ id: "my-widget", label: "my widget", contenturl: data.url("my-content.html") }); this widget contains an entire web page: require("sdk/widget").widget({ id: "hello-display", label: "my hello widget", content: "hello!", width: 50 }); widgets are quite small by default, so this example used the width property to grow it in order to show all the text.
...And 3 more matches
core/promise - Archive of obsolete content
}); in this example bar is a promise and it's fulfilled by one of two handlers that are responsible for: if handler returns a value, bar will be resolved with it.
...for example grouping promises to observe single resolution of all of them is as simple as this: var group = promised(array); var abc = group(aasync, basync, casync).then(function(items) { return items[0] + items[1] + items[2]; }); all the all function is provided to consume an array of promises and return a promise that will be accepted upon the acceptance of all the promises in the initial array.
... this can be used to perform an action that requires values from several promises, like getting user information and server status, for example: const { all } = require('sdk/core/promise'); all([getuser, getserverstatus]).then(function (result) { return result[0] + result[1] }); if one of the promises in the array is rejected, the rejection handler handles the first failed promise and remaining promises remain unfulfilled.
...And 3 more matches
ui/button/action - Archive of obsolete content
for example, in the screenshots above, firefox uses the small icon when the button is in the toolbar and the large icon when the button is in the menu panel.
... for example, if you have a button like this: var { actionbutton } = require('sdk/ui/button/action'); var button = actionbutton({ id: "my-button", label: "default", icon: "./firefox-16.png" }); you can change its label for only the currently active window like this: button.state("window", { "label" : "window-specific label" }); you can change its label for only the currently active tab like this:...
...for example, this add-on: creates a button with a default label opens a new tab sets a new label only for the new tab logs the result of accessing the global label, the window-specific label, and each of the 2 tab-specific labels var { actionbutton } = require('sdk/ui/button/action'); var tabs = require("sdk/tabs"); var button = actionbutton({ id: "my-button", label: "default label", icon: "./firefox-16.png" }); tabs.open({ ...
...And 3 more matches
Creating Event Targets - Archive of obsolete content
for example, you can listen to the tabs module's ready event or the panel object's show event.
...for example, we can adapt "index.js" as follows: var bookmarks = require("./bookmarks"); function logadded(uri) { console.log("added: " + uri); } function logvisited(uri) { console.log("visited: " + uri); } exports.main = function() { bookmarks.on("added", logadded); bookmarks.on("visited", logvisited); }; exports.onunload = function() { bookmarks.removelistener("added", logadded); bookmarks...
... in this example, we could define a class bookmarkmanager that inherits from eventtarget and emits added and visited events.
...And 3 more matches
Modifying the Page Hosted by a Tab - Archive of obsolete content
here's a simple example: var button = require("sdk/ui/button/action").actionbutton({ id: "style-tab", label: "style tab", icon: "./icon-16.png", onclick: function() { require("sdk/tabs").activetab.attach({ contentscript: 'document.body.style.border = "5px solid red";' }); } }); to run this example, save an icon file named "icon-16.png" in add-on's "data" directory.
...you should see a red border appear around the page, like this: keeping content scripts in a separate file in the example above, we've passed in content script as a string.
... for example, if we save the script above under the add-on's data directory in a file called my-script.js: var self = require("sdk/self"); var button = require("sdk/ui/button/action").actionbutton({ id: "style-tab", label: "style tab", icon: "./icon-16.png", onclick: function() { require("sdk/tabs").activetab.attach({ contentscriptfile: self.data.url("my-script.js") }); } }); you can load more than one script, and the scripts can interact directly with each other.
...And 3 more matches
Forms related code snippets - Archive of obsolete content
date picker (before implementing it in a working environment, please read the note about the const statement compatibility) <!doctype html> <html> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <title>datepicker example - mdn</title> <script type="text/javascript"> /*\ |*| |*| datepicker example mdndeveloper network |*| |*| https://developer.mozilla.org/docs/code_snippets/forms |*| https://developer.mozilla.org/user:fusionchess |*| |*| this snippet is released under the gnu public license, version 3 or later.
...if you want to emulate an editable select through a <fieldset> of radioboxes and textboxes (written in pure css, without javascript), please see this example.
... autogrowing <textarea> this example shows how to make a textarea really autogrowing during a typing.
...And 3 more matches
Displaying web content in an extension without security issues - Archive of obsolete content
a typical example is an rss reader extension that would take the content of the rss feed (html code), format it nicely and insert into the extension window.
...this means for example that javascript code top.location.href = "about:blank" will only unload the content document but won’t have any effect on the chrome.
...for example, "chrome://foo/content/foo.xhtml" will have full privileges, "http://example.com/foo.xhtml" will be allowed to access example.com, "file:///c:/foo.xhtml" will be allowed to read files from disk (with some restrictions).
...And 3 more matches
Inline options - Archive of obsolete content
here is an example of an options.xul file: <?xml version="1.0"?> <!doctype mydialog system "chrome://myaddon/locale/mydialog.dtd"> <vbox xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <setting type="bool" pref="extensions.myaddon.bool" title="boolean" desc="stored as a boolean preference" /> </vbox> note that it's limited to <setting> tags.
... 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.mya...
...ddon.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="12...
...And 3 more matches
JavaScript Object Management - Archive of obsolete content
however, most extensions are small projects by individuals, so these examples follow a more practical approach of having just one namespace with the project name.
...a clear example of this is the fact that there are no private or public keywords that allow you to protect object members.
...for example: _stringbundle, _createusernode().
...And 3 more matches
Setting up an extension development environment - Archive of obsolete content
in the following example, the described command starts a new instance of firefox, with a profile called dev; even if an instance of firefox is already running.
... 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.
... create a file in the "extensions" directory under your profile directory with the extension's id as the file name (for example "your_profile_directory/extensions/{46d1b3c0-db7a-4b1a-863a-6ee6f77ecb58}").
...And 3 more matches
Index of archived content - Archive of obsolete content
guides content scripts communicating with other scripts communicating using "port" communicating using "postmessage" cross-domain content scripts interacting with page scripts loading content scripts reddit example port self contributor's guide classes and inheritance content processes getting started modules private properties firefox compatibility module structu...
... 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 ...
... dehydra function reference dehydra object reference installing dehydra using dehydra developing new mozilla features devmo 1.0 launch roadmap download manager improvements in firefox 3 download manager preferences drag and drop drag and drop example drag and drop javascript wrapper drag and drop events editor embedding guide embedding faq embedding mozilla in a java application using javaxpcom error console exception logging in javascript existing content extension frequently asked questions external cvs snapshots in...
...And 3 more matches
In-Depth - Archive of obsolete content
example: -moz-border-top-colors: threeddarkshadow threedshadow transparent; -moz-border-right-colors: threeddarkshadow threedshadow transparent; -moz-border-bottom-colors: threeddarkshadow threedshadow transparent; -moz-border-left-colors: threeddarkshadow threedshadow transparent; -moz-border-top-colors see -moz-border-bottom-colors above.
...an example of where this would be used is on tabs.
...an example of where this would be used is on tabs.
...And 3 more matches
Dehydra Object Reference - Archive of obsolete content
often, the best way to become familiar with the dehydra objects is to print out the objects: dehydra example code an online tool for pretty-printing dehydra data understanding properties dehydra only sets properties that are applicable.
... for example, class types and typedefs are declared and will have a .loc property.
...for example, a pointer type will have .ispointer == true, but a class type will not have an .ispointer property.
...And 3 more matches
Introducing the Audio API extension - Archive of obsolete content
the following example extracts the data from an audio element: <!doctype html> <html> <head> <title>javascript metadata example</title> </head> <body> <audio id="audio-element" src="song.ogg" controls="true" style="width: 512px;"> </audio> <script> function loadedmetadata() { channels = audio.mozchannels; rate = audio.
...for example, for a two-channel signal: channel1-sample1 channel2-sample1 channel1-sample2 channel2-sample2 channel1-sample3 channel2-sample3.
... we can extend the previous example to visualize the timestamp and the first two samples in a <div> element: <!doctype html> <html> <head> <title>javascript visualization example</title> </head> <body> <audio id="audio-element" src="revolve.ogg" controls="true" style="width: 512px;"> </audio> <pre id="raw">hello</pre> <script> function loadedmetadata() { channels = audio.mozchannels; rate = audio.mozsamplerate; framebufferlength = audio.mozframebufferlength; } function audioavailable(event) { var framebuffer = event.framebuffer; var t = event.time; var text = "samples at: " + t + "\n"; text += framebuffer[0] + " " + framebuffer[1]; ...
...And 3 more matches
Modularization techniques - Archive of obsolete content
the mechanism we're using is based on the principles laid down by com, so pretty much anything you know about com can be applied here, and any reference on com can provide you with more interesting and complex examples than the ones provided here.
... a simple example it is recommended that you use xpidl to define your interfaces.
...extern "c" ns_export prbool nscanunload(); the implementation of nsgetfactory() in the simplest case is nearly identical to that of getsamplefactory() in our previous example.
...And 3 more matches
Priority Content - Archive of obsolete content
note: use example at sample:original document information to credit original authors.
...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.
...And 3 more matches
RDF Datasource How-To - Archive of obsolete content
the "rdf universe" consists of a set of statements about internet resources; for example, "my home page was last modified april 2nd", or "that news article was sent by bob".
...for example, a "file system datasource" would translate the file system into statements like "/tmp is a directory" and "/tmp/foo is contained within /tmp".
...for example, you may choose to delegate to the in-memory datasource, which is a generic datasource that implements nsirdfdatasource.
...And 3 more matches
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.
...you can type /help next, for example, to see how to use the next command.
...when the view again becomes necessary—for example, when you open a source file from the loaded scripts view and want to view the source—the view reappears where it was last positioned.
...And 3 more matches
Writing textual data - Archive of obsolete content
the example above passes 0 as the third argument, which disables buffering (note: the implementation of the converter stream might not support buffering).
... to instead write a replacement character in such cases, specify the character instead of 0x00: os.init(fos, charset, 0, "?".charcodeat(0)); you can, of course, replace the "?" in that example with any other character.
... here's an example: // first, get and initialize the converter var converter = components.classes["@mozilla.org/intl/scriptableunicodeconverter"] .createinstance(components.interfaces.nsiscriptableunicodeconverter); converter.charset = /* the character encoding you want, using utf-8 for this example */ "utf-8"; now you can convert and write to the stream: // this code assumes that os i...
...And 3 more matches
Moving, Copying and Deleting Files - Archive of obsolete content
var file = io.newfile("home", "source.txt"); var destination = io.newfile("desktop", ""); file.copyto(destination, "destination.txt"); this example copies a file called 'source.txt' within the user's home directory to the desktop.
... var file = io.newfile("home", "importantdata"); var destination = io.newfile("desktop", ""); destination.append("backups"); file.copyto(destination, ""); this example copies an item called 'importantdata' into a directory called 'backups' within the desktop directory.
... in this last example, the destination filename is set to an empty string.
...And 3 more matches
Extensions - Archive of obsolete content
for example, to add an item to the end of the tools menu, use the following: <menupopup id="menu_toolspopup"> <menuitem label="thesaurus"/> </menupopup> note that other extensions may be adding their own items into the same menus.
...in this example, a single item is added to the end of the firefox context menu.
...for example, the following may be used to insert a command just after the 'select all' command: <popup id="contentareacontextmenu"> <menuitem label="select links" oncommand="thumbnails.selectalllinks();" insertafter="context-selectall"/> </popup> see firefox context menu for a list of the ids of the items found on the firefox context menu.
...And 3 more matches
MenuModification - Archive of obsolete content
<script> function addtomenu() { var menu = document.getelementbyid("edit-menu"); menu.appenditem("insert", "insert"); } </script> <menu id="edit-menu"/> <button label="add" oncommand="addtomenu()"/> in this example, the addtomenu function is called when the button is pressed.
...note how in this example, the menu does not have a child menupopup.
... menu.insertitemat(0, "delete", "delete"); in this example, the insertitemat method is used to insert a new 'delete' item at the beginning of the menu's popup.
...And 3 more matches
PopupEvents - Archive of obsolete content
for examples of the use of the popupshowing event when used with context menus, see hiding and showing menu items based on context.
...in this example, a label within a panel is initialized with the current time.
...<menu label="edit"> <menupopup onpopupshowing="if (gdisallowed) event.preventdefault();"> <menuitem label="undo"/> <menuitem label="redo"/> </menupopup> </menu> in this example, a global variable gdisallowed is checked and the preventdefault method is called.
...And 3 more matches
Containment Properties - Archive of obsolete content
let's look back at the very first example again.
...<vbox datasources="template-guide-ex1.rdf" ref="http://www.xulplanet.com/rdf/a" containment="http://www.xulplanet.com/rdf/relateditem"> <template> <rule> <label uri="rdf:*" value="rdf:*"/> </rule> </template> </vbox> instead of iterating over a container, this example iterates over a specific predicate.
...this next example demonstrates this.
...And 3 more matches
Result Generation - Archive of obsolete content
you could have arcs pointing elsewhere--for example, node d could have an arc pointing back to a.
...in this example, all the arrows have the same label.
...a literal's value is, for example, the name of the thing, such as 'fred'.
...And 3 more matches
Complete - Archive of obsolete content
for example, chrome.manifest originally had: content custombutton chrome/ now it has: content allcustom jar:chrome/allcustom.jar!/content/allcustom/ you can see the other changes if you unpack the xpi.
...for example, the code en-us means english language (en) for the united states (us).
...this is how it happens: for example, if your locale is fr-fr, it loads: locale/fr-fr/allcustom/allcustom.dtd from inside the jar file.
...And 3 more matches
Creating a Skin - Archive of obsolete content
for example, change references of 'classic/1.0' to 'blueswayedshoes/1.0'.
...if following the example in this section, just copy the files to your new skin and change the urls accordingly.
...for example, having different images for the check boxes in the find files dialog as other windows looks a little odd.
...And 3 more matches
Cross Package Overlays - Archive of obsolete content
in the examples in the previous section, the overlays were imported by the window.
...for example, you could add menu items or toolbars to the mozilla browser window.
...for example, if mail is not installed, there will be no new message command.
...And 3 more matches
Manifest Files - Archive of obsolete content
for example, on a windows machine, you might use c:\testfiles create a new ascii1 file called test.manifest in the chrome directory.
...the packagename in the example above is 'tests', which means that the first field in the chrome url is 'tests' as in chrome://tests/content/sample.xul.
...for example: skin browser classic/1.0 jar:classic.jar!/skin/classic/browser/ locale browser en-us jar:en-us.jar!/locale/browser/ for these, the extra field has been added to indicate that the skin and locale applies to the browser.
...And 3 more matches
More Button Features - Archive of obsolete content
example 1 : source view <button label="help" image="happy.png"/> button with css image another way to specify the image is by using the css list-style-image style property on the button.
...an example is shown below.
... example 2 : source view <button id="find-button" label="find" style="list-style-image: url('happy.png')"/> in this case, the image 'happy.png' is displayed on the button.
...And 3 more matches
Trees - Archive of obsolete content
ArchiveMozillaXULTutorialTrees
some examples of trees include the list of messages in a mail application, or the bookmarks window in mozilla.
... example tree with two columns example 1 : source view <tree flex="1"> <treecols> <treecol id="namecolumn" label="name" flex="1"/> <treecol id="addresscolumn" label="address" flex="2"/> </treecols> <treechildren/> </tree> first, the entire table is surrounded with a tree element.
...in this example, the second column will be approximately twice as wide as the first column.
...And 3 more matches
XBL Attribute Inheritance - Archive of obsolete content
for example: xul: <searchbox/> xbl: <binding id="searchbinding"> <content> <xul:textbox/> <xul:button label="search"/> </content> </binding> in the example, the label attribute has been placed directly on the button element.
...the next example demonstrates this.
... <bindings xmlns:xbl="http://www.mozilla.org/xbl" xmlns:xul="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <xbl:binding id="buttonbinding"> <xbl:content> <xul:button label="ok" xbl:inherits="label"/> </xbl:content> </xbl:binding> in this example, the button inherits the label attribute, but this attribute is also given a value directly in the xbl.
...And 3 more matches
key - Archive of obsolete content
ArchiveMozillaXULkey
« 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.
...mespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata details on key, keycode, and modifiers attributes for example, consider the following key: <key key="r" modifiers="shift"/> this key will only match when the shift key is pressed as well as the r key, and no other keys.
...And 3 more matches
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.
... <menulist> <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"/> </menupopup> </menulist> the following example shows how a menupopup can be used as a context menu for an element.
...And 3 more matches
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.
...for example, the browser's home page is set with the preference browser.startup.homepage.
...And 3 more matches
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"/> ...
...for example, if you are using a listbox and the user changes the contents of the listbox (such as adding or removing an item) and you want to sync the changes back to a preference, you must write an onsynctopreference handler for your listbox that returns the value to be written to the preference element, and then call the userchangedvalue function every time you edit the list in a way that should cause the ...
...And 3 more matches
tree - Archive of obsolete content
ArchiveMozillaXULtree
« 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.
... relevant accessbility guidelines provide alternative access (for example, via menus) to column picker and for header behaviors like sorting (these have no default keyboard access).
...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> ...
...And 3 more matches
Why RSS Content Module is Popular - Including HTML Contents - Archive of obsolete content
for example, you could use it to include the entire contents of a blog post; or just a summary of it.
...(even through you are not suppose to.) for example, if your blog post was: this is <b>bold</b>.
...using the example above we'd have: <description><![cdata[this is <b>bold</b>.]]></description> this helps reduce the bloat.
...And 3 more matches
Threats - Archive of obsolete content
for example, someone could learn your credit card number, record a sensitive conversation, or intercept classified information.
...for example, someone could alter an order for goods or change a person's resume.
...for example, a person can pretend to have the email address jdoe@example.net, or a computer can identify itself as a site called www.example.net when it is not.
...And 3 more matches
GetObject - Archive of obsolete content
for example: var cadobject; cadobject = getobject("c:\\cad\\schema.cad"); when this code is executed, the application associated with the specified pathname is started, and the object in the specified file is activated.
... for example, in a drawing application you might have multiple layers to a drawing stored in a file.
...for example, a drawing might support three different types of objects: an application object, a drawing object, and a toolbar object, all of which are part of the same file.
...And 3 more matches
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.
... 15 3d games on the web games, graphics, needscontent, needsexample, webgl, webvr, three.js for rich gaming experiences on the web, the weapon of choice is webgl, which is rendered on html <canvas>.
...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.
...And 3 more matches
Mobile touch controls - Game development
traightforward: var el = document.getelementsbytagname("canvas")[0]; el.addeventlistener("touchstart", handlestart); el.addeventlistener("touchmove", handlemove); el.addeventlistener("touchend", handleend); el.addeventlistener("touchcancel", handlecancel); this way, touching the game's <canvas> on the mobile screen would emit events, and thus we could manipulate the game in any way we want (for example, moving the space ship around).
... touchmove is fired when they move the finger on the screen while touching it touchend is fired when the user stops touching the screen touchcancel is fired when a touch is cancelled, for example when the user moves their finger outside of the screen.
... note: the touch events reference article provides more examples and information.
...And 3 more matches
Test your skills: HTML accessibility - Learn web development
try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor.
... try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor.
... try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor.
...And 3 more matches
What is accessibility? - Learn web development
some screen reader examples include: some are paid commercial products, like jaws (windows) and dolphin screen reader (windows).
...the below video also provides a brief example of what the experience is like.
...can you use the tab key to move between the different controls of a web form, for example?
...And 3 more matches
Test your skills: The Box Model - Learn web development
try updating the live code below to recreate the finished example: for assessment or further work purposes, download the starting point for this task to work in your own editor or in an online editor.
... try updating the live code below to recreate the example as displayed in the image: for assessment or further work purposes, download the starting point for this task to work in your own editor or in an online editor.
... the box model three in this example the inline element has a margin, padding and border however the lines above and below are overlapping it.
...And 3 more matches
Test your skills: backgrounds and borders - Learn web development
the finished example should look like the image below.
... try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor.
... the finished example should look like the image below: try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor.
...And 3 more matches
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.
...And 3 more matches
Your first form - Learn web development
forms allow users to enter data, which is generally sent to a web server for processing and storage (see sending form data later in the module), or used on the client-side to immediately update the interface in some way (for example, add another item to a list, or show or hide a ui feature).
... in our simple example, we use the value <input/text> for the first input — the default value for this attribute.
... note: you can also use the <input> element with the corresponding type to produce a button, for example <input type="submit">.
...And 3 more matches
Dealing with files - Learn web development
so for example, if you put an image on your website at, test-site/myimage.jpg and then in a different file you try to invoke the image as test-site/myimage.jpg, it may not work.
...for example, if you use spaces in your filename, some systems may treat the filename as two filenames.
... styles folder: this folder will contain the css code used to style your content (for example, setting text and background colors).
...And 3 more matches
The web and web standards - Learn web development
for example, the html living standard describes exactly how html (all the html elements, and their associated apis, and other surrounding technologies) should be implemented.
... cascading style sheets (css) is a rule-based language used to apply styles to your html, for example setting text and background colors, adding borders, animating things, or laying out a page in a certain way.
... as a simple example, the following code would turn our html paragraph red: p { color: red; } in the house analogy, css is like the paint, wallpaper, carpets and paintings you'd use to make the house look nice.
...And 3 more matches
Adding vector graphics to the Web - Learn web development
to give you an idea of the difference between the two, let's look at an example.
... you can find this example live on our github repo as vector-versus-raster.html — it shows two seemingly identical images side by side, of a red star with a black drop shadow.
...again, go to the vector-versus-raster.html demo for a real example!
...And 3 more matches
Silly story generator - Learn web development
starting point to get this assessment started, you should: go and grab the html file for the example, save a local copy of it as index.html in a new directory somewhere on your computer, and do the assessment locally to begin with.
... this also has the css to style the example contained within it.
... will generate another random silly story if you press the button again (and again...) the following screenshot shows an example of what the finished program should output: to give you more of an idea, have a look at the finished example (no peeking at the source code!) steps to complete the following sections describe what you need to do.
...And 3 more matches
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).
... try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor.
... try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor.
...And 3 more matches
What went wrong? Troubleshooting JavaScript - Learn web development
an erroneous example to get started, let's return to our number guessing game — except this time we'll be exploring a version that has some deliberate errors introduced.
... note: you might well have your own version of the game example that doesn't work, which you might want to fix!
...then you can go back and try to fix your example.
...And 3 more matches
Object-oriented JavaScript for beginners - Learn web development
for example, a student's greeting might be of the form "yo, i'm [firstname]" (e.g yo, i'm sam), whereas a teacher might use something more formal, such as "hello, my name is [prefix] [lastname], and i teach [subject]." (e.g hello, my name is mr griffiths, and i teach chemistry).
...for example: in the rest of the article, we'll start to look at how oop theory can be put into practice in javascript.
... a simple example let's start by looking at how you could define a person with a normal function.
...And 3 more matches
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).
... try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor.
... try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor.
...And 3 more matches
Measuring performance - Learn web development
for example, you can use performance metrics to determine how your app performs in comparison to a competitor or you can compare your app's performance across releases.
...a performance entry can be directly created by making a performance mark or measure (for example by calling the mark() method) at an explicit point in an application.
...you can also refer to the navigation and timings article for further examples on using performance web apis.
...And 3 more matches
TypeScript support in Svelte - Learn web development
if we pass an unknown property in the options parameter of the app constructor (for example a typo like traget instead of target) typescript will complain: in the app.svelte component, the setuptypescript.js script has added the lang="ts" attribute to the <script> tag.
...for example, if you start adding an ms property to the alert component call, typescript will infer from the default value that the ms property should be a number: and if you pass something that is not a number it will complain about it: the application template has a validate script configured that runs svelte-check against your code.
...so it is in fact any javascript object with a couple limitations, for example undefined, functions, and symbols are not valid json values.
...And 3 more matches
Getting started with Svelte - Learn web development
this is one example of svelte extending javascript syntax to make it more useful, while keeping it familiar.
... <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.
... at this point you can try updating your app.svelte component — for example change the <h1> element on line 6 of app.svelte so that it reads like this: <h1>hello {name} from mdn!</h1> just save your changes and the app running at localhost:5000 will be automatically updated.
...And 3 more matches
A bird's-eye view of the Mozilla framework
chrome and extensions are examples of packages.
... xpcom object model before getting into the details of the ui example, it's helpful to have a basic understanding of the xpcom object model.
...for example, a javascript object or c++ class could both implement the same xpidl interface.
...And 3 more matches
Command line options
for example, if you have multiple profiles you can use command line configuration options to bypass the profile manager and open a specific profile.
... each message option follows the syntax field=value, for example: to=foo@nowhere.net subject=cool page attachment=www.mozilla.org attachment='file:///c:/test.txt' body=check this page or also in thunderbird 52 and newer: body=c:\path\to\file.txt separate multiple message options by comma (,), for example: "to=foo@nowhere.net,subject=cool page" .
... to assign multiple values to a field, enclose the values in single quotes ('), for example: "to='foo@nowhere.net,foo@foo.de',subject=cool page" .
...And 3 more matches
Error codes returned by Mozilla APIs
for example, by using components.results.ns_error_not_initialized general errors the following errors are general and can occur when using any component.
...for example, if a character in the path is not valid for a filename.
...for example, an attempt was made to use the element.insertbefore method to insert a node before one that is not a child.
...And 3 more matches
Downloads.jsm
example (using task.jsm): try { yield downloads.fetch(sourceuri, targetfile); } catch (ex if ex instanceof downloads.error && ex.becausetargetfailed) { console.log("unable to write to the target file, ignoring the error."); } methods createdownload() creates a new download object.
... examples downloading to a local file this example downloads an html file without showing progress, handling errors programmatically.
... components.utils.import("resource://gre/modules/downloads.jsm"); components.utils.import("resource://gre/modules/osfile.jsm") components.utils.import("resource://gre/modules/task.jsm"); task.spawn(function () { yield downloads.fetch("http://www.mozilla.org/", os.path.join(os.constants.path.tmpdir, "example-download.html")); console.log("example-download.html has been downloaded."); }).then(null, components.utils.reporterror); observing downloads this example logs a message every time a change occurs in one of the global download lists.
...And 3 more matches
PromiseWorker.jsm
the above example can be rewritten like this: myworker.post('func', [new basepromiseworker.meta(buffer, {transfers: [buffer]})]); this is convenient if the function's arguments are generated by some other functions or passed from somewhere else.
...for example: myworker.post('func', [foo(), bar(), baz()]) foo now has the power to determine if the argument should be transferred by returning a meta instance.
... this example shows how to transfer a single value, which is an arraybuffer.
...And 3 more matches
gettext
in the above example, $num equals 1, so the string returned (for english) will be %d user likes this.
...gettext will return one of the msgstrs, depending on the number passed to the gettext function in the code ($num in the above example).
...for example, for english, the plural rule is of the following form: plural-forms: nplurals=2; plural=n != 1; the first part defines the number of different plural forms (2).
...And 3 more matches
Investigating leaks using DMD heap scan mode
if you are investigating a leak of www.example.com, then from $logdir you can do "grep nsglobalwindow cc-edges* | grep example.com".
... this looks through all of the windows in all of the cc logs (which may leaked, this late in shutdown), and then filters out windows where the url contains example.com.
... the result of that grep will contain output that looks something like this: cc-edges.15873.log:0x7f0897082c00 [rc=1285] nsglobalwindowinner # 2147483662 inner https://www.example.com/ * cc-edges.15873.log: the first part is the file name where it was found.
...And 3 more matches
DMD
for example, from javascript code you can do the following.
... here's an example stack trace record from the "unreported stack trace records" section.
...for example: reported at { #01: mozilla::dmd::report(void const*) (/home/njn/moz/mi2/memory/replace/dmd/dmd.cpp:1740) 0x7f68652581ca #02: cyclecollectormallocsizeof(void const*) (/home/njn/moz/mi2/xpcom/base/nscyclecollector.cpp:3008) 0x7f6860fdfe02 #03: nspurplebuffer::sizeofexcludingthis(unsigned long (*)(void const*)) const (/home/njn/moz/mi2/xpcom/base/nscyclecollector.cpp:933) 0x7f6860fdb7af #0...
...And 3 more matches
Gecko Profiler FAQ
for this purpose you should try to use a native profiler on your platform of choice (for example xperf/vtune on windows, instruments on osx, and perf/zoom on linux.) one workaround is to break the hot function into several explicitly-non-inline helpers, recompile, and re-profile.
... for example, see julian’s great investigation on the impact of cache line sharing across multiple cores on jemalloc’s multi-core performance in https://bugzilla.mozilla.org/show_bug.cgi?id=1291355#c26.
... on linux, perf does a good job at visualizing page faults, for example, they will show up as part of the same call stack as the user-space call stack for the program you are profiling.
...And 3 more matches
A guide to searching crash reports
for example, to perform a search for all mac crash reports that occurred while javascript garbage collection was running, do the following.
... grouping in the previous section we saw one example of grouping, in the "signature facet" tab that is shown by default.
... grouping by platform for example, if we start with a default search for all firefox crashes in the past week, but then replace the "signature" facet with "platform" and "moz crash reason", we get search results with two facet tabs.
...And 3 more matches
NSS Sample Code sample6
nss sample code 6: persistent symmetric keys in nss database /* example code to illustrate generation of a secret symmetric key ring * that persists in the nss database.
... * to decrypt, you need the ciphertext and the id of the key that was used * to encrypt * * before running this example, create the nss database * certutil -n -d .
...this example happens to use an * integer */ void genkey(int id); /* this callback is responsible for returning the password to the nss * key database.
...And 3 more matches
NSS_Initialize
certprefix [in] prefix added to the beginning of the certificate database, for example, "https-server1-".
... keyprefix [in] prefix added to the beginning of the key database, for example, "https-server1-".
...this is necessary if another piece of code is using the same pkcs#11 modules that nss is accessing without going through nss, for example, the java sunpkcs11 provider.
...And 3 more matches
NSS tools : pk12util
- key db conversion version 3 to version 2 error 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).
... pk12util -i p12file [-h tokenname] [-v] [-d [sql:]directory] [-p dbprefix] [-k slotpasswordfile|-k slotpassword] [-w p12filepasswordfile|-w p12filepassword] for example: # pk12util -i /tmp/cert-files/users.p12 -d sql:/home/my/sharednssdb enter a password which will be used to encrypt your keys.
... pk12util -o p12file -n certname [-c keycipher] [-c certcipher] [-m|--key_len keylen] [-n|--cert_key_len certkeylen] [-d [sql:]directory] [-p dbprefix] [-k slotpasswordfile|-k slotpassword] [-w p12filepasswordfile|-w p12filepassword] for example: # pk12util -o certs.p12 -n server-cert -d sql:/home/my/sharednssdb enter password for pkcs12 file: re-enter password: listing keys and certificates the information in a .p12 file are not human-readable.
...And 3 more matches
NSS Tools crlutil
-p dbprefix specify the prefix used on the nss security database files (for example, my_cert8.db and my_key3.db).
... for example: 20050204153000z add an extension to a crl or a crl certificate entry: addext extension-name critical/non-critical [arg1[arg2 ...]] where: extension-name: string value of a name of known extensions.
...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 ...
...And 3 more matches
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).
... pk12util -i p12file [-h tokenname] [-v] [-d [sql:]directory] [-p dbprefix] [-k slotpasswordfile|-k slotpassword] [-w p12filepasswordfile|-w p12filepassword] for example: # pk12util -i /tmp/cert-files/users.p12 -d sql:/home/my/sharednssdb enter a password which will be used to encrypt your keys.
... pk12util -o p12file -n certname [-c keycipher] [-c certcipher] [-m|--key_len keylen] [-n|--cert_key_len certkeylen] [-d [sql:]directory] [-p dbprefix] [-k slotpasswordfile|-k slotpassword] [-w p12filepasswordfile|-w p12filepassword] for example: # pk12util -o certs.p12 -n server-cert -d sql:/home/my/sharednssdb enter password for pkcs12 file: re-enter password: listing keys and certificates the information in a .p12 file are not human-readable.
...And 3 more matches
SpiderMonkey Build Documentation
for example, assuming your local nspr has been installed to c:/mozilla-build/msys/local: /bin/sh ../configure.in --with-nspr-cflags="-ic:/mozilla-build/msys/local/include" \ --with-nspr-libs="c:/mozilla-build/msys/local/lib/libnspr4.a \ c:/mozilla-build/msys/local/lib/libplds4.a \ c:/mozilla-build/msys/local/lib/libplc4.a" if you get ...
...for example, if you're using the gnu toolchain, the following will pass the -g3 flag to the compiler, causing it to emit debug information about macros.
... for example on debian linux you'll need the following to cross compile from x86_64 to x86.
...And 3 more matches
JIT Optimization Outcomes
this can occur if one of the expected types of objects to be used in this operation has unknown properties, or if different instances of the object store the property at different locations (for example, some instances have the property assigned in a different order than others).
... protoindexedprops the object being accessed has indexed properties that are exotic (for example, defined as a property on a prototype object and left as a hole in the underlying object).
...for example, if the array has sparse indexes, or has indexes that overflow the array's length, the optimization strategy may fail.
...And 3 more matches
JIT Optimization Strategies
in particular, arguments cannot be returned from the function, or passed as an argument into calls (except for the apply example listed above).
...for example, in the following code: var constants = {}; constants.n = 100; function testarray(array) { for (var i = 0; i < array.length; i++) { if (array[i] > constants.n) return true; } return false; } will have the loop compiled into the following when testarray gets hot.
...} in the above example, the properties x and y can always be determined to exist on any instance of someconstructor at definite locations, allowing the engine to infer deterministically the position of x without a shape guard.
...And 3 more matches
History Service Design
for example, is possible to create a query folder containing the 10 pages most visited by the user, allowing to fast find good candidates for bookmarking.
...many queries are especially optimized, for example limited history queries, often used to build menus, allowing for good performances even in presence of a really large history.
... certain scheme are excluded from history, so they will never be added, for example: about, view-source, chrome.
...And 3 more matches
Places Developer Guide
the example below shows how to enumerate a bookmark folder's contents, and how to access the properties of the items themselves.
...the example below shows how to search through all bookmarks, and to iterate over the results.
... // observers can use this to suspend updates to the user-interface, for example // while a batch change is occurring.
...And 3 more matches
Querying Places
example of querying for any pages i've visited that contain the word "firefox" in the title/url or that i've visited today from mozilla.org.
... example of serializing and deserializing two queries and an options object: let querystring = placesutils.history.queriestoquerystring([query1, query2], 2, options); let queriesref = { }; let querycountref = { }; let optionsref = { }; placesutils.history.querystringtoqueries(querystring, queriesref, querycountref, optionsref); // now use queriesref.value, optionsref.value see places query uris for mo...
...this section discusses how to access the result directly, for example, if you are creating your own view or are processing the results instead of displaying them.
...And 3 more matches
Components.utils.exportFunction
modifying the argument while cloning creates a copy of an object, an xray for an object refers to the original, so any changes to the argument that are made in the exported function will affect the original object that was passed in: // privileged scope: for example, a content script function changemyname(user) { user.name = "bill"; } exportfunction(changemyname, contentwindow, { defineas: "changemyname" }); // less-privileged scope: for example, a page script var user = {name: "jim"}; var test = document.getelementbyid("test"); test.addeventlistener("click", function() { console.log(user.name); // "jim" window.changemyname(user); ...
...console.log(user.name); // "bill" }, false); note that this is subject to the normal rules of xrays: for example, an expando property added to a dom node will not be visible in the original object.
...for the full details refer to the documentation for xray vision, but for example: functions are not visible in the xrays of javascript object types.
...And 3 more matches
nsIDOMWindowUtils
keep in mind that during a restyle operation, an element may be restyled multiple times (for example, when an inline element contains blocks).
... this is used on mobile, for example, to prevent attempts to render content until enough of the page has been loaded to avoid content bouncing around excessively as more content is loaded.
...this is used to locate nodes that are within some number of pixels of a point; for example, you can use this to find candidate target nodes when the user taps on a touch screen.
...And 3 more matches
nsILoginManagerStorage
1.0 66 introduced gecko 1.9 inherits from: nsisupports last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) for example, if you wish to provide operating system integration with a native password manager system, implementing and registering a storage module for the login manager is how you do it.
...this method is called, for example, to check to see if there is a login that will match the criteria without having to ask the user for their master password in order to decrypt the logins.
...for example: "http://www.site.com".
...And 3 more matches
Component; nsIPrefBranch
for example, if this object is created with the root "browser.startup.", the preferences "browser.startup.page", "browser.startup.homepage", and "browser.startup.homepage_override" can be accessed by simply passing "page", "homepage", or "homepage_override" to the various get/set methods.
...for example, if your observer is registered with addobserver("bar.", ...) on a branch with root "foo.", modifying the preference "foo.bar.baz" will trigger the observer, and adata parameter will be "bar.baz".
...for example holding the "root" prefbranch and calling addobserver("foo.bar.", ...) will observe changes to foo.bar.baz and foo.bar.bzip.
...And 3 more matches
nsISHistoryListener
iuri abackuri); boolean onhistorygoforward(in nsiuri aforwarduri); boolean onhistorygotoindex(in long aindex, in nsiuri agotouri); void onhistorynewentry(in nsiuri anewuri); boolean onhistorypurge(in long anumentries); boolean onhistoryreload(in nsiuri areloaduri, in unsigned long areloadflags); methods onhistorygoback() called when navigating to a previous session history entry, for example due to an nsiwebnavigation.goback() call.
...onhistorygoforward() called when navigating to a next session history entry, for example due to an nsiwebnavigation.goforward() call.
...onhistorygotoindex() called when navigating to a session history entry by index, for example, when nsiwebnavigation.gotoindex() is called.
...And 3 more matches
nsIXULAppInfo
attributes attribute type description appbuildid acstring the application's build id/date, for example "2004051604".
...this must be ascii, and is normally mixed-case, for example "firefox", "thunderbird" or "seamonkey".
... platformversion acstring the version of gecko or xulrunner platform, for example "1.8.1.19" or "1.9.3pre".
...And 3 more matches
XPCOM reference
for example to move forward a message, you would call:nsmsgsearchopvaluedefined in comm-central/ mailnews/ base/ search/ public/ nsmsgsearchcore.idl nsmsgviewcommandcheckstatethe nsmsgviewcommandcheckstate interface contains constants used for command status in thunderbird.
...for example to mark a message read, you would call:nsmsgviewflagstypethe nsmsgviewflagstype interface contains constants used for view flags in thunderbird.
...for example, the 'unread only' view would use the flag:nsmsgviewsortorderthe nsmsgviewsortorder interface contains constants used for sort direction in thunderbird.
...And 3 more matches
Storage
opening a connection javascript example of opening my_db_file_name.sqlite in the profile directory: components.utils.import("resource://gre/modules/services.jsm"); components.utils.import("resource://gre/modules/fileutils.jsm"); let file = fileutils.getfile("profd", ["my_db_file_name.sqlite"]); let dbconn = services.storage.opendatabase(file); // will also create the file if it does not exist likewise, the c++ would look like this:...
...cutesimplesql(ns_literal_cstring("create temp table table_name (column_name integer)")); ns_ensure_success(rv, rv); results to be returned however, if you need to get results back, you should create the statement with the mozistorageconnection.createstatement() api like this in javascript: var statement = dbconn.createstatement("select * from table_name where column_name = :parameter"); this example uses a named placeholder called "parameter" to be bound later (described in binding parameters).
... similarly, the c++ looks like this: nscomptr<mozistoragestatement> statement; rv = dbconn->createstatement(ns_literal_cstring("select * from table_name where column_name = ?1"), getter_addrefs(statement)); ns_ensure_success(rv, rv); this example uses the numbered placeholder indexed by zero for a parameter to be bound later (described in binding parameters).
...And 3 more matches
Filelink Providers
the hightail implementation is a great place to look for examples and inspiration.
...see cloudfile/cloudfilecomponents.manifest for an example, as well as this document on chrome.manifest files.
...hightail, for example, requires a username and password.
...And 3 more matches
Mail and RDF
here is an example of how this might be set up: in this tree-style representation of an rdf graph, i've made arcs italic and resources bold.
...for example...???
... for example, the folder pane needs to display the number of messages in the inbox.
...And 3 more matches
Debugger.Object - Firefox Developer Tools
for example, in firefox, code in privileged compartments sees content dom element objects without redefinitions or extensions made to that object's properties by content code.
...for example: function f() {} // display name: f (the given name) var g = function () {}; // display name: g o.p = function () {}; // display name: o.p var q = { r: function () {} // display name: q.r }; note that the display name may not be a proper javascript identifier, or even a proper expression: we attempt to find helpful names even when the function is not immediately assigned a...
...for example: function h() { var i = function() {}; // display name: h/i f(function () {}); // display name: h/< } var s = f(function () {}); // display name: s< parameternames if the referent is a debuggee function, the names of the its parameters, as an array of strings.
...And 3 more matches
DevTools API - Firefox Developer Tools
example here's a minimal definition for a tool.
... example here's a basic template for a toolpanel implementation.
... examples here's a few examples using the gdevtools object.
...And 3 more matches
Network request list - Firefox Developer Tools
for example, "csp", "malware", "cors missing allow origin", "blocked by [name of extension]".
... image thumbnails if the request is for an image, hovering over its filename shows a preview of the image in a tooltip: security icons the network monitor displays an icon in the domain column: this gives you extra information about the security status of the request: icon meaning https weak https (for example, a weak cipher was used) failed https (for example, a certificate was invalid) http localhost indicates that the url belongs to a known tracker that would be blocked with content blocking enabled.
...ou can filter by plain text (in which case the text is used to find partial matches; entering "for" will match any message that contains the word "for") or—as of firefox 75—using regular expressions (by writing the regexp bracketed within slashes; "/.+corp.*/" will look for any occurrence of "corp" which has at least one character before it and may or may not have any characters after it, for example).
...And 3 more matches
Examine and edit HTML - Firefox Developer Tools
for example, //a matches all <a> elements but not the letter "a" within the text content.
... furthermore it allows for some more advanced searches like finding elements that start with a specific text, for example.
...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.
...And 3 more matches
Work with animations - Firefox Developer Tools
to see how it works, we'll walk through an example.
... let's use the animation inspector to see what's going on in this example.
...in the example above you can see that the first bar is concave, representing ease-in, and the second is convex, representing ease-out.
...And 3 more matches
Paint Flashing Tool - Firefox Developer Tools
the paint flashing tool, when activated, highlights the part of a page that the browser needs to repaint in response to some input: for example, the user moving the mouse or scrolling.
...for example, a repaint will be needed if the user scrolls the page or moves the mouse pointer over an element with a :hover pseudo-class that changes the element's style.
...layers are painted independently and then composited, so a change in the appearance of one layer does not trigger a repaint in any other layers, and when only the relation of two layers changes (in an animation, for example) no repaints are required at all.
...And 3 more matches
AudioListener - Web APIs
retrieval is done by accessing, for example, audiolistener.positionx, while setting the same property is done with audiolistener.positionx.value.
...for example setposition(x, y, z) can be achieved by setting positionx.value, positiony.value, and positionz.value respectively.
... example in the following example, you can see an example of how the createpanner() method, audiolistener and pannernode would be used to control audio spatialisation.
...And 3 more matches
AudioWorkletProcessor.process - Web APIs
however, plans are already in place to revise the specification to allow the size of the audio blocks to be changed depending on circumstances (for example, if the audio hardware or cpu utilization is more efficient with larger block sizes).
...for example, inputs[n][m][i] will access n-th input, m-th channel of that input, and i-th sample of that channel.
...for example, take the audiobuffersourcenode — the processor behind such a node should return true from the process method while the buffer is playing, and start returning false when the buffer playing has ended (there's no way to call play on the same audiobuffersourcenode again).
...And 3 more matches
Bluetooth.requestDevice() - Web APIs
for example, options.filters is present and options.acceptalldevices is true, or if options.filters is not present and options.acceptalldevices is false.
...for example, it is called from insecure origin.
... example // discovery options match any devices advertising: // .
...And 3 more matches
Using dynamic styling information - Web APIs
setting the border property, for example, will override settings made elsewhere for that element's border property in the head section, or external style sheets.
... however, this will not affect any other property declarations for that element's styles, such as padding or margin or font, for example.
... to change a particular element's style, you can adapt the following example for the element(s) you want to style.
...And 3 more matches
Cache - Web APIs
WebAPICache
the cache interface provides a storage mechanism for request / response object pairs that are cached, for example as part of the serviceworker life cycle.
... examples this code snippet is from the service worker selective caching sample.
...though there's only one cache in this example, the same approach can be used for multiple caches.
...And 3 more matches
Pixel manipulation with canvas - Web APIs
for example, to read the blue component's value from the pixel at column 200, row 50 in the image, you would do the following: bluecomponent = imagedata.data[((50 * (imagedata.width * 4)) + (200 * 4)) + 2]; if given a set of coordinates (x and y), you may end up doing something like this: var xcoord = 50; var ycoord = 100; var canvaswidth = 1024; function getcolorindicesforcoord(x, y, width) { var red ...
... a color picker in this example we are using the getimagedata() method to display the color under the mouse cursor.
... for example, to paint the entire image represented by myimagedata to the top left corner of the context, you can simply do the following: ctx.putimagedata(myimagedata, 0, 0); grayscaling and inverting colors in this example we iterate over all pixels to change their values, then we put the modified pixel array back to the canvas using putimagedata().
...And 3 more matches
Transformations - Web APIs
a save and restore canvas state example this example tries to illustrate how the stack of drawing states functions by drawing a set of consecutive rectangles.
... a translate example this example demonstrates some of the benefits of translating the canvas origin.
... a rotate example in this example, we'll use the rotate() method to first rotate a rectangle from the canvas origin and then from the center of the rectangle itself with the help of translate().
...And 3 more matches
Using images - Web APIs
for example, if you have a <video> element with the id "myvideo", you can do this: function getmyvideo() { var canvas = document.getelementbyid('canvas'); if (canvas.getcontext) { var ctx = canvas.getcontext('2d'); return document.getelementbyid('myvideo'); } } this returns the htmlvideoelement object for the video, which, as covered earlier, is one of the objects that can be used as a canv...
... example: a simple line graph in the following example, we will use an external image as the backdrop for a small line graph.
...in this example, we're only using one image, so i use the image object's load event handler to execute the drawing statements.
...And 3 more matches
Element.innerHTML - Web APIs
WebAPIElementinnerHTML
for example, you can erase the entire contents of a document by clearing the contents of the document's body attribute: document.body.innerhtml = ""; this example fetches the document's current html markup and replaces the "<" characters with the html entity "&lt;", thereby essentially converting the html into raw text.
...for example: const name = "<img src='x' onerror='alert(1)'>"; el.innerhtml = name; // shows the alert for that reason, it is recommended that you do not use innerhtml when inserting plain text; instead, use node.textcontent.
...for example, if you use innerhtml in a browser extension and submit the extension to addons.mozilla.org, it will not pass the automated review process.
...And 3 more matches
Using the Frame Timing API - Web APIs
this document describes how to use the performanceframetiming interfaces including example code.
...in the following example, two observers for the "frame" performance entry type are created and the first observer constructor uses inline function syntax.
...in the following example, the observer only registers for "frame" performance entry notifications.
...And 3 more matches
install - Web APIs
method of installtrigger object syntax int install(array xpilist [, function callbackfunc ] ) parameters the install method has the following parameters: xpilist an array of files to be installed (see example below).
... callbackfunc an optional callback function invoked when the installation is complete (see example below).
...to surface detail about the status of the installation, use the optional callback function and its status parameter, as in the example below.
...And 3 more matches
Timing element visibility with the Intersection Observer API - Web APIs
although many aspects of this example will not match real world usage (in particular, the articles all have the same text and aren't loaded from a database, and there are just a handful of simple text-only ads that are selected from an array), this should provide enough understanding of the api to quickly learn how to apply the intersection observer api to your own site.
... there's a good reason why the notion of tracking visibility of ads is being used in this example.
... the header the header is fairly simple, since for this example all it contains is some text.
...And 3 more matches
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).
...And 3 more matches
MediaTrackConstraints.cursor - Web APIs
for example, if your app needs to alter the stream by inserting a representation of the cursor position if the stream doesn't include the rendered cursor, you can determine the need to do so by using code like this: let insertfakecursorflag = false; if (displaystream.getvideotracks()[0].getsettings().cursor === "never") { insertfakecursorflag = true; } following this code, insertfakecursorflag is true ...
... examples here are some example constraints objects for getdisplaymedia() that make use of the cursor property.
... in addition, see example: constraint exerciser in capabilities, constraints, and settings for a complete example showing how constraints are used.
...And 3 more matches
Navigator.registerProtocolHandler() - Web APIs
for example, this api lets webmail sites open mailto: urls, or voip sites open tel: urls.
...for example, you can register to handle sms text message links by passing the "sms" scheme.
... for example, web+burger, as shown in the example below.
...And 3 more matches
Using the Permissions API - Web APIs
historically, different apis handle their own permissions inconsistently — for example the notifications api allows for explicit checking of permission status and requesting permission, whereas the geolocation api doesn't (which causes problems if the user denied the initial permission request, as we'll see below).
...for example, it can query whether permission to use a particular api is granted or denied, and specifically request permission to use an api.
... a simple example for this article, we have put together a simple demo called location finder.
...And 3 more matches
Using Pointer Events - Web APIs
this example is based on the one in the touch events overview, except it uses the pointer events input event model.
... example the text below uses the term "finger" when describing the contact with the surface, but it could, of course, also be a stylus, mouse, or other method of pointing at a location.
...</canvas> <br> <button onclick="startup()">initialize</button> <br> log: <pre id="log" style="border: 1px solid #ccc;"></pre> setting up the event handlers when the page loads, the startup() function shown below should be called by our <body> element's onload attribute (but in the example we use a button to trigger it, due to limitations of the mdn live example system).
...And 3 more matches
Sensor APIs - Web APIs
for example, the accelerometer interface returns the acceleration of the device along all three axes at the time it is read.
...for example, the gyroscope interface corresponds exactly to a physical device interface.
... the examples below show three methods for detecting sensor apis.
...And 3 more matches
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.
...And 3 more matches
Using the User Timing API - Web APIs
a live version of the examples is available on github, as is the source code.
...the method takes one argument, the name of the mark, as shown in the following example.
...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.
...And 3 more matches
Adding 2D content to a WebGL context - Web APIs
drawing the scene the most important thing to understand before we get started is that even though we're only rendering a square plane object in this example, we're still drawing in 3d space.
... let's take a quick look at the two types of shader, with the example in mind of drawing a 2d shape into the webgl context.
... in this example, we're not computing any lighting at all, since we haven't yet applied any to the scene.
...And 3 more matches
Rendering and the WebXR frame animation callback - Web APIs
120 hz—or 120 frame per second—displays are increasingly common, for example.
...for example, a 60 hz display has 1/60th of a second to render a single frame, or 0.0166667 seconds.
...since in the example above we gave this function the name mydrawframe(), we'll continue to use that here.
...And 3 more matches
WebXR Device API - Web APIs
webxr device api concepts and usage example webxr hardware setup while the older webvr api was designed solely to support virtual reality (vr), webxr provides support for both vr and augmented reality (ar) on the web.
...for example, a given xr device might have two views: one for the left eye and one for the right.
...for example, it takes two views to create the stereoscopic view as perceived by human vision—one for the left eye and a second for the right eye.
...And 3 more matches
Using the Web Audio API - Web APIs
we'll briefly look at some concepts, then study a simple boombox example that allows us to load an audio track, play and pause it, and change its volume and stereo panning.
...for example, there is no ceiling of 32 or 64 sound calls at one time.
... example code our boombox looks like this: note the retro cassette deck with a play button, and vol and pan sliders to allow you to alter the volume and stereo panning.
...And 3 more matches
Window.sessionStorage - Web APIs
in particular, data stored by a script on a site accessed with http (e.g., http://example.com) is put in a different sessionstorage object from the same site accessed with https (e.g., https://example.com).
... exceptions securityerror the request violates a policy decision, or the origin is not a valid scheme/host/port tuple (this can happen if the origin uses the file: or data: scheme, for example).
... for example, the user may have their browser configured to deny permission to persist data for the specified origin.
...And 3 more matches
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 myaddr...
...essid"/> </div> example 2: associating headings with regions in the example below, header elements are associated with the content they head.
...And 3 more matches
ARIA: figure role - Accessibility
<div role="figure" aria-labelledby="caption"> <img src="image.png" alt="full alternative image description"> <p id="caption">figure 1: the caption</p> </div> in the above example, we have a figure that consists of two separate content items — an image and a caption.
...for example, make sure it is perceivable by users of assistive technology, navigable by keyboard as well as mouse, and so on.
...see best practices for a full example.
...And 3 more matches
Web applications and ARIA FAQ - Accessibility
user interface library (yui) for more information about javascript toolkit accessibility: steve faulkner's wai-aria implementation in javascript ui libraries can you show me an example of aria in action?
...in this example, the role="progressbar" attribute informs the browser that this element is actually a javascript-powered progress bar widget.
...instead, use javascript to dynamically add aria to your page, as shown in the answer to can you show me an example of aria in action?
...And 3 more matches
Multipart labels: Using ARIA for labels with embedded fields inside them - Accessibility
a classic example we all know from our browser settings is the setting “delete history after x days”.
... “delete history after” is to the left of the textbox, x is the number, for example 21, and the word “days” follows the textbox, forming a sentence that is easy to understand.
... both aria-labelledby and aria-describedby are specified on the form element that is to be labelled, for example an <input> in both cases, the label for/label control bindings that may also exist are overridden by aria-labelledby.
...And 3 more matches
@font-face - CSS: Cascading Style Sheets
since firefox 61 (and in other modern browsers) this also accepts two values to specify a range that is supported by a font-face, for example font-stretch: 50% 200%; font-style a font-style value.
... since firefox 61 (and in other modern browsers) this also accepts two values to specify a range that is supported by a font-face, for example font-style: oblique 20deg 50deg; font-weight a font-weight value.
... since firefox 61 (and in other modern browsers) this also accepts two values to specify a range that is supported by a font-face, for example font-weight: 100 400; font-variant a font-variant value.
...And 3 more matches
Handling content breaks in multicol - CSS: Cascading Style Sheets
for example, we would generally prefer that the figcaption of an image not be separated into a new column away from the image it refers to and ending a column with a heading looks strange.
... there are various places we might want to control our breaks: breaks inside boxes, for example inside a figure element.
... breaks before and after boxes, which would include our heading example above.
...And 3 more matches
Using multi-column layouts - CSS: Cascading Style Sheets
e.g., example 1 html <div id="col"> <p> lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
... example 2 html <div id="wid"> lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
... example 3 html <div id="col_short"> lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
...And 3 more matches
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.
... in the live example below i have added a focus style in order that as you tab from link to link you can see which is highlighted.
... as an example, i have 5 flex items, and assign order values as follows: source item 1: order: 2 source item 2: order: 3 source item 3: order: 1 source item 4: order: 3 source item 5: order: 1 these items would be displayed on the page in the following order: source item 3: order: 1 source item 5: order: 1 source item 1: order: 2 source item 2: order: 3 source item 4: order: 3 you can play a...
...And 3 more matches
Flow Layout and Writing Modes - CSS: Cascading Style Sheets
the block flow direction is the direction in which boxes, for example paragraphs, stack in that writing mode.
... the following example shows blocks using horizontal-tb.
... the value vertical-rl gives you a right-to-left block flow direction with a vertical inline direction, as shown in the next example.
...And 3 more matches
CSS Grid Layout and Accessibility - CSS: Cascading Style Sheets
in order to lay the design out in the table we often broke up the content in ways that made no sense at all when read out by a screen reader for example.
...you can see how this works with a very simple example.
... in this example i have used grid to lay out a set of boxes that contain links.
...And 3 more matches
CSS Grid Layout and Progressive Enhancement - CSS: Cascading Style Sheets
in the example below, i have a simple media object.
...tom: 1em; } .media::after { content: ""; display: block; clear: both; } .media .image { float: left; width: 150px; margin-right: 20px; } .media .text { padding: 10px; align-self: end; } <div class="media"> <div class="image"><img src="https://udn.realityripple.com/samples/89/f993f273dd.png" alt="placeholder"></div> <div class="text">this is a media object example.
... i am using floats for older browsers and grid for new ones.</div> </div> the image below shows the media object in a non-supporting browser on the left, and a supporting one on the right: using feature queries the above example is very simple, and we can get away without needing to write code that would be a problem to browsers that do not support grid, and legacy code is not an issue to our grid supporting browsers.
...And 3 more matches
Basic concepts of Logical Properties and Values - CSS: Cascading Style Sheets
an example of why these mappings might be needed is as follows.
... you can try this out in the live example below.
...some of the properties are essentially mappings from the physical versions, for example inline-size for width or margin-inline-start rather than margin-left.
...And 3 more matches
Logical properties for floating and positioning - CSS: Cascading Style Sheets
float and clear example the physical values used with the float and clear properties are left, right and both.
... in the example below i have two boxes — the first has the box floated with float: left, the second with float: inline-start.
... example: inset properties for positioned layout positioning generally allows us to position an element in a manner relative to its containing block — we essentially inset the item relative to where it would fall based on normal flow.
...And 3 more matches
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.
... in the example below i have created two boxes and added different sized margins to each edge.
... 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.
...And 3 more matches
Using CSS transitions - CSS: Cascading Style Sheets
for example, if you change the color of an element from white to black, usually the change is instantaneous.
... 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 ...
...And 3 more matches
Layout and the containing block - CSS: Cascading Style Sheets
some examples the html code for all our examples is: <body> <section> <p>this is a paragraph!</p> </section> </body> only the css is altered in each instance below.
... example 1 in this example, the paragraph is statically positioned, so its containing block is <section> because it's the nearest ancestor that is a block container.
...body> <section> <p>this is a paragraph!</p> </section> </body> body { background: beige; } section { display: block; width: 400px; height: 160px; background: lightgray; } p { width: 50%; /* == 400px * .5 = 200px */ height: 25%; /* == 160px * .25 = 40px */ margin: 5%; /* == 400px * .05 = 20px */ padding: 5%; /* == 400px * .05 = 20px */ background: cyan; } example 2 in this example, the paragraph's containing block is the <body> element, because <section> is not a block container (because of display: inline) and doesn’t establish a formatting context.
...And 3 more matches
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.
... this is very much like specifying a specific width and height, since once you have one dimension and a ratio, the other dimension is implied, but it's still a useful example.
...it's always square, and is usable at any size, such as 32x32, 128x128, or 512x512, for example.
...And 3 more matches
background-repeat - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...example: an image with an original width of 260px, repeated three times, might stretch until each repetition is 300px wide, and then another image will be added.
...And 3 more matches
box-sizing - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...for example, if you have four boxes with width: 25%;, if any has left or right padding or a left or right border, they will not by default fit on one line within the constraints of the parent container.
...And 3 more matches
calc() - CSS: Cascading Style Sheets
WebCSScalc
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... formal syntax calc( <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> ) accessibility concerns when calc() is used for controlling text size, be sure that one of the values includes a relative length unit, for example: h1 { font-size: calc(1.5rem + 3vw); } this ensures that text size will scale if the page is zoomed.
...And 3 more matches
<gradient> - CSS: Cascading Style Sheets
WebCSSgradient
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...(be aware that older browsers may not use this behavior when using the transparent keyword.) examples linear gradient example a simple linear gradient.
...And 3 more matches
line-height - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...values given in em units may produce unexpected results (see example below).
...And 3 more matches
linear-gradient() - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... note also that the first example above does not exactly render as depicted in mozilla firefox (particularly version 80.0b3).
...And 3 more matches
repeating-conic-gradient() - CSS: Cascading Style Sheets
{{embedinteractiveexample("pages/css/function-repeating-conic-gradient.html")}} the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... description example repeating conic gradients include starbursts.
...And 3 more matches
text-align - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...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.
...And 3 more matches
text-underline-position - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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.
...And 3 more matches
Adding captions and subtitles to HTML5 video - Developer guides
captioned video example in this article, we will refer to the video player with captions example.
... this example uses an excerpt from the sintel open movie, created by the blender foundation.
... note: you can find the source on github, and also view the example live.
...And 3 more matches
Media events - Developer guides
event name description abort sent when playback is aborted; for example, if the media is playing and is restarted from the beginning, this event is sent.
... this is sent, for example, when the media has loaded enough that the duration is known.
... emptied the media has become empty; for example, this event is sent if the media has already been loaded (or partially loaded), and the load() method is called to reload it.
...And 3 more matches
The HTML autocomplete attribute - HTML: Hypertext Markup Language
"impp" a url for an instant messaging protocol endpoint, such as "xmpp:username@example.net".
... 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.
...And 3 more matches
<abbr>: The Abbreviation element - HTML: Hypertext Markup Language
WebHTMLElementabbr
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...see the example defining an abbreviation below.
...And 3 more matches
<article>: The Article Contents element - HTML: Hypertext Markup Language
WebHTMLElementarticle
examples include: a forum post, a magazine or newspaper article, or a blog entry.
... the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...And 3 more matches
<dfn>: The Definition element - HTML: Hypertext Markup Language
WebHTMLElementdfn
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...this is shown in the first example below.
...And 3 more matches
<fieldset>: The Field Set element - HTML: Hypertext Markup Language
WebHTMLElementfieldset
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... as the example above shows, the <fieldset> element provides a grouping for a part of an html form, with a nested <legend> element providing a caption for the <fieldset>.
...And 3 more matches
<input type="hidden"> - HTML: Hypertext Markup Language
WebHTMLElementinputhidden
for example, the id of the content that is currently being ordered or edited, or a unique security token.
... note: there is a live example below the following line of code — if it is working correctly, you should see nothing!
...let's look at some examples that illustrate its use.
...And 3 more matches
<kbd>: The Keyboard Input element - HTML: Hypertext Markup Language
WebHTMLElementkbd
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...see echoed input, below, for an example.
...And 3 more matches
<mark>: The Mark Text element - HTML: Hypertext Markup Language
WebHTMLElementmark
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...this might be used, for example, to indicate the words that matched a search operation.
...And 3 more matches
<nav>: The Navigation Section element - HTML: Hypertext Markup Language
WebHTMLElementnav
common examples of navigation sections are menus, tables of contents, and indexes.
... the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...And 3 more matches
<source>: The Media or Image Source element - HTML: Hypertext Markup Language
WebHTMLElementsource
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...please note that sizes will have its effect only if width dimension descriptors are provided with srcset instead of pixel ratio values (200w instead of 2x for example).
...And 3 more matches
<tbody>: The Table Body element - HTML: Hypertext Markup Language
WebHTMLElementtbody
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... examples below are some examples showing the use of the <tbody> element.
...And 3 more matches
<track>: The Embed Text Track element - HTML: Hypertext Markup Language
WebHTMLElementtrack
it lets you specify timed text tracks (or time-based data), for example to automatically handle subtitles.
... the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...And 3 more matches
HTML elements reference - HTML: Hypertext Markup Language
WebHTMLElement
common examples of navigation sections are menus, tables of contents, and indexes.
... <hr> the html <hr> element represents a thematic break between paragraph-level elements: for example, a change of scene in a story, or a shift of topic within a section.
...it lets you specify timed text tracks (or time-based data), for example to automatically handle subtitles.
...And 3 more matches
Using Feature Policy - HTTP
<origin(s)>: the feature is allowed for specific origins (for example, https://example.com).
... feature-policy: <feature name> <allowlist of origin(s)> for example, to block all content from using the geolocation api across your site: feature-policy: geolocation 'none' several features can be controlled at the same time by sending the http header with a semicolon-separated list of policy directives, or by sending a separate header for each policy.
... for example, the following are equivalent: feature-policy: unsized-media 'none'; geolocation 'self' https://example.com; camera *; feature-policy: unsized-media 'none' feature-policy: geolocation 'self' https://example.com feature-policy: camera *; the iframe allow attribute the second way to use feature policy is for controlling content within an iframe.
...And 3 more matches
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.
... if the url for a particular document is at https://example.com/documents/foo, the site could 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.
...And 3 more matches
Content-Security-Policy - HTTP
navigation directives navigation directives govern to which locations a user can navigate or submit a form, for example.
...so for compatibility with current browsers while also adding forward compatibility when browsers get report-to support, you can specify both report-uri and report-to: content-security-policy: ...; report-uri https://endpoint.example.com; report-to groupname in browsers that support report-to, the report-uri directive will be ignored.
... the exception to this is if the worker script's origin is a globally unique identifier (for example, if its url has a scheme of data or blob).
...And 3 more matches
Referrer-Policy - HTTP
for example, a document at https://example.com/page.html will send the referrer https://example.com/.
...for example, you can set the referrer policy for the entire document with a <meta> element with a name of referrer: <meta name="referrer" content="origin"> or set it for individual requests with the referrerpolicy attribute on <a>, <area>, <img>, <iframe>, <script>, or <link> elements: <a href="http://example.com" referrerpolicy="origin"> alternatively, a noreferrer link relation on an a, area, or link e...
...lement can be set: <a href="http://example.com" rel="noreferrer"> integration with css css can fetch resources referenced from stylesheets.
...And 3 more matches
Set-Cookie - HTTP
domain=<domain-value> set-cookie: <cookie-name>=<cookie-value>; path=<path-value> set-cookie: <cookie-name>=<cookie-value>; secure set-cookie: <cookie-name>=<cookie-value>; httponly set-cookie: <cookie-name>=<cookie-value>; samesite=strict set-cookie: <cookie-name>=<cookie-value>; samesite=lax set-cookie: <cookie-name>=<cookie-value>; samesite=none // multiple attributes are also possible, for example: set-cookie: <cookie-name>=<cookie-value>; domain=<domain-value>; secure; httponly attributes <cookie-name>=<cookie-value> a cookie begins with a name-value pair: a <cookie-name> can be any us-ascii characters, except control characters, spaces, or tabs.
... contrary to earlier specifications, leading dots in domain names (.example.com) are ignored.
... httponly optional forbids javascript from accessing the cookie, for example, through the document.cookie property.
...And 3 more matches
User-Agent - HTTP
<comment> zero or more comments containing more details; sub-product information, for example.
...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.
...And 3 more matches
HTTP Index - HTTP
WebHTTPIndex
17 content negotiation content negotiation, content negotiation reference, http, reference in http, content negotiation is the mechanism that is used for serving different representations of a resource at the same uri, so that the user agent can specify which is best suited for the user (for example, which language of a document, which image format, or which content encoding).
... 65 alt-svc draft, http, http header, needscompattable, needscontent, needsexample, reference the alt-svc header is used to list alternate ways to reach this website.
...the referer header allows servers to identify where people are visiting them from and may use that data for analytics, logging, or optimized caching, for example.
...And 3 more matches
HTTP Public Key Pinning (HPKP) - HTTP
this is important for example when the former key gets compromised.
... extracting the base64 encoded public key information note: while the example below shows how to set a pin on a server certificate, it is recommended to place the pin on the intermediate certificate of the ca that issued the server certificate, to ease certificates renewals and rotations.
... openssl s_client -servername www.example.com -connect www.example.com:443 | openssl x509 -pubkey -noout | openssl pkey -pubin -outform der | openssl dgst -sha256 -binary | openssl enc -base64 example hpkp header public-key-pins: pin-sha256="cupctazwkaasuywhhnedttwpy3obake3h2+sozs7sws="; pin-sha256="m8hztczm3eluxkcjr2s5p4hhybnf6lhkmjahkhpgpwe="; max-age=5184000; includesubdomains; report-uri="https://www.example.org/hpkp-report...
...And 3 more matches
Memory Management - JavaScript
example var x = { a: { b: 2 } }; // 2 objects are created.
...in the following example, two objects are created with properties that reference one another, thus creating a cycle.
... function f() { var x = {}; var y = {}; x.a = y; // x references y y.a = x; // y references x return 'azerty'; } f(); real-life example internet explorer 6 and 7 are known to have reference-counting garbage collectors for dom objects.
...And 3 more matches
extends - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... examples using extends the first example creates a class called square from a class called polygon.
...And 3 more matches
Default parameters - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... in the following example, if no value is provided for b when multiply is called, b's value would be undefined when evaluating a * b and multiply would return nan.
...And 3 more matches
arguments.callee - JavaScript
for example, this syntax worked: function factorial (n) { return !(n > 1) ?
...for example: [1, 2, 3, 4, 5].map(function factorial(n) { return !(n > 1) ?
...for example, if you cannot guarantee that a function f will not call an unknown function, it is not possible to inline f.
...And 3 more matches
getter - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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.
...And 3 more matches
Array.prototype.filter() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...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.
...And 3 more matches
Array.prototype.push() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... examples adding elements to an array the following code creates the sports array containing two elements, then appends two elements to it.
...And 3 more matches
Date.prototype.getYear() - JavaScript
for example, if the year is 2026, getyear() returns 126.
...for example, if the year is 1976, getyear() returns 76.
...for example, if the year is 1800, getyear() returns -100.
...And 3 more matches
Function.prototype.bind() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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.
...And 3 more matches
Function.name - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...if you rely on function.name, like in the example above, make sure your build pipeline doesn't change function names, or don't assume a function to have a particular name.
...And 3 more matches
Object.create() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...for example, here are two objects: oco = object.create( {} ); // create a normal object ocn = object.create( null ); // create a "null" object > console.log(oco) // {} -- seems normal > console.log(ocn) // {} -- seems normal here too, so far oco.p = 1; // create a simple property on normal obj ocn.p = 0; // create a simple property on "null" obj > console.log(oco) // {p: 1} -- still seems normal > cons...
...And 3 more matches
Iteration protocols - JavaScript
however, it is easy to create an object that satisfies both the iterator and iterable protocols (as shown in the example below).
... }, [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", done: false } console.log(iterator.nex...
...{ 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.
...And 3 more matches
empty - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... examples empty loop body the empty statement is sometimes used with loop statements.
...And 3 more matches
for...of - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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.
...And 3 more matches
let - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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.
...And 3 more matches
throw - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... examples throw an object you can specify an object when you throw an exception.
...And 3 more matches
try...catch - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...for example, when the exception occurs in the following code, control transfers to the catch-block.
...And 3 more matches
MathML documentation index - MathML
WebMathMLIndex
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.
... 4 mathml: deriving the quadratic formula beginner, education, example, guide, html5, mathml, needsbeginnerupdate this page outlines the derivation of the quadratic formula.
... 5 proving the pythagorean theorem beginner, example, guide, html5 math, math education, mathml, needsbeginnerupdate we will now prove the pythagorean theorem: 6 mathml attribute reference mathml, mathml reference this is an alphabetical list of mathml attributes.
...And 3 more matches
Autoplay guide for media and Web Audio APIs - Web media technologies
example: the autoplay attribute an <audio> element using the autoplay attribute might look like this: <audio id="musicplayer" autoplay> <source src="/music/chapter1.mp4"> </audio> example 2: detecting autoplay failure if you rely on autoplay for anything important, or if autoplay failure will impact your app in any way, you will probably want to be able to tell when it autoplay didn't begin.
... example: playing video this simple example plays the first <video> element found in the document.
... document.queryselector("video").play(); example: handling play() failures it's much easier to detect a failure to autoplay media when you use the play() method to start it.
...And 3 more matches
begin - SVG: Scalable Vector Graphics
WebSVGAttributebegin
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" widt...
..."85" y1="25" x2="85" y2="105" stroke="grey" stroke-width=".5" /> <text x="110" y="20" text-anchor="middle">8s</text> <line x1="110" y1="25" x2="110" y2="105" stroke="grey" stroke-width=".5" /> <line x1="10" y1="30" x2="110" y2="30" stroke="grey" stroke-width=".5" /> <line x1="10" y1="105" x2="110" y2="105" stroke="grey" stroke-width=".5" /> </svg> begin-1-offset.svg syncbase example <svg width="120" height="120" viewbox="0 0 120 120" xmlns="http://www.w3.org/2000/svg" version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink"> <!-- animated rectangles --> <rect x="10" y="35" height="15" width="0"> <animate attributetype="xml" attributename="width" to="50" id="first" begin="0s;third.end" dur="4s" /> </rect> <rect x="60" y="...
...="85" y1="25" x2="85" y2="105" stroke="grey" stroke-width=".5" /> <text x="110" y="20" text-anchor="middle">8s</text> <line x1="110" y1="25" x2="110" y2="105" stroke="grey" stroke-width=".5" /> <line x1="10" y1="30" x2="110" y2="30" stroke="grey" stroke-width=".5" /> <line x1="10" y1="105" x2="110" y2="105" stroke="grey" stroke-width=".5" /> </svg> begin-2-syncbase.svg event example <svg width="120" height="120" viewbox="0 0 120 120" xmlns="http://www.w3.org/2000/svg" version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink"> <!-- animated rectangle --> <rect x="10" y="35" height="15" width="0"> <animate attributetype="xml" attributename="width" from="0" to="100" begin="startbutton.click" dur="8s" fill="freeze" />...
...And 3 more matches
d - SVG: Scalable Vector Graphics
WebSVGAttributed
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 instr...
... 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 -8...
... 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="re...
...And 3 more matches
transform - SVG: Scalable Vector Graphics
ix} x_{\mathrm{newcoordsys}} \\ y_{\mathrm{newcoordsys}} \\ 1 \end{pmatrix} = \begin{pmatrix} a & c & e \\ b & d & f \\ 0 & 0 & 1 \end{pmatrix} \begin{pmatrix} x_{\mathrm{prevcoordsys}} \\ y_{\mathrm{prevcoordsys}} \\ 1 \end{pmatrix} = \begin{pmatrix} a x_{\mathrm{prevcoordsys}} + c y_{\mathrm{prevcoordsys}} + e \\ b x_{\mathrm{prevcoordsys}} + d y_{\mathrm{prevcoordsys}} + f \\ 1 \end{pmatrix} example html,body,svg { height:100% } <svg viewbox="0 0 200 200" xmlns="http://www.w3.org/2000/svg"> <rect x="10" y="10" width="30" height="20" fill="green" /> <!-- in the following example we are applying the matrix: [a c e] [3 -1 30] [b d f] => [1 3 40] [0 0 1] [0 0 1] which transform the rectangle as such: top left corner: oldx=10 oldy=10 newx = a * oldx + c * oldy +...
... in other words: xnew = xold + <x> ynew = yold + <y> example html,body,svg { height:100% } <svg viewbox="0 0 100 100" xmlns="http://www.w3.org/2000/svg"> <!-- no translation --> <rect x="5" y="5" width="40" height="40" fill="green" /> <!-- horizontal translation --> <rect x="5" y="5" width="40" height="40" fill="blue" transform="translate(50)" /> <!-- vertical translation --> <rect x="5" y="5" width="40" height="40" fill="red" ...
... example html,body,svg { height:100% } <svg viewbox="-50 -50 100 100" xmlns="http://www.w3.org/2000/svg"> <!-- uniform scale --> <circle cx="0" cy="0" r="10" fill="red" transform="scale(4)" /> <!-- vertical scale --> <circle cx="0" cy="0" r="10" fill="yellow" transform="scale(1,4)" /> <!-- horizontal scale --> <circle cx="0" cy="0" r="10" fill="pink" transform="scale(4,1)" /> <!-- no scale --> <circle cx="0" cy...
...And 3 more matches
SVG animation with SMIL - SVG: Scalable Vector Graphics
below are examples for the four different ways.
... animating attributes of an element the following example animates the cx attribute of a circle.
... dur the duration of the animation (for example, write '5s' for 5 seconds).
...And 3 more matches
Subresource Integrity - Web security
subresource integrity (sri) is a security feature that enables browsers to verify that resources they fetch (for example, from a cdn) are delivered without unexpected manipulation.
... example integrity string with base64-encoded sha384 hash: sha384-oqvuafxrkap7fdgccy5uykm6+r9gqq8k/uxy9rx7hnqlgyl1kpzqho1wx4jwy8wc so oqvuafxrkap7fdgccy5uykm6+r9gqq8k/uxy9rx7hnqlgyl1kpzqho1wx4jwy8wc is the "hash" part, and the prefix sha384 indicates that it's a sha384 hash.
... note: an integrity value's "hash" part is, strictly speaking, a cryptographic digest formed by applying a particular hash function to some input (for example, a script or stylesheet file).
...And 3 more matches
Communicating With Other Scripts - Archive of obsolete content
for example: if an add-on creates a single panel object and loads several content scripts into the panel at the same time, then they can interact with each other.
... for more discussion and an example please see content scripts: communicating with the add-on: content script to content script.
...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() ...
...And 2 more matches
Communicating using "port" - Archive of obsolete content
for example, to receive the context message in a content script associated with a context menu object, you would call the on function attached to the global self object: self.on("context", function() { // handle the message }); so the port property is essentially used here as a namespace for user-defined messages.
... this example uses the action button api, which is only available from firefox 29 onwards.
... for example, here's an add-on that creates a page-worker and a button.
...And 2 more matches
Modules - Archive of obsolete content
however, the following example shows how it can be used to load scripts from other locations: const { classes: cc interfaces: ci } = components; var instance = cc["@mozilla.org/moz/jssubscript-loader;1"]; var loader = instance.getservice(ci.mozijssubscriptloader); function loadscript(url) { loader.loadsubscript(url); } when a script is loaded, it is evaluated in the scope of the global object of the script that...
...this becomes a problem when two scripts try to define the same property: // index.js: loadscript("www.foo.com/a.js"); loadscript("www.foo.com/b.js"); foo; // => 5 // a.js: foo = 3; // b.js: foo = 5; in the above example, the value of foo depends on the order in which the subscripts are loaded: there is no way to access the property foo defined by "a.js", since it is overwritten by "b.js".
...using this new version of loadscript, we can now rewrite our earlier example as follows: // index.js: let a = loadscript("www.foo.com/a.js"); let b = loadscript("www.foo.com/b.js"); a.foo // => 3 b.foo; // => 5 // a.js: foo = 3; // b.js: foo = 5; importing names in addition to exporting properties from the script being loaded to the loading script, we can also import properties from the loading script to the script being loaded: function loadscript(url, imports) { ...
...And 2 more matches
remote/parent - Archive of obsolete content
for example, when the child process is sandboxed, modules won't be able to access the file system.
... examples property retrieval this first example shows fetching a simple property from every existing and future process.
...for example, the user might have closed a content tab.
...And 2 more matches
Modifying Web Pages Based on URL - Archive of obsolete content
to modify any pages that match a particular pattern (for example, "http://example.org/") as they are loaded, use page-mod module.
... keeping the content script in a separate file in the example above, we've supplied content script as a string.
... for example, if we save the script above under the add-on's data directory in a file called my-script.js: // import the page-mod api var pagemod = require("sdk/page-mod"); // import the self api var self = require("sdk/self"); // create a page-mod // it will run a script whenever a ".org" url is loaded // the script replaces the page contents with a message pagemod.pagemod({ include: "*.org", contentsc...
...And 2 more matches
Progress Listeners - Archive of obsolete content
in the examples below the progress listener is attached to the tabbrowser, which means you don't get any notifications for inactive tabs.
... example create an object which implements nsiwebprogresslistener: const state_start = ci.nsiwebprogresslistener.state_start; const state_stop = ci.nsiwebprogresslistener.state_stop; var mylistener = { queryinterface: xpcomutils.generateqi(["nsiwebprogresslistener", "nsisupportsweakreference"]), onstatechange: function(awebprogress, arequest, aflag, astatus) { // if you use mylistener for more than one tab/window, use // awebprogress.domwindow to obtain the tab/window which triggers the state change if (aflag & state_start) { // this fires when the load event is initiated } if...
...tions of the remaining functions see related documentation onprogresschange: function(awebprogress, arequest, curself, maxself, curtot, maxtot) {}, onstatuschange: function(awebprogress, arequest, astatus, amessage) {}, onsecuritychange: function(awebprogress, arequest, astate) {} } attach the progress listener to a <browser> or a <tabbrowser> element using addprogresslistener, for example for firefox put the following code in a load listener of a main window: gbrowser.addprogresslistener(mylistener); when used with a browser, the second argument is a mask which determines the type of events that will be received.
...And 2 more matches
Rosetta - Archive of obsolete content
also, regarding some languages (like c), it is even not well defined the meaning of part of their semantics in respect to a scope that is more restricted than the full access to the resources they usually deal with – imagine, for example, the meaning of a c pointer within a html page!
...call this function createecmasrc() and let us associate it with the c mime types: rosetta_c.js: a c compiler /* c compiler for rosetta */ (function () { if (!window.rosetta) { return; } /* this function takes as argument a plain text (in this case, a code written in c) and returns another plain text written in ecmascript */ function createecmasrc (scsrc) { /* this is just an empty example...
... now, all you need is to include rosetta.js and your compiler within your html page and you will be able to execute scripts written in c together with scripts written in ecmascript: example.html: html example <!doctype html> <html> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <title>rosetta c example</title> <script type="text/javascript" src="rosetta.js"></script> <script type="text/javascript" src="rosetta_c.js"></script> <script type="text/x-csrc"> #include <stdio.h> int main () { printf("hello world number 1!\n"); return 0; } </script> <scr...
...And 2 more matches
Extension Etiquette - Archive of obsolete content
make one only if you have a special feature that needs to be included — for example, a custom updater.
... theming if you have xul buttons in your extension that do functions similar to ones that already exist in a browser — for example, a feed reader that reloads and stops — use icons from the browser's theme.
... while these are among the most common examples of namespaces in which conflicts can occur, there are many others.
...And 2 more matches
Interaction between privileged and non-privileged pages - Archive of obsolete content
document.addeventlistener("message", function(e) { yourfunction(e); }, false, true); sending data from chrome to unprivileged document to "answer" the web page (e.g., return code), your extension can set an attribute or attach child elements on the event target element (<myextensiondataelement/> in this example).
...this can be done using the same principle as the above example.
... we can extend the above example with some data transfer from the extension to the web page.
...And 2 more matches
Chapter 2: Technologies used in developing extensions - Archive of obsolete content
some examples of xml-based markup languages include xhtml, which is html redefined on an xml base; svg, for expressing vector images; and mathml, for expressing mathematical formulas.
...for example, even though xhtml and svg have elements with the same name, these can be distinguished.
... listing 3: an example of a class definition in javascript function myclass() { } myclass.prototype = { property1 : true, property2 : 'string', method : function() { alert('hello, world!'); } }; var obj = new myclass(); obj.method(); dom: an api for manipulating xml documents the document object model (dom) is a technical standard promulgated by the w3c, and is an api for manipulating the contents of xm...
...And 2 more matches
Adding Events and Commands - Archive of obsolete content
for example: <button label="&xulschoolhello.defaultgreeting.label;" oncommand="xulschoolchrome.browseroverlay.changegreeting(event);" /> then on the javascript code you would have something like this: changegreeting : function(aevent) { // more stuff aevent.target.setattribute("label", somenewgreeting); } the target in this example is the button element, so clicking on it will change its text.
... 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.
...you can override pre-existing values, such as the label attribute value in the example.
...And 2 more matches
Adding windows and dialogs - Archive of obsolete content
an alert window is an example of this.
...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.
...And 2 more matches
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.
...(a standalone xul window can use an onload attribute.) example the following overlay will load the script “overlay.js” from the same directory as the overlay file into the window which it overlays.
... examples the following code will execute a simple script in a sandbox with the privilege level of the current content page.
...And 2 more matches
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.
...let's look at the preference service as an example of this.
...And 2 more matches
Bookmark Keywords - Archive of obsolete content
for example, a keyworded bookmark could be set up so that a user could type <tt>google spam and eggs</tt> and thereby trigger a google search for the words "spam and eggs." because these tools require bookmarks with specific keywords in order to work, they will be referred to hereafter as keymarks, as distinct from regular bookmarks.
... laying the groundwork we're going to pick a relatively easy example to illustrate this process: a keymark that will let the user jump straight to a specific bugzilla entry by entering its number.
...see figure 1 for an example.
...And 2 more matches
Embedding Mozilla in a Java Application using JavaXPCOM - Archive of obsolete content
for example: mozilla mozilla = mozilla.getinstance(); windowcreator creator = new windowcreator(); // implements nsiwindowcreator nsiservicemanager servicemanager = mozilla.getservicemanager(); nsiwindowwatcher windowwatcher = (nsiwindowwatcher) servicemanager .getservicebycontractid(ns_windowwatcher_contractid, nsiwindowwatcher.ns_iwindowwatcher_iid); windowwatcher.setwindowcreator(creator)...
...; in this example, we have a java class called windowcreator, which implements the nsiwindowcreator interface, and we want to register it with mozilla.
... another example: (taken from rayh.co.uk) // note, on linux, gtk has to be already initialized for this code to work mozilla moz = mozilla.getinstance(); // now we need to start an xul application, so we get an instance of the xpcom service manager nsiservicemanager servicemanager = moz.getservicemanager(); // now we need to get the @mozilla.org/toolkit/app-startup;1 service: nsiappstartup appstartup = (nsiappstartup)servicemanager.getservicebycontractid("@mozilla.org/toolkit/app-startup;1", nsiappstartup.ns_iappstartup_iid); // get the nsiwindowwatcher interface to the above nsiwindowcreator windowcreator = (nsiwindowcreator)appstartup.queryin...
...And 2 more matches
First run - Archive of obsolete content
for example, you may want to tell users how to use your jetpack or link to your jetpack's homepage.
...this example sets the first-run page to some html: var manifest = { firstrunpage: '<p>thanks for installing!
... visit my <a href="http://example.com/myjetpack">homepage</a>.</p>' }; this does the same but uses e4x xml: var manifest = { firstrunpage: <> <p> thanks for installing!
...And 2 more matches
First Run - Archive of obsolete content
for example, you may want to tell users how to use your jetpack or link to your jetpack's homepage.
...this example sets the first-run page to some html: var manifest = { firstrunpage: '<p>thanks for installing!
... visit my <a href="http://example.com/myjetpack">homepage</a>.</p>' }; this does the same but uses e4x xml: var manifest = { firstrunpage: <> <p> thanks for installing!
...And 2 more matches
Plug-n-Hack Phase1 - Archive of obsolete content
for example: var manifest = {"detail":{"url":"http://localhost:8080/manifest"}}; var evt = new customevent('configuresectool', manifest); it is suggested that browsers wishing to support pnh restrict handling of customevents such that they’re ignored where the event happens outside of user initiated actions.
... you can see an example of a configuration document in the zap pnh addon.
... there’s another (possibly out of date) example here.
...And 2 more matches
Supporting per-window private browsing - Archive of obsolete content
} } catch(e) { components.utils.reporterror(e); return; } } obtaining an nsiloadcontext for privacy-sensitive apis some apis (such as nsitransferable and nsiwebbrowserpersist) take nsiloadcontext arguments that are used to determine whether they should be classed as private or not (for example, whether the uri being persisted by saveuri should be added to the permanent download history).
...as an example, if an add-on adds a context menu item that accesses an api that requires an nsiloadcontext, the most relevant window is the one that owns the element being targeted by the context menu (element.ownerdocument.defaultview).
...however, sometimes you need to adjust the privacy status on a channel manually, for example, if you have created the channel directly yourself.
...And 2 more matches
Treehydra Manual - Archive of obsolete content
example treehydra script: function process_cp_pre_genericize(fn) { // fn is a function_decl, decl_saved_tree(fn) is ast print(fn); } gimple asts gimple asts are provided via the process_tree callback.
...example: function process_tree(fn) { // fn is a function_decl, decl_saved_tree(fn) is ast print(fn); } gimple cfgs process_tree can also provide gimple cfgs.
...in this example, we show how to access the gimple just after function inlining is performed.
...And 2 more matches
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.
...together these segments form the url spec with the following syntax: scheme://username:password@host:port/directory/filebasename.fileextension;param?query#ref for performance reasons the complete spec is stored in escaped form in the nsstandardurl object with pointers (position and length) to each basic segment and for the more global segments like path and prehost for example.
...for example, "%20" is the escaped encoding for the us-ascii space character.
...And 2 more matches
accesskey - Archive of obsolete content
for example, when a menu labeled 'file' has an accesskey of 'f', the generated label will be 'file'.
...for example, when an accesskey of an 'open' label is 'a', the generated label will be 'open (a)'.
...however in some languages, for example, in japanese, characters will not always map directly to single keys, and it is quite common to have labels which cannot have a single accesskey.
...And 2 more matches
XUL Events - Archive of obsolete content
the default action of the event can be prevented to prevent the popup to appear.popupshownthe popupshown event is executed when a <menupopup>, <panel> or <tooltip> has become visible.radiostatechangethe radiostatechange event is executed when the state of a <radio> element has changed.valuechangethe valuechange event is executed when the value of an element, <progress> for example, has changed.
...for example, a button can be activated by clicking on it with the mouse or by pressing enter while it has the focus.
...for example, if a box has a maximum size of 100 pixels, and only enough space for 80 pixels is available, the overflow event will be sent to the box.
...And 2 more matches
MenuButtons - Archive of obsolete content
for instance, in the following example, pressing the 'view' button will open a menu which allows the user to select from a set of radio menuitems.
...in the example below a toolbarbutton with an image has a menu associated with it.
...as with this example, the 'menu-button' type of button is usually used when the menu provides more specific options pertaining to the operation.
...And 2 more matches
Bindings - Archive of obsolete content
« previousnext » we can add more triples to the previous example to show more information.
... for example, a description could be added to a photo.
... <rdf:description rdf:about="http://www.xulplanet.com/ndeakin/images/t/palace.jpg" dc:title="palace from above"/> dc:description="view from the top of the tower looking east of the doges palace"/> if you try a full example based on this data, you will notice that only one result has been generated.
...And 2 more matches
Building Menus With Templates - Archive of obsolete content
here is an example using an xml source: <button type="menu" datasources="people.xml" ref="*" querytype="xml"> <template> <query expr="person"/> <action> <menupopup> <menuitem uri="?" label="?name"/> </menupopup> </action> </template> </button> <button label="children" oncommand="alert(this.previoussibling.childnodes.length);"/> in this example, the datasources attribute has been...
...the second button in the example displays an alert with the number of children the template-driven button has.
...here is an rdf example: <button label="houses in my neighbourhood" type="menu" datasources="template-guide-streets.rdf" ref="http://www.xulplanet.com/rdf/myneighbourhood" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"> <template> <rule rdf:type="http://www.xulplanet.com/rdf/house"> <menupopup> <menuitem uri="rdf:*" label="rdf:http://www.xulplanet.com/rdf/address"/> ...
...And 2 more matches
Template Builder Interface - Archive of obsolete content
they could also be used, for example, to generate html elements.
... this isn't a very common technique, however, here is an example of how this can be used: <html:div id="photoslist" datasources="template-guide-photos5.rdf" ref="http://www.xulplanet.com/rdf/myphotos" xmlns:html="http://www.w3.org/1999/xhtml"> <html:h1>my photos</html:h1> <template> <html:p uri="rdf:*"><textnode value="rdf:http://purl.org/dc/elements/1.1/title"/></html:p> </template> </html:div> this example generates three paragraphs.
...sometimes this is due to different whitespace handling for html and xul, which is why the content to generate in the above example is all on one line.
...And 2 more matches
Template and Tree Listeners - Archive of obsolete content
var somelistener = { item: null, willrebuild : function(builder) { this.item = builder.getresourceatindex(builder.root.currentindex); }, didrebuild : function(builder) { if (this.item) { var idx = builder.getindexofresource(this.item) if (idx != -1) builder.root.view.selection.select(idx); } } }; tree.builder.addlistener(somelistener); this example is very simple and just saves and restores the selected index after a rebuild.
...if you try an example using the code above, you will notice that the first tree will maintain the selection when the rebuild button is pressed, whereas in the second tree does not.
...the example above makes use of the getresourceatindex and getindexofresource methods.
...And 2 more matches
Using Recursive Templates - Archive of obsolete content
for example, using this xml datasource: <people> <group name="male"> <person name="napoleon bonaparte"/> <person name="julius caesar"/> <person name="ferdinand magellan"/> </group> <group name="female"> <person name="cleopatra"/> <person name="laura secord"/> </group> </people> we could display this data in a flat list by using the right query: <query expr="group/person/"> or, we could display one level for the two groups, and use another level f...
...<groupbox type="menu" datasources="people.xml" ref="*" querytype="xml"> <template> <query expr="*"/> <action> <vbox uri="?" class="indent"> <label value="?name"/> </vbox> </action> </template> </groupbox> in this simplified example, the xpath expression just gets the list of child elements of the reference node.
...in this example, both the parent groups and child people are displayed the same.
...And 2 more matches
SeaMonkey - making custom toolbar (SM ver. 1.x) - Archive of obsolete content
open the file in seamonkey (for example, by dragging it and dropping it in the navigator window, or by choosing file – open file...
... the next section in this tutorial contains examples of code that you can use to make your button do something useful.
... get a context menu for the image that you see here (for example, by right-clicking it).
...And 2 more matches
Adding Buttons - Archive of obsolete content
buttons are commonly used for the ok and cancel buttons in a dialog, for example.
...for example, ok or cancel.
... some examples of buttons example 1 : source view <button label="normal"/> <button label="disabled" disabled="true"/> the examples above will generate the buttons in the image.
...And 2 more matches
Adding Event Handlers to XBL-defined Elements - Archive of obsolete content
the last example in the previous section demonstrated this.
... in that example, oncommand handlers were added to some buttons.
...for example, a custom checkbox might have a checked property which needs to be changed when the user clicks the checkbox: <handlers> <handler event="mouseup" action="this.checked=!this.checked"/> </handlers> when the user clicks and releases the mouse button over the check box, the mouseup event is sent to it, and the handler defined here is called, causing the state of the checked property to be reversed...
...And 2 more matches
Adding Style Sheets - Archive of obsolete content
all the xul examples so far have actually been using a style sheet already.
...an example would be when a script changes the style, or where a difference in layout might change the meaning of the element.
...our find files dialog example let's modify the find files dialog so that its style comes from a separate style file.
...And 2 more matches
Install Scripts - Archive of obsolete content
for example, you may wish to check versions of files and only install updated files, or perhaps you wish to apply patches to existing files.
...for example: /xulplanet/find files /netscape/personal security manager the first example is what we'll use for the find files dialog.
...the syntax of this function is as follows: initinstall( ''packagename'' , ''regpackage'' , ''version'' ); an example initinstall("find files","/xulplanet/find files","0.5.0.0"); the first argument is the name of the package in user-readable form.
...And 2 more matches
Introduction to RDF - Archive of obsolete content
to see some example rdf/xml files, look at those provided with mozilla.
...rdf database let's take the example of a bookmarks list generated from rdf.
...for example, a selection of the fields in the mozilla bookmark list is described by the uris below: name http://home.netscape.com/nc-rdf#name bookmark name url http://home.netscape.com/nc-rdf#url url to link to description http://home.netscape.com/nc-rdf#description bookmark description last visited http:...
...And 2 more matches
Property Files - Archive of obsolete content
in addition, you may wish to display a message which is generated from a script, if, for example, you do not know the exact text to be displayed.
...an example is shown below: notfoundalert=no files were found matching the criteria.
...var strbundle = document.getelementbyid("strings"); var nofilesfound=strbundle.getstring("notfoundalert"); alert(nofilesfound); this example first gets a reference to the bundle using its id then, it looks up the string 'notfoundalert' in the property file.
...And 2 more matches
Splitters - Archive of obsolete content
an example is the mozilla browser window, where you can change the size of the sidebar panel by dragging the bar in-between the two frames.
... splitter example an example would be helpful here: example 1 : source view <hbox flex="1"> <iframe id="content-1" width="60" height="20" src="w1.html"/> <splitter collapse="before" resizeafter="farthest"> <grippy/> </splitter> <iframe id="content-2" width="60" height="20" src="w2.html"/> <iframe id="content-3" width="60" height="20" src="w3.html"/> <iframe id="content-4" width="60" height="20" ...
... for example, if you specified a minimum width of 30 pixels on panel 4 above, it would not shrink below that size.
...And 2 more matches
Updating Commands - Archive of obsolete content
<script src="chrome://global/content/globaloverlay.js"/> <command id="cmd_paste" oncommand="godocommand('cmd_paste');"/> <button label="paste" command="cmd_paste"/> the example above will implement a paste button.
...for example, the paste command is valid when a textbox has the focus and there is something on the clipboard to paste.
...in the example above, the command updater listens for the focus event.
...And 2 more matches
XBL Inheritance - Archive of obsolete content
for example, let's say you want to create an xbl button with a popup.
...for example, the following binding creates a textbox which adds the text 'http://www' to the beginning of its value when the f4 key is pressed.
... example 1 : source <binding id="textboxwithhttp" extends="chrome://global/content/bindings/textbox.xml#textbox"> <handlers> <handler event="keypress" keycode="vk_f4"> this.value="http://www"+value; </handler> </handlers> </binding> the xbl here extends from the xul textbox element.
...And 2 more matches
XUL Template Primer - Bindings - Archive of obsolete content
example to illustrate how <bindings> work, we'll examine this xul document, which builds a simple content model an rdf/xml file.
...in our example, the ?friend variable serves this purpose in the first <binding> element.
... the subject may refer to any variable that has been computed in the <conditions>, or it may refer to another <binding>'s object variable.[1] in our example, the second <binding>'s subject does this: the value for the ?addr variable is computed by the first <binding> the predicate must name the uri of an rdf property, in this case, nc:address.
...And 2 more matches
panel - Archive of obsolete content
ArchiveMozillaXULpanel
« 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 example, if the menu doesn't have room to open downward, it flips to open upward instead; this is a vertical flip.
...And 2 more matches
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"/> ...
...for example the permissions manager ui in firefox uses the same window for three dialogs: images, software installation and popups.
...And 2 more matches
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"...
...for example, for a menuitem in a menu you can add the following css rule when you want to use the value none: menupopup > menuitem, menupopup > menu { max-width: none; } dir type: one of the values below the direction in which the child elements of the element are placed.
...And 2 more matches
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.
...*/ list-style-image: url("chrome://global/skin/checkbox/cbox-check.gif"); } for example: create a css file.
...And 2 more matches
Mozilla release FAQ - Archive of obsolete content
for example, if you were to make a proposal to compress whole webpages before sending them, devise a new protocol to do so, research how http works, how html works, and think about all the good *and* bad points of reworking things.
... to start understanding the issues with this example, you should dig up the rfcs for the relevant protocols, any documents written on the subject, etc.
... for this particular example, you would want to go look at relevant topics stuart cheshire's discussion on latency versus bandwidth internet -- under the covers (by me) the rfc for http the w3's html 4.0 definition building mozilla i get x error when trying to build mozilla - what's wrong?
...And 2 more matches
Sunbird Theme Tutorial - Archive of obsolete content
for example, a theme can change the size and colour of the toolbar buttons, and provide different icons on the buttons.
...copy and paste the content from here, making sure that you scroll to get all of it: <?xml version="1.0"?> <rdf xmlns="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:em="http://www.mozilla.org/2004/em-rdf#"> <description about="urn:mozilla:install-manifest" em:id="just-testing@example.com" em:name="just testing" em:creator="rod whiteley" em:description="a test theme for sunbird" em:homepageurl="http://developer.mozilla.org/" em:version="0.1" em:internalname="testing" em:type="4" > <em:targetapplication><!-- sunbird --> <description em:id="{718e30fb-e89b-41dd-9da7-e25a45638b28}" em:minversion="0.2.9" em:maxversion=...
...for example, when i wrote this article i used this command in my theme directory: zip -0r testing-0.1.jar .
...And 2 more matches
-ms-filter - Archive of obsolete content
examples the following example shows how to use the -ms-filter attribute in internet explorer 8.
... code example: http://samples.msdn.microsoft.com/workshop/samples/author/dhtml/refs/filter_8.htm -ms-filter: 'progid:dximagetransform.microsoft.motionblur(strength=50), progid:dximagetransform.microsoft.basicimage(mirror=1)'; the following example shows how to use an inline style sheet to set the filter on an image.
... code example: http://samples.msdn.microsoft.com/workshop/samples/author/dhtml/refs/filter_h.htm <img style="filter:progid:dximagetransform.microsoft.motionblur(strength=50) progid:dximagetransform.microsoft.basicimage(mirror=1)" src="/workshop/samples/author/dhtml/graphics/cone.jpg" height="80px" width="80px" alt="cone"> the following example shows how to use scripting to set the filter on an image.
...And 2 more matches
Processing XML with E4X - Archive of obsolete content
variables and expressions can be used to create attribute values by simply wrapping them with braces ({}) and omitting quotation marks that would normally go around an attribute value, as the following example illustrates: var a = 2; var b = <foo bar={a}>"hi"</foo>; upon execution the variable is evaluated and quotes are automatically added where appropriate.
... the preceding example would result in an xml object which looks like this: <foo bar="2">"hi"</foo>.
... while one can interpolate attribute names as well as attribute values: var a = 'att'; var b = <b {a}='value'/>; alert(b); // gives: <b att="value"/> ...one cannot interpolate a whole expression at once (e.g., <b {a}>.) after executing the above example, the variable languages references an xml object corresponding to the <languages> node in the xml document.
...And 2 more matches
Archive of obsolete content
perhaps your target audience is people that are using older hardware, for example, and can't upgrade to the latest and greatest browsers.
...- some inline examples were removed because of technical limitations.
... they are actually replaced by ''-(example removed)-'' the goal of this handbook is to help you update websites to work with standards-based browsers and properly detect gecko.
...And 2 more matches
Desktop mouse and keyboard controls - Game development
we could write our own keycode object containing the key codes, for example: var keyboardhelper = { left: 37, up: 38, right: 39, down: 40 }; that way instead of using the codes to compare the input in the handler functions we could do something like this, which is arguably easier to remember: if(event.keycode == keyboardhelper.left) { leftpressed = true; } note: you can also find a list if the different keycodes and what keys they relate to in the keycode refere...
... you can see this example in action online at end3r.github.io/javascript-game-controls and the full source code can be found at github.com/end3r/javascript-game-controls.
...mes built with phaser by enabling the basic cursor keys in the create() function using the createcursorkeys() function: this.cursors = this.input.keyboard.createcursorkeys(); this creates four directional arrow keys for us: this.cursors.left; this.cursors.right; this.cursors.up; this.cursors.down; you can also define the keys on your own and offer an alternative, w a s d control mechanism for example: this.keyleft = this.input.keyboard.addkey(phaser.keycode.a); this.keyright = this.input.keyboard.addkey(phaser.keycode.d); this.keyup = this.input.keyboard.addkey(phaser.keycode.w); this.keydown = this.input.keyboard.addkey(phaser.keycode.s); to support both the cursor and w a s d keys, we need to do this: if(this.cursors.left.isdown || this.keyleft.isdown) { // move left } else if(this.c...
...And 2 more matches
First-class Function - MDN Web Docs Glossary: Definitions of Web-related terms
for example, in such a language, a function can be passed as an argument to other functions, can be returned by another function and can be assigned as a value to a variable.
... example | assign a function to a variable javascript const foo = function() { console.log("foobar"); } // invoke it using the variable foo(); we assigned an anonymous function in a variable, then we used that variable to invoke the function by adding parentheses () at the end.
... example | pass a function as an argument javascript function sayhello() { return "hello, "; } function greeting(hellomessage, name) { console.log(hellomessage() + name); } // pass `sayhello` as an argument to `greeting` function greeting(sayhello, "javascript!"); we are passing our sayhello() function as an argument to the greeting() function, this explains how we are treating the function as a value.
...And 2 more matches
Test your skills: WAI-ARIA - Learn web development
try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor.
... try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor.
... wai-aria 3 for this final wai-aria task, we return to an example we previously saw in the css and javascript skilltest.
...And 2 more matches
Combinators - Learn web development
body article p in the example below, we are matching only the <p> element which is inside an element with a class of .box.
...for example, to select only <p> elements that are direct children of <article> elements: article > p in this next example, we have an unordered list, nested inside of which is an ordered list.
...for example, to select all <img> elements that come right after <p> elements: p + img a common use case is to do something with a paragraph that follows a heading, as in my example below.
...And 2 more matches
Test your skills: sizing - Learn web development
try updating the live code below to recreate the finished example: for assessment or further work purposes, download the starting point for this task to work in your own editor or in an online editor.
... try updating the live code below to recreate the example as displayed in the image: for assessment or further work purposes, download the starting point for this task to work in your own editor or in an online editor.
... try updating the live code below to recreate the example as displayed in the image: for assessment or further work purposes, download the starting point for this task to work in your own editor or in an online editor.
...And 2 more matches
Test your skills: values and units - Learn web development
try updating the live code below to recreate the finished example: for assessment or further work purposes, download the starting point for this task to work in your own editor or in an online editor.
... try updating the live code below to recreate the example as displayed in the image: for assessment or further work purposes, download the starting point for this task to work in your own editor or in an online editor.
... try updating the live code below to recreate the example as displayed in the image: for assessment or further work purposes, download the starting point for this task to work in your own editor or in an online editor.
...And 2 more matches
Test your skills: Multicol - Learn web development
try updating the live code below to recreate the finished example: for assessment or further work purposes, download the starting point for this task to work in your own editor or in an online editor.
... try updating the live code below to recreate the finished example: for assessment or further work purposes, download the starting point for this task to work in your own editor or in an online editor.
... try updating the live code below to recreate the finished example: for assessment or further work purposes, download the starting point for this task to work in your own editor or in an online editor.
...And 2 more matches
Test your skills: position - Learn web development
try updating the live code below to recreate the finished example: as an extra challenge, can you change the target to display underneath the text?
... position two in the below example if you scroll the box the sidebar scrolls with the content.
... try updating the live code below to recreate the finished example: for assessment or further work purposes, download the starting point for this task to work in your own editor or in an online editor.
...And 2 more matches
CSS layout - 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.
... positioning positioning allows you to take elements out of the normal document layout flow, and make them behave differently, for example sitting on top of one another, or always remaining in the same place inside the browser viewport.
... beginner's guide to media queries the css media query gives you a way to apply css only when the browser and device environment matches a rule that you specify, for example "viewport is wider than 480 pixels".
...And 2 more matches
CSS FAQ - Learn web development
LearnCSSHowtoCSS FAQ
for example: /* heading default color is black */ h1 { color: red; } h1 { color: black; } this has changed with css 2; the keyword initial is now a valid value for a css property.
...</div> in the previous example the problem occurred on rules belonging to different elements, but it could happen also for the same element, because rule order is important.
...</div> in this example the body * selector applies the rule to all elements inside body, at any hierarchy level, including the .stockup class.
...And 2 more matches
HTML forms in legacy browsers - Learn web development
let's see some examples related to html forms.
...for example, the input of color type looks different in safari, chrome and firefox browser, but the color picker widget is the same in all browsers on a device as it opens up the operating system's native color picker.
...for example, if you declare input { font-size: 2rem; }, it will impact number, date, and text, but not color or range.
...And 2 more matches
Test your skills: Basic controls - Learn web development
try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor.
... try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor.
... try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor.
...And 2 more matches
Test your skills: Other controls - Learn web development
try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor.
... try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor.
... try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor.
...And 2 more matches
Test your skills: HTML text basics - Learn web development
try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor.
... try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor.
... try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor.
...And 2 more matches
Test your skills: HTML images - Learn web development
try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor.
... try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor.
... try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor.
...And 2 more matches
Test your skills: Multimedia and embedding - Learn web development
try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor.
... try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor.
... try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor.
...And 2 more matches
Function return values - Learn web development
let's return to a familiar example (from a previous article in this series): let mytext = 'the weather is cold'; let newstring = mytext.replace('cold', 'warm'); console.log(newstring); // should print "the weather is warm" // the replace() string function takes a string, // replaces one substring with another, and returns // a new string with the replacement made the replace() function is invoked on the mytext string, and is pas...
...(in these cases, our reference pages list the return value as void or undefined.) for example, in the displaymessage() function we built in the previous article, no specific value is returned when the function is invoked.
...we saw this in action recently in our random-canvas-circles.html example.
...And 2 more matches
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).
... so, try updating the live code below to recreate the finished example, following these steps: create four variables that contain numbers.
... try updating the live code below to recreate the finished example, following these steps: write a calculation that multiplies result and result2 together and assigns the result back to result.
...And 2 more matches
Test your skills: JSON - Learn web development
note: in the example 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).
... try updating the live code below to recreate the finished example: warning: to answer this question, you'll need to write your code into the live code window above.
... the example won't work locally, or in an environment like codepen or jsfiddle, because of something called cross-origin security.
...And 2 more matches
Starting our Svelte Todo list app - Learn web development
previous overview: client-side javascript frameworks next now that we have a basic understanding of how things work in svelte, we can start building our example app: a todo list.
...for example: <button class="btn toggle-btn" aria-pressed="true"> <span class="visually-hidden">show</span> <span>all</span> <span class="visually-hidden">tasks</span> </button> here, aria-pressed tells assistive technology (like screen readers) that the button can be in one of two states: pressed or unpressed.
... for example, if we add an <img> element to our todos.svelte component without its corresponding alt prop: <h1>svelte to-do list</h1> <img height="32" width="88" src="https://udn.realityripple.com/samples/b0/98dase3c7d.png"> the compiler will issue the following warning: (!) plugin svelte: a11y: <img> element should have an alt attribute src/components/todos.svelte 1: <h1>svelte to-do list</h1> 2: 3: <im...
...And 2 more matches
Getting started with Vue - Learn web development
in this article we'll look at a little bit of vue background, learn how to install it and create a new project, study the high-level structure of the whole project and an individual component, see how to run the project locally, and get it prepared to start building our example.
...currently it just has one example component.
... note: depending on the options you select when creating a new project, there might be other directories present (for example, if you choose a router, you will also have a views directory).
...And 2 more matches
Accessibility Features in Firefox
for example, it is possible to navigate to the desired link by pressing 2 letter keys rather than tabbing through many links to get there.
...for example, you can disable functions that websites use to move or resize windows, or to remove your status bar, to disable right-click contextual menus, change the status bar text, etc.
...for example, prefs.js gives access to a large number of configuration options not available in the preferences window.
...And 2 more matches
Accessible Toolkit Checklist
for example, lists of checkboxes are implemented in windows with images of checked and unchecked checkboxes.
...for example, a unique child id would be required for each tree item supporting the most important basic iaccessible events get_accparent: get the parent of an iaccessible.
... get_accname: get the "name" of the iaccessible, for example the name of a button, checkbox or menu item.
...And 2 more matches
Creating a spell check dictionary add-on
for example en-us, de-de or da.
...in addition to these required files, you may add optional files, for example to give your add-on an icon or to describe the license of the dictionary.
... here is an example of the install.rdf file.
...And 2 more matches
Cross Process Object Wrappers
for example, this frame script sends a dom node to chrome when the user clicks it, as the clicked property of the third argument: // frame script addeventlistener("click", function (event) { sendasyncmessage("my-e10s-extension-message", {}, { clicked : event.target }); }, false); in the chrome script, the dom node is now accessible through a cross process object wrapper, as a property of the objects prop...
...one of these shims provides the following behavior: whenever chrome code tries to access content directly (for example, through window.content or browser.contentdocument), it is given back a cpow that wraps the content object.
... 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.
...And 2 more matches
Limitations of chrome scripts
for example: whenever extensions try to access web content from the chrome process, the browser will return a cross process object wrapper that gives the chrome code synchronous access to the content.
...for example: // chrome code gbrowser.contentwindow; // null gbrowser.contentdocument; // null gbrowser.selectedbrowser.contentwindow; // null window.content; // null content; // null as a special note, docshells live in the content process, so they are also inaccessible: gbrowser.docshell; ...
...however, the domwindow is passed asynchronously, so by the time the chrome process receives it, the dom might have changed (for example, because code running in the content process modified it or we navigated to a different page).
...And 2 more matches
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 proce...
...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.
...And 2 more matches
Communicating with frame scripts
the example below sends a message named "my-e10s-extension-message", with a data payload containing details and tag properties, and exposes the event.target object as a cpow: // frame script addeventlistener("click", function (event) { sendasyncmessage("my-addon@me.org:my-e10s-extension-message", { details : "they clicked", tag : event.target.tagname }, { target : event.target }); }, fa...
... objects an object whose properties are any cpows exposed by the sender as the third argument to sendasyncmessage() in the example below the listener just logs all the messages details: // chrome script messagemanager.addmessagelistener("my-addon@me.org:my-e10s-extension-message", listener); function listener(message) { console.log(message.name); console.log(message.sync); console.log(message.data); console.log(message.target); console.log(message.objects); } so combining this message listener with the message ...
...> { target: <div#searchcontainer> } if your code requires access to a window (for example to run window.opendialog), and your message listener is run from somewhere without access to a window (e.g.
...And 2 more matches
Limitations of frame scripts
for example: nsifileinputstream nsifileoutputstream constructing a file from a string or nsifile (but file objects can be sent via message manager) htmlinputelement.mozsetfilenamearray (alternative: mozsetfilearray) file: uris, see bug 1187099 <...> xul and browser ui anything that tries to touch the browser ui or anything to do with xul is likely not to work in the content process.
... 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.
...And 2 more matches
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.
... while it may seem fairly innocencous in this toy example, real scripts often have a lot more functions and initialize some fairly heavyweight objects.
... additionally the example above does not clean unregister itself, thus leaking objects each time a tab is closed.
...And 2 more matches
Process scripts
for example, if you call the global frame message manager's loadframescript() function, then the script will be loaded separately into all open tabs.
... for example, in multiprocess firefox, if you need to use nsicontentpolicy to register a content policy, you must do this in the content process.
...ive messages from the chrome side, and to send messages to the chrome side: // process-script.js if (services.appinfo.processtype == services.appinfo.process_type_content) { dump("welcome to the process script in a content process"); } else { dump("welcome to the process script in the main process"); } // message is sent using contentprocessmessagemanager sendasyncmessage("hello"); in this example, the dump() statement will run once in each content process as well as in the main process.
...And 2 more matches
JavaScript-DOM Prototypes in Mozilla
as an example of this let's look at an html image element in a document.
...as an example: function bar() { alert("hello world!"); } document.images[0].__proto__.foo = bar; this would make every image in this document have a callable foo property (i.e.
...if you think back to the htmlimageelement examples above, those examples let you define new properties on all image elements.
...And 2 more matches
JNI.jsm
for example, the class of geckoappshell has the fully-qualified class name of org.mozilla.gecko.geckoappshell.
... var ia = intarray.new(5); // object { js#obj: cdata, length: 5 } ia.get(0); // 0 ia.get(1); // 0 ia.get(2); // 0 ia.get(3); // 0 ia.get(4); // 0 ia.set(2, 10); // void ia.get(2); // 10 ia.setelements(3, [50, 75]); // void ia.get(0); // 0 ia.get(1); // 0 ia.get(2); // 10 ia.get(3); // 50 ia.get(4); // 75 } finally { if (my_jenv) { jni.unloadclasses(my_jenv); } } casting this example shows how to cast, the casting happens at jni.classes.android.view.windowmanager.__cast__(wm) below: function main() { var my_jenv; try { my_jenv = jni.getforthread(); var sig = { windowmanager: 'landroid/view/windowmanager;', windowmanager_layoutparams: 'landroid/view/windowmanager$layoutparams;', viewgroup_layoutparams: 'landroid/vie...
...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.
...And 2 more matches
Promise
a reference to an existing promise may be received by different means, for example as the return value of a call into an asynchronous api.
...for example, the os.file.exists function returns a promise that will eventually fulfill with a boolean: promise<boolean> exists(string path); the rejection reason may be specified separately in the function's documentation, and is considered to be an error object unless otherwise specified.
...for example, if an exception occurs in one callback, it does not affect the execution of subsequent callbacks.
...And 2 more matches
Localizing with Koala
in a real-life situation, that would become for example "de" (for german) or "es-es" (for spanish in spain).
... translating to x-testing will basically consist of converting any strings to uppercase, for example "file" in original version (en-us) will become "file" in x-testing.
...user: type your name and your e-mail address in the form: "firstname lastname <me@example.com>" (be sure to type the wrapping quotes: "") note that you no longer have to edit the location now, it automatically fills in when you check the "mercurial" checkbox (e.g.
...And 2 more matches
Fonts for Mozilla 2.0's MathML engine
you may also want to check out the mozilla mathml torture test to test your installation against concrete examples.
...for example asana math is available in truetype format and there is an unofficial truetype conversion for stix fonts.
...mathml font selection with css you can get these fonts from the mathml-fonts add-on ; the xpi is just a zip archive that you can fetch and extract for example with the following command: wget https://addons.mozilla.org/firefox/downloads/latest/367848/addon-367848-latest.xpi -o mathml-fonts.zip; \ unzip mathml-fonts.zip -d mathml-fonts then copy the mathml-fonts/resource/ directory somewhere on your web site and ensure that the woff files are served with the correct mime type.
...And 2 more matches
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).
...here's an example to illustrate spacing around fences m ⁢ [ m ⁢ m ⁢ m ] ⁢ m ⁢ ( m ⁢ m ) ⁢ m ⁢ { m ⁢ m } ⁢ m ⁢ ⟨ m ⁢ m ⟩ ⁢ m ⁢ | m ⁢ m | ⁢ m ⁢ m m ⁢ [ m ⁢ m ⁢ m ] + ( m ⁢ m ) + { m ⁢ m } + ⟨ m ⁢ m ⟩ + | m ⁢ m | ⁢ m ⁢ m m ⁢ [ m ⁢ m ⁢ m ] ⁢ ( m ⁢ m ) ⁢ { m ⁢ m } ⁢ ⟨ m ⁢ m ⟩ ⁢ | m ⁢ m | ⁢ m ⁢ m in latex, all fencing symbols are symmetric - they have equal extent abov...
...And 2 more matches
Scroll-linked effects
the definition of a scroll-linked effect is an effect implemented on a webpage where something changes based on the scroll position, for example updating a positioning property with the aim of producing a parallax scrolling effect.
... 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.
... example 2: scroll snapping below is an implementation of scroll snapping, where the scroll position snaps to a particular destination when the user's scrolling stops near that destination.
...And 2 more matches
nss tech note2
for example, to log the softoken, use: nss_debug_pkcs11_module="nss internal pkcs #11 module" note: in the command prompt on windows, do not quote the name of the target module, otherwise the quotes are considered part of the name.
... for example, to log the softoken on windows, use: set nss_debug_pkcs11_module=nss internal pkcs #11 module the logger is available by default in debug builds.
...to enable this mode, set: nspr_log_modules=nss_mod_log:1 nspr_log_file=<logfile> the output format is: osthreadid[nsprthreadid]: c_xxx osthreadid[nsprthreadid]: rv = 0xyyyyyyyy for example, 1024[805ef10]: c_initialize 1024[805ef10]: rv = 0x0 1024[805ef10]: c_getinfo 1024[805ef10]: rv = 0x0 1024[805ef10]: c_getslotlist 1024[805ef10]: rv = 0x0 2.
...And 2 more matches
GCIntegration - SpiderMonkey Redirect 1
consider the following example.
...there are several examples of this usage in xpconnect.
...as a concrete example of this, imagine that we call getwrapper() on an nswrappercache instance.
...And 2 more matches
64-bit Compatibility
for example, consider this code: #define pointer_tagbits 3 static inline uintptr_t unmaskpointer(uintptr_t v) { return v & ~pointer_tagbits; } the value 3 will be inverted to 0xfffffffc, then zero-extended to 0x00000000fffffffc - a subtle and nasty bug, assuming it is unintended.
...this sort of bug happens surprisingly often - see bug 501324, bug 512866 for example.
...for example, this code will not load a native integer correctly on a 64-bit machine: struct object { void *data; }; lir->insload(lir_ld, objins, ins->insimm(offsetof(object, data))); lir_ld is 32-bit.
...And 2 more matches
Bytecode Descriptions
for example, object.prototype.hasownproperty is implemented this way (see js/src/builtin/object.js).
... for example, in with (date) { getfullyear(); }, the implicit this passed to getfullyear is date, not undefined.
...for example, delete super.prop; is allowed in methods, but always throws a referenceerror.
...And 2 more matches
JSAPI Cookbook
* otherwise, convert the number to floating point (see the next example).
... catch // javascript try { // try some stuff here; for example: foo(); bar(); } catch (exc) { // do error-handling stuff here } /* jsapi */ /* try some stuff here; for example: */ if (!js_callfunctionname(cx, global, "foo", 0, null, &r)) goto catch_block; /* instead of returning false */ if (!js_callfunctionname(cx, global, "bar", 0, null, &r)) goto catch_block; /* instead of returning false */ return true; ca...
...if this happens in foo() or bar() in the above example, the pending exception will still be set when you call cleanup(), which would be bad.
...And 2 more matches
TPS Bookmark Lists
for example: var bookmarks_after_second_modify = { "menu": [ { uri: "http://www.getfirefox.com/", title: "get firefox" } ], "menu/foldera": [ { uri: "http://mozilla.com", title: "mozilla" }, ] }; this describes two bookmarks, one in the "menu" folder, and the other in the "folder1" subfolder of "menu".
...rties above, plus two additional properties: location: the full path of the folder that the bookmark should be moved to position: the title of the existing bookmark item, in the current folder, where this bookmark should be moved to (i.e., this bookmark would be inserted into the bookmark list at the position of the named bookmark, causing that bookmark to be positioned below the current one) example: { uri: "http://www.google.com", title: "google", loadinsidebar: false, tags: [ "google", "computers", "misc" ] } livemark objects valid properties are: livemark: the livemark name.
...rties above, plus two additional properties: location: the full path of the folder that the livemark should be moved to position: the title of the existing bookmark item, in the current folder, where this livemark should be moved to (i.e., this livemark would be inserted into the bookmark list at the position of the named bookmark, causing that bookmark to be positioned below the current one) example: { livemark: "livemarkone", feeduri: "http://rss.wunderground.com/blog/jeffmasters/rss.xml", siteuri: "http://www.wunderground.com/blog/jeffmasters/show.html" } folder objects valid properties are: folder: the folder's name.
...And 2 more matches
How to build an XPCOM component in JavaScript
this tutorial does not describe how and why xpcom works the way it does, or what every bit of the example code does.
... implementation this example component will expose a single method, which returns the string "hello world!".
...the library provides a simple example of its use in the source code (js/xpconnect/loader/xpcomutils.jsm), but here's another using this example.
...And 2 more matches
Finishing the Component
for example, take a look at the nsiservicemanager: /** * the nsiservicemanager manager interface provides a means to obtain * global services in an application.
...for example, in 2002 the gnu compiler collection (gcc), version 3.2 changed the c++ abi, and this caused problems between libraries compiled with gcc 3.2 and applications compiled with an earlier version and vice versa.
... if you care to extend this implementation so that the list of urls is held remotely on a server somewhere - as might be the case when the weblock component is used in a corporate intranet, for example - there are networking apis in gecko that will support this.
...And 2 more matches
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.
... in addition to the cookiemanager component, for example, the webbrowserfind component is another part of a large set of web browsing interfaces you can use.
... the weblock component now it's time to look at the weblock component as another example of xpcom components (since you'll be creating it shortly).
...And 2 more matches
IAccessibleText
for example, if the string "one two three" is implemented as a two text() objects, with a top level text() object containing an embed character "one ?
...three" object would be 4, matching the embed character</li> the caretoffset for "two" would be 2, matching the "o" the caret position/offset is that of the character logically following it, for example to the right of it in a left to right language.
...the caret position/offset is that of the character logically following it, for example to the right of it in a left to right language.
...And 2 more matches
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.
...this can be used, for example, to display the number of unread messages in an email client.
...this is created by using the dockmenu attribute of nsimacdocksupport here: http://mxr.mozilla.org/mozilla-release/source/browser/base/content/browser.js#1562 this is seen here: if you were to copy and follow that example you would replace the default native menu.
...And 2 more matches
nsIPushService
void subscribe( in domstring scope, in nsiprincipal principal, in nsipushsubscriptioncallback callback ); parameters scope the serviceworkerregistration.scope for a service worker subscription, or a unique url (for example, chrome://my-module/push) for a system subscription.
... example const { classes: cc, interfaces: ci, utils: cu } = components; const scriptsecuritymanager = cc["@mozilla.org/scriptsecuritymanager;1"] .getservice(ci.nsiscriptsecuritymanager); const pushservice = cc["@mozilla.org/push/service;1"] .getservice(ci.nsipushservice); pushservice.subscribe( "chrome://my-module/push", scriptsecuritymanager.getsystemprincipal(), (code, subscription) =...
... example pushservice.getsubscription( "chrome://my-module/push", scriptsecuritymanager.getsystemprincipal(), (code, subscription) => { if (!components.issuccesscode(code)) { cu.reporterror("error fetching subscription: " + code); return; } // `subscription == null` if the `(scope, principal)` pair doesn't have a // push subscription.
...And 2 more matches
nsIURI
if this value is something other than utf-8 then the uri components (for example spec, prepath, username, and so on) are all fully url-escaped.
...a port value of -1 corresponds to the protocol's default port (for example -1 implies port 80 for http uris).
...for example, under mac os x, the spec of a file uri doesn't necessarily uniquely identify a file, since two volumes can have the same name.
...And 2 more matches
Performance
for example, explain select * from moz_history; the results are hard to understand, but you should be able to see whether it is using indices.
...for example sqlite> explain query plan select * from moz_historyvisit v join moz_history h on v.page_id = h.id where v.visit_date > 1000000000; 0|0|table moz_historyvisit as v with index moz_historyvisit_dateindex 1|1|table moz_history as h using primary key this tells us that it will first look up in moz_historyvisit using an index, and will then look up in moz_history using the primary key.
...sqlite> explain query plan select * from moz_historyvisit where session = 12; 0|0|table moz_historyvisit in this example, you can see that it is not using an index, so this query would be slow.
...And 2 more matches
Zombie compartments
for example, if i open www.techcrunch.com the following compartments are created.
... for example, if i open https://bugzilla.mozilla.org/show_bug.cgi?id=668871 in one tab, then compartment(https://bugzilla.mozilla.org/show_bug.cgi?id=668871) will show up in about:memory.
... see bug 669545 for an example.
...And 2 more matches
Using COM from js-ctypes
speech synthesis example let's start with following c++ code, which invokes microsoft speech api and says "hello, firefox!" with system default voice, then wait until the speaking done.
... this example uses busy loop and thus firefox won't respond until the speaking is done.
... 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.
...And 2 more matches
ctypes
for example, ctypes.char.array(30)(str) converts the string str to utf-8 and returns a new cdata object of array type.
... examples example of structtype() on windows let's say we need tb_button, this type needs to be created.
...unsigned_char}, {'breserved4': ctypes.unsigned_char}, {'breserved5': ctypes.unsigned_char}, {'breserved6': ctypes.unsigned_char}, {'dwdata': ctypes.uintptr_t}, {'istring': ctypes.intptr_t} ]); } else { throw new error("wut?!"); } console.log(struct_tbbutton.size); // 20 on 32-bit, 32 on 64-bit if i'm not mistaken there is another way to do this, we can use arraytype, but example for this i don't know at this time.
...And 2 more matches
Drawing and Event Handling - Plugins
for example, if a user removes an instance from the page, the browser should call npp_setwindow with a window value of null.
... however, for the plug-in to draw at any other time, for example, to highlight on a mouse-down event or draw animation at idle time, it must save the current setting of the port, set up its drawing environment as appropriate, draw, and then restore the port to the previous settings.
...if the plug-in needs to receive periodic time messages (for example, for animation), it should use a timer or a separate thread.
...And 2 more matches
Debugger.Object - Firefox Developer Tools
for example, in firefox, code in privileged compartments sees content dom element objects without redefinitions or extensions made to that object’s properties by content code.
...this accessor may throw if the referent is a scripted proxy or some other sort of exotic object (an opaque wrapper, for example).
...for example: function f() {} // display name: f (the given name) var g = function () {}; // display name: g o.p = function () {}; // display name: o.p var q = { r: function () {} // display name: q.r }; note that the display name may not be a proper javascript identifier, or even a proper expression: we attempt to find helpful names even when the function is not immediately assigned a...
...And 2 more matches
Debugger.Script - Firefox Developer Tools
if the script has no display name — for example, if it is a top-level eval script — this is undefined.
...for example: function f() {} // display name: f (the given name) var g = function () {}; // display name: g o.p = function () {}; // display name: o.p var q = { r: function () {} // display name: q.r }; note that the display name may not be a proper javascript identifier, or even a proper expression: we attempt to find helpful names even when the function is not immediately assigned as the value of some variable or property.
...for example: function h() { var i = function() {}; // display name: h/i f(function () {}); // display name: h/< } var s = f(function () {}); // display name: s< if the instance refers to webassembly code, throw a typeerror.
...And 2 more matches
Dominators view - Firefox Developer Tools
for example: variables allocated on the stack need to be rooted, or internal caches may need to root their​ elements.
...for example: in this screenshot we can see five entries under "gc roots".
... for example, if we click on the first window object: we can see that this window dominates a css2properties object, whose retained size is 2% of the total snapshot size.
...And 2 more matches
The JavaScript input interpreter - Firefox Developer Tools
for example, if you type: function foo() { and then enter, the console does not immediately execute the input, but behaves as if you had pressed shift+enter , so you can finish entering the function definition.
...for example, if you type a function definition in the multi-line editor, and click run, you can switch to single-line mode and still use your function.
...ame using cd(): you can pass the iframe dom element: var frame = document.getelementbyid("frame1"); cd(frame); you can pass a css selector that matches the iframe: cd("#frame1"); you can pass the iframe's global window object: var frame = document.getelementbyid("frame1"); cd(frame.contentwindow); to switch the context back to the top-level window, call cd() with no arguments: cd(); for example, suppose we have a document that embeds an iframe: <!doctype html> <html> <head> <meta charset="utf-8"> </head> <body> <iframe id="frame1" src="static/frame/my-frame1.html"></iframe> </body> </html> the iframe defines a new function: <!doctype html> <html> <head> <meta charset="utf-8"> <script> function whoareyou() { return "i'm frame1"; } </scr...
...And 2 more matches
AudioTrack - Web APIs
for example, the main audio track would have a kind of "main".
...for example, an audio commentary track for a movie might have a label of "commentary with director john q.
... this first example gets the first audio track on the media: var firsttrack = tracks[0]; the next example scans through all of the media's audio tracks, enabling any that are in the user's preferred language (taken from a variable userlanguage) and disabling any others.
...And 2 more matches
Blob - Web APIs
WebAPIBlob
examples creating a blob the blob() constructor can create blobs from other objects.
... for example, to construct a blob from a json string: const obj = {hello: 'world'}; const blob = new blob([json.stringify(obj, null, 2)], {type : 'application/json'}); creating a url representing the contents of a typed array the following code creates a javascript typed array and creates a new blob containing the typed array's data.
... html <p>this example creates a typed array containing the ascii codes for the space character through the letter z, then converts it to an object url.
...And 2 more matches
Basic animations - Web APIs
in the examples below, we'll use the window.requestanimationframe() method to control the animation.
... an animated solar system this example animates a small model of our solar system.
...nds()); ctx.translate(0, 28.5); ctx.drawimage(moon, -3.5, -3.5); ctx.restore(); ctx.restore(); ctx.beginpath(); ctx.arc(150, 150, 105, 0, math.pi * 2, false); // earth orbit ctx.stroke(); ctx.drawimage(sun, 0, 0, 300, 300); window.requestanimationframe(draw); } init(); <canvas id="canvas" width="300" height="300"></canvas> screenshotlive sample an animated clock this example draws an animated clock, showing your current time.
...And 2 more matches
Hit regions and accessibility - Web APIs
a good example at html5accessibility.com demonstrates how this can be done: <canvas> <h2>shapes</h2> <p>a rectangle with a black border.
...lly overlaying the circle is a green <a href="http://en.wikipedia.org/wiki/square" onfocus="drawsquare();" onblur="drawpicture();">square</a> and a purple <a href="http://en.wikipedia.org/wiki/triangle" onfocus="drawtriangle();" onblur="drawpicture();">triangle</a>, both of which are semi-opaque, so the full circle can be seen underneath.</p> </canvas> see the video how nvda reads this example by steve faulkner.
... you can add a hit region to your path and check for the mouseevent.region property to test if your mouse is hitting your region, for example.
...And 2 more matches
DataTransfer.setDragImage() - Web APIs
return value void example this example shows how to use the setdragimage() method.
... note the example refers to an image file named example.gif.
... demo <!doctype html> <html lang=en> <title>example of datatransfer.setdragimage()</title> <meta name="viewport" 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"); // set the drag's format and data.
...And 2 more matches
Document.requestStorageAccess() - Web APIs
examples: allow lists, block lists, on-device classification, user settings, anti-clickjacking heuristics, or prompting the user for explicit permission.
...the threshold is enforced on the level of etld+1, so for example two storage access grants for foo.example.com and bar.example.com will only count as a single exception against the limit.
...for example, if you want to configure firefox to automatically grant access on the first site where requeststorageaccess() is called and then prompt afterwards, you should adjust the value of the dom.storage_access.max_concurrent_auto_grants preference to 1.
...And 2 more matches
Element.getClientRects() - Web APIs
examples these examples draw client rects in various colors.
... html example 1: this html creates three paragraphs with a <span> inside, each embedded in a <div> block.
...oxes.</p> <div> <strong>original</strong> <p> <span>paragraph that spans multiple lines</span> </p> </div> <div> <strong>p's rect</strong> <p class="withclientrectsoverlay"> <span>paragraph that spans multiple lines</span> </p> </div> <div> <strong>span's rect</strong> <p> <span class="withclientrectsoverlay">paragraph that spans multiple lines</span> </p> </div> example 2: this html creates three ordered lists.
...And 2 more matches
FileError - Web APIs
WebAPIFileError
for example, the app might be trying to move a directory into its own child or moving a file into its parent directory without changing its name.
...for example, the state that was cached in an interface object has changed since it was last read from disk.
...for example, a file did not exist but was being opened.
...And 2 more matches
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.
...for example, the state that was cached in an interface object has changed since it was last read from disk.
...for example, a file did not exist but was being opened.
...And 2 more matches
FileSystemEntrySync - Web APIs
for example, if your app is in http://ww.html5rocks.com, open filesystem:http://www.html5rocks.com/temporary/ in a tab.
...examples include a backslash (\), dot (.), and two dots (..).
...examples include a backslash (\), dot (.), and two dots (..).
...And 2 more matches
Guide to the Fullscreen API - Web APIs
activating full-screen mode given an element that you'd like to present in full-screen mode (such as a <video>, for example), you can present it in full-screen mode by simply calling its requestfullscreen() method.
...for example, <iframe> elements have the allowfullscreen attribute in order to opt-in to allowing their content to be displayed in fullscreen mode.
... in addition, navigating to another page, changing tabs, or switching to another application (using, for example, alt-tab) while in fullscreen mode exits fullscreen mode as well.
...And 2 more matches
File drag and drop - Web APIs
these steps are described below, including example code snippets.
...this example illustrates the use of both apis (and does not use any gecko specific interfaces).
...in this example, the drop target element uses the following styling: #drop_zone { border: 5px solid blue; width: 200px; height: 100px; } note that dragstart and dragend events are not fired when dragging a file into the browser from the os.
...And 2 more matches
IDBRequest.error - Web APIs
WebAPIIDBRequesterror
you get this error, for example, if you try to add a new key that already exists in the record.
...a failure due to disk io errors is such an example.
...for example, if the the request failed and the result is not available, the invalidstateerror exception is thrown.
...And 2 more matches
Basic concepts - Web APIs
indexeddb is useful for applications that store a large amount of data (for example, a catalog of dvds in a lending library) and applications that don't need persistent internet connectivity to work (for example, mail clients, to-do lists, and notepads).
...the result property is particularly magical, as it can be many different things, depending on how the request was generated (for example, an idbcursor instance, or the key for a value that you just inserted into the database).
...for example, while an app or a page in http://www.example.com/app/ can retrieve data from http://www.example.com/dir/, because they have the same origin, it cannot retrieve data from http://www.example.com:8080/dir/ (different port) or https://www.example.com/dir/ (different protocol), because they have different origins.
...And 2 more matches
LockManager.request() - Web APIs
this shared/exclusive lock pattern is common in database transaction architecture, for example to allow multiple simultaneous readers (each requests a "shared" lock) but only one writer (a single "exclusive" lock).
... examples general example the following example shows the basic use of the request() method with an asynchronous function as the callback.
...}); mode example the following example shows how to use the mode option for readers and writers.
...And 2 more matches
Using the Media Capabilities API - Web APIs
for example, you can use the api to ensure that you don't try to play high dynamic range (hdr) content on a standard dynamic range (sdr) screen.
...you can, therefore, test for the presence of the api like so: if ("mediacapabilities" in navigator) { // mediacapabilities is available } else { // mediacapabilities is not available } taking video as an example, to obtain information about video decoding abilities, you create a video decoding configuration which you pass as a parameter to mediacapabilities.decodinginfo() method.
... in our example, we are testing the decoding capabilities of a video configuration.
...And 2 more matches
MouseEvent.pageX - Web APIs
WebAPIMouseEventpageX
for example, if the page is scrolled such that 200 pixels of the left side of the document are scrolled out of view, and the mouse is clicked 100 pixels inward from the left edge of the view, the value returned by pagex will be 300.
... example more examples you can also see an example that demonstrates how to access the mouse position information in every available coordinate system.
... let's take a look at a simple example that shows you the mouse's position relative to the page's origin.
...And 2 more matches
PannerNode - Web APIs
retrieval is done by accessing, for example, pannernode.positionx.
... 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.
...you might be moving a character around inside a game world for example, and wanting delivery of audio to change realistically as your character moves closer to or further away from a music player such as a stereo.
...And 2 more matches
Using Performance Timeline - Web APIs
the following example show the usage of these methods getentries(), getentriesbyname() and getentriesbytype().
...the following example shows the use of these properties.
...the following examples show the use of this method.
...And 2 more matches
Permissions API - Web APIs
for example, the permissions api can be used to determine if permission to access a particular api has been granted or denied.
... concepts and usage historically different apis handle their own permissions inconsistently — for example the notifications api allows for explicit checking of permission status and requesting permission, whereas the geolocation api doesn't (which causes problems if the user denied the initial permission request).
... once you have this object you can then perform permission-related tasks, for example querying a permission using the permissions.query() method to return a promise that resolves with the permissionstatus for a specific api.
...And 2 more matches
RTCIceServer - Web APIs
older versions of the webrtc specification included an url property instead of urls; this was changed in order to let you specify multiple addresses for each server in the list, as shown in the example below.
...because many older books and examples still use this, we include it to help developers update their code or make sense of older examples.
... example the configuration below establishes two ice servers.
...And 2 more matches
Reporting API - Web APIs
the reporting api provides a generic reporting mechanism for web applications to use to make reports available based on various platform features (for example content security policy, feature-policy, or feature deprecation reports) in a consistent manner.
... occurrence of user-agent interventions (when the browser blocks something your code is trying to do because it is deemed a security risk for example, or just plain annoying, like auto-playing audio).
... reports sent to endpoints can be retrieved independently of the running of the websites they relate to, which is useful — a crash for example could bring down a web site and stop anything running, but a report could still be obtained to give the developer some clues as to why it happened.
...And 2 more matches
Screen Wake Lock API - Web APIs
examples feature detection this code checks for wake lock support and updates the ui accordingly.
... if ('wakelock' in navigator) { issupported = true; statuselem.textcontent = 'screen wake lock api supported!'; } else { wakebutton.disabled = true; statuselem.textcontent = 'wake lock is not supported by this browser.'; } requesting a wake lock the following example demonstrates how to request a wakelocksentinel object.
...lock = async () => { try { wakelock = await navigator.wakelock.request('screen'); // change up our interface to reflect wake lock active statuselem.textcontent = 'wake lock is active!'; } catch (err) { // if wake lock request fails - usually system related, such as battery statuselem.textcontent = `${err.name}, ${err.message}`; } } releasing wake lock the following example shows how to release the previously acquired wake lock.
...And 2 more matches
Storage Access API - Web APIs
as an example, federated logins often require access to authentication cookies stored in first-party storage, and will require the user to sign in on each site separately (or completely break) if those cookies are not available.
...design properties unique to firefox are summarized here: if the embedded origin tracker.example has already obtained first-party storage access on the top-level origin foo.example, and the user visits a page from foo.example embedding a page from tracker.example again in less than 30 days, the embedded origin will have storage access immediately when loading.
... if a page from top-level origin foo.example embeds more than one <iframe> from tracker.example, and one of those <iframe>s uses the storage access api in order to obtain storage access successfully, all other iframes from tracker.example on foo.example top-level origins will immediately gain storage access as well, without needing to call requeststorageaccess() separately.
...And 2 more matches
SubtleCrypto.deriveKey() - Web APIs
otherwise it will be the initial key material for the derivation function: for example, for pbkdf2 it might be a password, imported as a cryptokey using subtlecrypto.importkey().
...they can then use this shared secret as a symmetric key to secure their communication, or can use the secret as an input to derive such a key (for example, using the hkdf algorithm).
... examples note: you can try the working examples on github.
...And 2 more matches
SubtleCrypto.unwrapKey() - Web APIs
examples note: you can try the working examples on github.
... unwrapping a "raw" key in this example we unwrap an aes-gcm symmetric key.
... // in this example it's supplied as a constant "saltbytes".
...And 2 more matches
TextRange - Web APIs
WebAPITextRange
for example, when you hold down the mouse to select the content on the page, you create a typical textrange.
...for example, expanding a "word" means that the words at both ends of the range will completely included in the range.
... example the following example is valid under ie9.
...And 2 more matches
URL API - Web APIs
WebAPIURL API
for example, to create a url and set its username: let myusername = "someguy"; let addr = new url("https://mysite.com/login"); addr.username = myusername; setting the value of username not only sets that property's value, but it updates the overall url.
...for example, if the url is https://mysite.com/login?user=someguy&page=news, then the value of the search property is ?user=someguy&page=news.
... you can also look up the values of individual parameters with the urlsearchparams object's get() method: let addr = new url("https://mysite.com/login?user=someguy&page=news"); try { loginuser(addr.searchparams.get("user")); gotopage(addr.searchparams.get("page")); } catch(err) { showerrormessage(err); } for example, in the above snippet, the username and target page are taken from the query and passed to appropriate functions that are used by the site's code to log in and route the user to their desired destination within the site.
...And 2 more matches
Boilerplate 1 - Web APIs
« previousnext » this example describes repeated pieces of code that will be hidden from now on, as well as defining a javascript utility function to make webgl initialization easier.
...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.
...And 2 more matches
Color masking - Web APIs
« previousnext » this webgl example modifies random colors by applying color masking to limit the range of displayed colors to specific shades.
... masking random colors this example modifies the random color animation by applying color masking with colormask().
...by limiting the color channels that are written by each drawing command, you can use each channel, for example, to store a different grayscale image.
...And 2 more matches
Lighting in WebGL - Web APIs
this example uses the glmatrix library to perform its matrix and vertex math.
...sunlight, for example, is considered directional light.
...a light bulb emits light in all directions, for example.
...And 2 more matches
Spaces and reference spaces: Spatial tracking in WebXR - Web APIs
for example, if you wish to draw a hand controller's representation using the controller's gripspace, you can get the pose needed like this: let controlpose = frame.getpose(worldrefspace, inputsource.gripspace); this converts the position and orientation of the input's grip space to use the world's coordinate system, then generates the corresponding xrpose, storing it in controlpose.
... for example, given an xrsession whose reference space is worldrefspace, the following line of code would request the first frame of animation to be scheduled: animationframerequestid = xrsession.requestanimationframe(mydrawframe); then, the mydrawframe() function—the callback executed when it's time to draw the frame—might be something like this: function mydrawframe(currentframetime, frame) { let ...
...for example, to create a new reference space that moves the reference space arefspace a half meter in each direction, you can do something like this: let halfmetertransform = new xrrigidtransform({ x: 0.5, y: 0.5, z: 0.5, w: 1.0 }); arefspace = arefspace.getoffsetreferencespace(halfmetertransform); this replaces the existing reference space arefspace with one whose coordinates and orientation have...
...And 2 more matches
Starting up and shutting down a WebXR session - Web APIs
this can also be used to determine whether to use an immersive or an inline presentation, for example.
... for example, if you need an unbounded reference space, you can specify that as a required feature in order to ensure that the session you get can use unbounded spaces: async function createimmersivesession(xr) { try { session = await xr.requestsession("immersive-vr", { requiredfeatures: [ "unbounded" ] }); return session; } catch(error) { throw error; } } on the other hand, if ...
...ng the scene referencespace = await worlddata.session.requestreferencespace("unbounded"); worlddata.referencespace = referencespace.getoffsetreferencespace( new xrrigidtransform(worlddata.playerspawnposition, worlddata.playerspawnorientation)); worlddata.animationframerequestid = worlddata.session.requestanimationframe(ondrawframe); return worlddata; } for the purposes of this example, an object named worlddata gets created to encapsulate data about the world and rendering environment.
...And 2 more matches
Controlling multiple parameters with ConstantSourceNode - Web APIs
for example, perhaps you have a set of oscillators, and two of them need to share the same, configurable volume, or you have a filter that's been applied to certain inputs but not to all of them.
... example let's take a look at this technique in action.
... in this simple example, we create three oscillatornodes.
...And 2 more matches
Web Audio API - Web APIs
a simple, typical workflow for web audio would look something like this: create audio context inside the context, create sources — such as <audio>, oscillator, stream create effects nodes, such as reverb, biquad filter, panner, compressor choose final destination of audio, for example your system speakers connect the sources up to the effects, and the effects to the destination.
...he features of the web audio api work, to help you make informed decisions while designing how audio is routed through your app.controlling multiple parameters with constantsourcenodethis article demonstrates how to use a constantsourcenode to link multiple parameters together so they share the same value, which can be changed by simply setting the value of the constantsourcenode.offset parameter.example and tutorial: simple synth keyboardthis article presents the code and working demo of a video keyboard you can play using the mouse.
...this example makes use of the following web api interfaces: audiocontext, oscillatornode, periodicwave, and gainnode.migrating from webkitaudiocontextin this article, we cover the differences in web audio api since it was first implemented in webkit and how to update your code to use the modern web audio api.
...And 2 more matches
Web Locks API - Web APIs
for example, if a web app running in multiple tabs wants to ensure that only one tab is syncing data between the network and indexed db, each tab could try to acquire a "my_net_db_sync" lock, but only one tab will succeed (the leader election pattern.) the api is used as follows: the lock is requested.
... the api provides optional functionality that may be used as needed, including: returning values from the asynchronous task shared and exclusive lock modes conditional acquisition diagnostics to query the state of locks in an origin an escape hatch to protect against deadlocks locks are scoped to origins; the locks acquired by a tab from https://example.com have no effect on the locks acquired by a tab from https://example.org:8080 as they are separate origins.
...for example: await do_something_without_lock(); // request the lock.
...And 2 more matches
Using the Web Storage API - Web APIs
so, for example, initially calling localstorage on a document will return a storage object; calling sessionstorage on a document will return a different storage object.
... for example, safari browser in private browsing mode gives us an empty localstorage object with a quota of zero, effectively making it unusable.
... example to illustrate some typical web storage usage, we have created an example, imaginatively called web storage demo.
...And 2 more matches
Window.devicePixelRatio - Web APIs
you can use window.matchmedia() to check if the value of devicepixelratio changes (which can happen, for example, if the user drags the window to a display with a different pixel density).
... see the example below.
... examples correcting resolution in a <canvas> a <canvas> can appear too blurry on retina screens.
...And 2 more matches
Window.localStorage - Web APIs
in particular, data stored by a script on a site accessed with http (e.g., http://example.com) is put in a different localstorage object from the same site accessed with https (e.g., https://example.com).
... exceptions securityerror the request violates a policy decision, or the origin is not a valid scheme/host/port tuple (this can happen if the origin uses the file: or data: scheme, for example).
... for example, the user may have their browser configured to deny permission to persist data for the specified origin.
...And 2 more matches
window.location - Web APIs
WebAPIWindowlocation
this means that you can work with location as if it were a string in most cases: location = 'http://www.example.com' is a synonym of location.href = 'http://www.example.com'.
... 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.
... location.assign("http://www.mozilla.org"); // or location = "http://www.mozilla.org"; example #2: force reloading the current page from the server location.reload(true); example #3 consider the following example, which will reload the page by using the replace() method to insert the value of location.pathname into the hash: function reloadpagewithhash() { var initialpage = location.pathname; location.replace('http://example.com/#' + initialpage); } example #4: display the properties of the current url in an alert dialog: function showloc() { var olocation = location, alog = ["property (typeof): value", "location (" + (typeof olocation) + "): " + olocation ]; for (var sprop in olocation){ alog.push...
...And 2 more matches
Sending and Receiving Binary Data - Web APIs
this example reads an image as a binary file and creates an 8-bit unsigned integer array from the raw bytes.
... var filestream = load_binary_resource(url); var abyte = filestream.charcodeat(x) & 0xff; // throw away high-order byte (f7) the example above fetches the byte at offset x within the loaded binary data.
... the following example creates a text file on-the-fly and uses the post method to send the "file" to the server.
...And 2 more matches
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.
...bel> <input type="range" id="fader" min="1" max="100" value="50" step="1" aria-valuemin="1" aria-valuemax="100" aria-valuenow="50" oninput="outputupdate(value)"> <output for="fader" id="volume">50</output> the following code snippet allows you to return the output as it is updated by user input: function outputupdate(vol) { document.queryselector('#volume').value = vol; } example 2: text values sometimes, a slider is used to choose a value that is not, semantically, a number.
...And 2 more matches
ARIA: img role - Accessibility
for example: <div role="img" aria-labelledby="image-1"> ...
... for example, if you use emojis in your text, the meaning might be obvious to a sighted user, but someone using a screenreader might get confused because the emojis might have either no text representation at all, or the alternative text might be confusing and not match the context it is being used in.
... for example, take the following code: <div role="img" aria-label="that cat is so funny"> <p> &#x1f408; &#x1f602; </p> </div> &#x1f408; &#x1f602; are entity references for emojis read out as "cat" and "face with tears of joy", but this doesn't necessarily make sense — the implied meaning is possibly more like "that cat is so funny", so we include that in an aria-label along with role="img".
...And 2 more matches
Basic form hints - Accessibility
the example below shows a simple form with labels.
... the example below shows a radio button group implemented using an unordered list.
... the example below shows a <button> element that is described by a sentence in a separate <div> element.
...And 2 more matches
Alerts - Accessibility
the problem you have a form — a contact form, for example — that you want to put some accessible error checking into.
... 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.
... in order to simplify this example, we’ll check whether the e-mail address contains the “@” symbol, and if the name entry contains at least 1 character.
...And 2 more matches
Accessibility and Spacial Patterns - Accessibility
for example, blue text on a gray background is easier to perceive if it is surrounded "locally" by black than by white.
... for example, "how" an object looks when it is rotated, from different angles, how they look sliced, and how they relate to each other in space all make a difference in an ability to understand math in spatial terms.
... adobe illustrator, for example, allows one to typeset ada braille for printing out.
...And 2 more matches
@counter-style - CSS: Cascading Style Sheets
for example if you want the counters to start at 01 and go through 02, 03, 04 etc, then the pad descriptor is to be used.
...for example, if the system specified is fixed, then each of the n symbols specified in the descriptor will be used to represent the first n counter symbols.
...for example, the value of the marker symbol can be read out as numbers or alphabets for ordered lists or as audio cues for unordered lists, based on the value of this descriptor.
...And 2 more matches
unicode-range - CSS: Cascading Style Sheets
syntax /* <unicode-range> values */ unicode-range: u+26; /* single codepoint */ unicode-range: u+0-7f; unicode-range: u+0025-00ff; /* codepoint range */ unicode-range: u+4??; /* wildcard range */ unicode-range: u+0025-00ff, u+4??; /* multiple values */ values single codepoint a single unicode character code point, for example u+26.
...so for example, u+0025-00ff means include all characters in the range u+0025 to u+00ff.
... wildcard range a range of unicode code points containing wildcard characters, that is using the '?' character, so for example u+4??
...And 2 more matches
Handling Overflow in Multicol - CSS: Cascading Style Sheets
for example, the situation could happen when an image in a column is wider than the column-width value or the width of the column based on the number of columns declared with column-count.
...you can see an example of this below, with an image of the expected rendering as, at the time of writing, browsers deal with this differently.
... in fragmented media, once a fragment (for example a page) is filled with columns, the columns will move to a new page and fill that up with columns.
...And 2 more matches
Flow Layout and Overflow - CSS: Cascading Style Sheets
giving an element a fixed height and width, then adding significant content to the box, creates a basic overflow example: the content goes into the box.
...comparing the next example with the example for overflow: scroll you should see overflow scroll has horizontal and vertical scrollbars when it only needs vertical scrolling.
... the auto example below only adds the scrollbar in the direct we need to scroll.
...And 2 more matches
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.
... in the example below, we have a circular purple item which is a <div> with a height, width, and background colour.
... in the example below you can see how the text now follows the line created by the border.
...And 2 more matches
Column layouts - CSS: Cascading Style Sheets
download this example use multicol when: you want your text to display in newspaper-like columns.
... download this example flexbox can also be used to create layouts where the flex items wrap onto new rows, by setting the flex-wrap property on the container to wrap.
... these new flex lines will distribute space along that line only — the items in the new line will not line up with items in the line above, as you'll see in the example below.
...And 2 more matches
Using CSS custom properties (variables) - CSS: Cascading Style Sheets
for example, the same color might be used in hundreds of different places, requiring global search and replace if that color needs to change.
...for example, --main-text-color is easier to understand than #00ff00, especially if this same color is also used in other contexts.
...75px; } .four { color: white; background-color: var(--main-bg-color); margin: 10px; width: 100px; } .five { background-color: var(--main-bg-color); } <div> <div class="one"></div> <div class="two">text <span class="five">- more text</span></div> <input class="three"> <textarea class="four">lorem ipsum</textarea> </div> this leads to the same result as the previous example, yet allows for one canonical declaration of the desired property value; very useful if you want to change the value across the entire page later.
...And 2 more matches
animation-timing-function - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...for example, if n is 5, there are 5 steps.
...And 2 more matches
background-size - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... working with gradients if you use a <gradient> as the background and specify a background-size to go with it, it's best not to specify a size that uses a single auto component, or is specified using only a width value (for example, background-size: 50%).
...And 2 more matches
clamp() - CSS: Cascading Style Sheets
WebCSSclamp
clamp(min, val, max) is resolved as max(min, min(val, max)) the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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.
...And 2 more matches
conic-gradient() - CSS: Cascading Style Sheets
example conic gradients include pie charts and color wheels.
... the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...And 2 more matches
cross-fade() - CSS: Cascading Style Sheets
for example, a value of 0% defined for the first image yields only the second image, while 100% yields only the first.
...the 50%/50% example seen above did not need to have the percentages listed, as when a percentage value is omitted, the included percentages are added together and subtracted from 100%.
... in the last example, the sum of both percentages is not 100%, and therefore both images include their respective opacities.
...And 2 more matches
float - CSS: Cascading Style Sheets
WebCSSfloat
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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).
...And 2 more matches
font-kerning - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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.
...And 2 more matches
left - CSS: Cascading Style Sheets
WebCSSleft
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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...
...And 2 more matches
max() - CSS: Cascading Style Sheets
WebCSSmax
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... in the first above example, the width will be at least 400px, but will be wider if the the viewport is more than 2000px wide (in which case 1vw would be 20px, so 20vw would be 400px).
...And 2 more matches
pointer-events - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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.
...And 2 more matches
position - CSS: Cascading Style Sheets
WebCSSposition
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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.
...And 2 more matches
scroll-margin - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... description you can see the effect of scroll-margin by scrolling to a point partway between two of the "pages" of the example's content.
...And 2 more matches
transform-style - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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.
...And 2 more matches
transition-timing-function - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...for example, if n is 5, there are 5 steps.
...And 2 more matches
url() - CSS: Cascading Style Sheets
WebCSSurl()
/* simple usage */ url(https://example.com/images/myimg.jpg); url(data:image/png;base64,irxvb0…); url(myfont.woff); url(#idofsvgpath); /* associated properties */ background-image: url("https://mdn.mozillademos.org/files/16761/star.gif"); list-style-image: url('../images/bullet.jpg'); content: url("pdficon.jpg"); cursor: url(mycursor.cur); border-image-source: url(/media/diamonds.png); src: url('fantasticfont.woff'); offset-path: u...
...l / 30px / 30px space; /* as a parameter in another css function */ background-image: cross-fade(20% url(first.png), url(second.png)); mask-image: image(url(mask.png), skyblue, linear-gradient(rgba(0, 0, 0, 1.0), transparent); /* as part of a non-shorthand multiple value */ content: url(star.svg) url(star.svg) url(star.svg) url(star.svg) url(star.svg); /* at-rules */ @document url("https://www.example.com/") { ...
... } @import url("https://www.example.com/style.css"); @namespace url(http://www.w3.org/1999/xhtml); relative urls, if used, are relative to the url of the stylesheet (not to the url of the web page).
...And 2 more matches
Creating and triggering events - Developer guides
elem.dispatchevent(event); the above code example uses the eventtarget.dispatchevent() method.
... for example, the event could be created as follows: const event = new customevent('build', { detail: elem.dataset.time }); this will then allow you to access the additional data in the event listener: function eventhandler(e) { console.log('the time is: ' + e.detail); } the old-fashioned way the older approach to creating events uses apis inspired by java.
... the following shows an example with document.createevent(): // create the event.
...And 2 more matches
Constraint validation - Developer guides
for a basic introduction to these concepts, with examples, see the form validation tutorial.
... complex constraints using the constraint validation api using javascript and the constraint api, it is possible to implement more complex constraints, for example, constraints combining several fields, or constraints involving complex calculations.
... as an example, we will add a script checking the constraint validation for this simple form: <form> <label for="zip">zip : </label> <input type="text" id="zip"> <label for="country">country : </label> <select id="country"> <option value="ch">switzerland</option> <option value="fr">france</option> <option value="de">germany</option> <option value="nl">the netherlands</op...
...And 2 more matches
A hybrid approach - Developer guides
this article presents one potential combination of techniques as an example here, but different combinations will be appropriate under different circumstances.
...for example, an often-criticized point about responsive web design is that full-resolution images are sent to all devices, including phones that show the images scaled down anyway.
...for example, you may not even need to adjust your content based on what actual device a user is using — just knowing whether a feature is present on their browser is often good enough.
...And 2 more matches
Writing forward-compatible websites - Developer guides
for example, if you have this markup: <div onclick="alert(ownerdocument)">click me</div> then clicking on the text alerts the ownerdocument of the div.
... as a simple example, don't assume that any browser in which "filter" in body.style tests true must be microsoft internet explorer and therefore e.g.
...for example, if you have tested that your default code path runs properly in firefox aurora but firefox beta and the latest release have a bug that make your default code path fail, it is ok to treat the firefox version number that is in aurora at the moment of testing as "current", and consider the beta version as a "past" version even though it hasn't been released to the general public yet.
...And 2 more matches
<del>: The Deleted Text element - HTML: Hypertext Markup Language
WebHTMLElementdel
this can be used when rendering "track changes" or source code diff information, for example.
... the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...And 2 more matches
<details>: The Details disclosure element - HTML: Hypertext Markup Language
WebHTMLElementdetails
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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.
...And 2 more matches
<iframe>: The Inline Frame element - HTML: Hypertext Markup Language
WebHTMLElementiframe
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...for example, this can safely sandbox an advertisement without forcing the same restrictions upon the page the ad links to.
...And 2 more matches
<ol>: The Ordered List element - HTML: Hypertext Markup Language
WebHTMLElementol
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...for example, to start numbering elements from the letter "d" or the roman numeral "iv," use start="4".
...And 2 more matches
<rb>: The Ruby Base element - HTML: Hypertext Markup Language
WebHTMLElementrb
{{embedinteractiveexample("pages/tabbed/rb.html", "tabbed-standard")}} the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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.
...And 2 more matches
<samp>: The Sample Output element - HTML: Hypertext Markup Language
WebHTMLElementsamp
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... examples basic example in this simple example, a paragraph includes an example of the output of a program.
...And 2 more matches
lang - HTML: Hypertext Markup Language
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...for example, the language code for english is en, and the code for badeshi is bdz.
...And 2 more matches
Content negotiation - HTTP
in http, content negotiation is the mechanism that is used for serving different representations of a resource at the same uri, so that the user agent can specify which is best suited for the user (for example, which language of a document, which image format, or which content encoding).
...html5 provides alternatives to content negotiation via, for example, the <source> element.
...see, for example, the apache negotiation algorithm.
...And 2 more matches
CSP: frame-ancestors - HTTP
default-src), but doesn't allow 'unsafe-eval' or 'unsafe-inline' for example.
... examples: http://*.example.com: matches all attempts to load from any subdomain of example.com using the http: url scheme.
... mail.example.com:443: matches all attempts to access port 443 on mail.example.com.
...And 2 more matches
Link prefetching FAQ - HTTP
an example using the link tag follows: <link rel="prefetch" href="/images/big.jpeg"> the same prefetching hint using an http link: header: link: </images/big.jpeg>; rel=prefetch the format for the link: header is described in rfc 5988 section 5.
...for example, the next document might contain several large images.
... 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?
...And 2 more matches
OPTIONS - HTTP
WebHTTPMethodsOPTIONS
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 g...
...in this example, we will request permission for these parameters: the access-control-request-method header sent in the preflight request tells the server that when the actual request is sent, it will have a post request method.
... options /resources/post-here/ http/1.1 host: bar.example accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 accept-language: en-us,en;q=0.5 accept-encoding: gzip,deflate connection: keep-alive origin: https://foo.example access-control-request-method: post access-control-request-headers: x-pingother, content-type the server now can respond if it will accept a request under these circumstances.
...And 2 more matches
JavaScript data types and data structures - JavaScript
for example (and unlike in c), strings are immutable.
...for example, +0 === -0 is true.
... this example demonstrates, where incrementing the number.max_safe_integer returns the expected result: > const x = 2n ** 53n; 9007199254740992n > const y = x + 1n; 9007199254740993n you can use the operators +, *, -, **, and % with bigints—just like with numbers.
...And 2 more matches
Keyed collections - JavaScript
see also the map reference page for more examples and the complete api.
... for more information and example code, see also "why weakmap?" on the weakmap reference page.
...the following example is from nick fitzgerald's blog post "hiding implementation details with ecmascript 6 weakmaps".
...And 2 more matches
constructor - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...for example: class validationerror extends error { constructor(message) { super(message); // call parent class constructor this.name = 'validationerror'; this.code = '42'; } printcustomermessage() { return `validation failed :-( (details: ${this.message}, code: ${this.code})`; } } try { throw new validationerror("not a valid phone number"); } catch (error) { if (error inst...
...And 2 more matches
Arrow function expressions - JavaScript
however, note that in // this example we are not assigning `length` value to the made up property.
... that.age++; }, 1000); } alternatively, a bound function could be created so that a preassigned this value would be passed to the bound target function (the growup() function in the example above).
...thus, in this example, arguments is simply a reference to the arguments of the enclosing scope: var arguments = [1, 2, 3]; var arr = () => arguments[0]; arr(); // 1 function foo(n) { var f = () => arguments[0] + n; // foo's implicit arguments binding.
...And 2 more matches
Rest parameters - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... // -- 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.
...And 2 more matches
Array.prototype.length - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...when you extend an array by changing its length property, the number of actual elements increases; for example, if you set length to 3 when it is currently 2, the array now contains 3 elements, which causes the third element to be a non-iterable empty slot.
...And 2 more matches
Array.prototype.map() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...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.
...And 2 more matches
Array.prototype.sort() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...for example, "banana" comes before "cherry".
...And 2 more matches
Array - JavaScript
for example, if you had an object with a property named 3d, it can only be referenced using bracket notation.
... let years = [1950, 1960, 1970, 1980, 1990, 2000, 2010] console.log(years.0) // a syntax error console.log(years[0]) // works properly renderer.3d.settexture(model, 'character.png') // a syntax error renderer['3d'].settexture(model, 'character.png') // works properly in the 3d example, '3d' had to be quoted (because it begins with a digit).
...as a result, '2' and '02' would refer to two different slots on the years object, and the following example could be true: console.log(years['2'] != years['02']) relationship between length and numerical properties a javascript array's length property and numerical properties are connected.
...And 2 more matches
Date.UTC() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...for example, 95 is converted to the year 1995.
...And 2 more matches
Date.prototype.setFullYear() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... syntax dateobj.setfullyear(yearvalue[, monthvalue[, datevalue]]) parameters yearvalue an integer specifying the numeric value of the year, for example, 1995.
...And 2 more matches
Date.prototype.setUTCFullYear() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... syntax dateobj.setutcfullyear(yearvalue[, monthvalue[, dayvalue]]) parameters yearvalue an integer specifying the numeric value of the year, for example, 1995.
...And 2 more matches
Date.prototype.toLocaleString() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... examples using tolocalestring() in basic use without specifying a locale, a formatted string in the default locale and with default options is returned.
...And 2 more matches
Error.prototype.stack - JavaScript
for example, firefox sets it when creating an error object, while phantomjs sets it only when throwing the error, and archived msdn docs also seem to match the phantomjs implementation.
... examples using the stack property the following html markup demonstrates the use of stack property.
... <!doctype html> <meta charset="utf-8"> <title>stack trace example</title> <body> <script> function trace() { try { throw new error('myerror'); } catch(e) { alert(e.stack); } } function b() { trace(); } function a() { b(3, 4, '\n\n', undefined, {}); } a('first call, firstarg'); </script> assuming the above markup is saved as c:\example.html on a windows file system it produces an alert message box with the following text: starting with firefox 30 and later containing the column number: trace@file:///c:/example.html:9:17 b@file:///c:/example.html:16:13 a@file:///c:/example.html:19:13 @file:///c:/example.html:21:9 firefox 14 to firefox 29: trace@file:///c:/example.html:9 b@file:///c:/example.html:16 a@file:///c:/example.html:19 @file:///c:/example.html:21 firefox 13 and ...
...And 2 more matches
Function() constructor - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...for example: "x", "thevalue"—or "x,thevalue".
...And 2 more matches
Object.prototype.toLocaleString() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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() ove...
...And 2 more matches
Object.prototype.toString() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... by using radix you can also convert base 10 numbers (like 1,2,3,4,5,.........) to another base numbers, in example below we are converting base 10 number to a base 2 (binary) number let basetenint = 10; console.log(basetenint.tostring(2)); // expected output is "1010" and same for big integers let bignum = bigint(20); console.log(bignum.tostring(2)); // expected output is "10100" some common radix are 2 for binary numbers, 8 for octal numbers, 10 for decimal numbers, 16 for hexadecimal numbers.
...And 2 more matches
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.
...see the example about "asynchronicity or synchronicity of promise.all" below.
... examples using promise.all promise.all waits for all fulfillments (or the first rejection).
...And 2 more matches
Promise.prototype.catch() - JavaScript
this means that you have to provide an onrejected function even if you want to fall back to an undefined result value - for example obj.catch(() => {}).
... the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...And 2 more matches
RegExp.prototype[@@matchAll]() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...for example, the following two examples return same result.
...And 2 more matches
RegExp() constructor - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... examples literal notation and constructor there are two ways to create a regexp object: a literal notation and a constructor.
...And 2 more matches
RegExp.prototype.exec() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... description consider the following example: // match "quick brown" followed by "jumps", ignoring characters in between // remember "brown" and "jumps" // ignore case let re = /quick\s(brown).+?(jumps)/ig; let result = re.exec('the quick brown fox jumps over the lazy dog'); the following table shows the results for this script: object property/index description example result [0] the full string...
...And 2 more matches
RegExp.prototype.test() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... examples using test() simple example that tests if "hello" is contained at the very beginning of a string, returning a boolean result.
...And 2 more matches
String.fromCharCode() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...for example, both string.fromcharcode(0xd83c, 0xdf03) and \ud83c\udf03 return code point u+1f303 "night with stars".
...And 2 more matches
String.prototype.replaceAll() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...above.) for example, if /(\a+)(\b+)/, was given, p1 is the match for \a+, and p2 for \b+.
...And 2 more matches
encodeURI() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...the following example shows all the parts that a uri "scheme" can possibly contain.
...And 2 more matches
Bitwise NOT (~) - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...for example, the following integer with more than 32 bits will be converted to a 32 bit integer: before: 11100110111110100000000000000110000000000001 after: 10100000000000000110000000000001 each bit in the first operand is paired with the corresponding bit in the second operand: first bit to first bit, second bit to second bit, and so on.
...And 2 more matches
Comma operator (,) - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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.
...And 2 more matches
Conditional (ternary) operator - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... examples a simple example var age = 26; var beverage = (age >= 21) ?
...And 2 more matches
Decrement (--) - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... syntax operator: x-- or --x description if used postfix, with operator after operand (for example, x--), the decrement operator decrements and returns the value before decrementing.
...And 2 more matches
Destructuring assignment - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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.
...And 2 more matches
Increment (++) - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... syntax operator: x++ or ++x description if used postfix, with operator after operand (for example, x++), the increment operator increments and returns the value before incrementing.
...And 2 more matches
Logical AND (&&) - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... examples of expressions that can be converted to false are: null; nan; 0; empty string ("" or '' or ``); undefined.
...And 2 more matches
Logical OR (||) - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... examples of expressions that can be converted to false are: null; nan; 0; empty string ("" or '' or ``); undefined.
...And 2 more matches
Nullish coalescing operator (??) - JavaScript
see below for more examples.
... the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...And 2 more matches
Optional chaining (?.) - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... for example, consider an object obj which has a nested structure.
...And 2 more matches
Spread syntax (...) - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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.
...And 2 more matches
Unsigned right shift (>>>) - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...for example, 9 >>> 2 yields 2, the same as 9 >> 2: .
...And 2 more matches
new.target - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... examples new.target in function calls in normal function calls (as opposed to constructor function calls), new.target is undefined.
...And 2 more matches
void operator - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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.
...And 2 more matches
for - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... examples using for the following for statement starts by declaring the variable i and initializing it to 0.
...And 2 more matches
function* - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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 // ...
...And 2 more matches
if...else - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...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.
...And 2 more matches
import - JavaScript
below are examples to clarify the syntax.
...for example, if the module imported above includes an export doalltheamazingthings(), you would call it like this: mymodule.doalltheamazingthings(); import a single export from a module given an object or value named myexport which has been exported from the module my-module either implicitly (because the entire module is exported) or explicitly (using the export statement), this inserts myexport into the current scope.
...for example, this inserts shortname into the current scope.
...And 2 more matches
label - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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" //...
...And 2 more matches
OpenSearch description format
<opensearchdescription xmlns="http://a9.com/-/spec/opensearch/1.1/" xmlns:moz="http://www.mozilla.org/2006/browser/search/"> <shortname>[snk]</shortname> <description>[search engine full name and summary]</description> <inputencoding>[utf-8]</inputencoding> <image width="16" height="16" type="image/x-icon">[https://example.com/favicon.ico]</image> <url type="text/html" template="[searchurl]"> <param name="[key name]" value="{searchterms}"/> <!-- other params if you need them… --> <param name="[other key name]" value="[parameter value]"/> </url> <url type="application/x-suggestions+json" template="[suggestionurl]"/> <moz:searchform>[https://example.com/search]</moz:searchform> </opensearchdescr...
...(you can generate a data: uri from an icon file at the data: uri kitchen.) <image height="16" width="16" type="image/x-icon">https://example.com/favicon.ico</image> <!-- or --> <image height="16" width="16">data:image/x-icon;base64,aaabaaeaebaaa … daaa=</image> firefox caches the icon as a base64 data: uri (search plug-ins are stored in the profile's searchplugins/ folder).
... note: since this element is firefox-specific, and not part of the opensearch specification, we use the moz: xml namespace prefix in the example above to ensure that other user agents that don't support this element can safely ignore it.
...And 2 more matches
Add to Home screen - Progressive web apps (PWAs)
we've written a very simple example web site (see our demo live, and also see the source code) that doesn't do much, but was developed with the necessary code to allow it to be added to a home screen, as well as a service worker to enable it to be used offline.
... the example displays a series of fox pictures.
... if you have firefox for android available, use it to navigate to our demo at https://mdn.github.io/pwa-examples/a2hs/.
...And 2 more matches
stroke-linejoin - SVG: Scalable Vector Graphics
example html,body,svg { height:100% } <svg viewbox="0 0 6 6" xmlns="http://www.w3.org/2000/svg"> <!-- effect of the "arcs" value --> <path d="m1,5 a2,2 0,0,0 2,-3 a3,3 0 0 1 2,3" stroke="black" fill="none" stroke-linejoin="arcs" /> <!-- the following pink lines highlight the position of the path for each stroke --> <g id="p"> <path d="m1,5 a2,2 0,0,0 2,-3 a3,3 0 0 1 2,3" ...
... example html,body,svg { height:100% } <svg viewbox="0 0 6 6" xmlns="http://www.w3.org/2000/svg"> <!-- effect of the "bevel" value --> <path d="m1,5 l2,-3 l2,3" stroke="black" fill="none" stroke-linejoin="bevel" /> <!-- the following pink lines highlight the position of the path for each stroke --> <g id="p"> <path d="m1,5 l2,-3 l2,3" stroke="pink" fill="none" stroke-width="0.025" /> <circle cx="1" cy="5" r="0.05" fill="pink" /> <circle...
... example html,body,svg { height:100% } <svg viewbox="0 -1 10 7" xmlns="http://www.w3.org/2000/svg"> <!-- effect of the "miter" value --> <path d="m1,5 l2,-3 l2,3" stroke="black" fill="none" stroke-linejoin="miter" /> <!-- effect of the "miter" value on a sharp angle where de default miter limit is exceeded --> <path d="m7,5 l0.75,-3 l0.75,3" stroke="black" fill="none" s...
...And 2 more matches
SVG In HTML Introduction - SVG: Scalable Vector Graphics
overview this article and its associated example shows how to use inline svg to provide a background picture for a form.
... source here is the source to the example: <html> <head> <title>xtech svg demo</title> <style> stop.begin { stop-color:yellow; } stop.end { stop-color:green; } body.invalid stop.end { stop-color:red; } #err { display:none; } body.invalid #err { display:inline; } </style> <script> function signalerror() { document.getelementbyid('body').setattribute("class", "invalid"); } </script> </head> <body id="body" style="position:absolute; z-index:0; border:1px solid black; left:5%; top:5%; width:90%; height:90%;"> <form> <fieldset> <legend>html form</legend> <p><label>enter something:</label> <input type="text"> <span id="err">incorrect value!</span>...
...like in the following example: var img = document.createelementns("http://www.w3.org/2000/svg", "image"); img.setattributens("http://www.w3.org/1999/xlink", "xlink:href", "move.png"); details the viewbox attribute establishes a logical coordinate system which the svg picture's coordinates are relative to.
...And 2 more matches
SVG fonts - SVG: Scalable Vector Graphics
let's show an example declaration (the one from the specification), and explain the details.
...in the example above the first and most important to be defined is font-family, the value of which can then be referenced in css and svg font-family properties.
...all following attributes are rendering instructions for the font layout engine, for example, how much of the glyphs' overall heights are ascenders.
...And 2 more matches
XML introduction - XML: Extensible Markup Language
example <?xml version="1.0" encoding="utf-8"?> <message> <warning> hello world <!--missing </warning> --> </message> now let's look at a corrected version of that same document: <?xml version="1.0" encoding="utf-8"?> <message> <warning> hello world </warning> </message> a document that contains an undefined tag is invalid.
... for example, if we never defined the <warning> tag, the document above wouldn't be valid.
...for example, to create a new &warning; entity, you can do this: <?xml version="1.0" encoding="utf-8"?> <!doctype body [ <!entity warning "warning: something bad happened...
...And 2 more matches
Module structure of the SDK - Archive of obsolete content
-level modules this is just sdk/<module_name>, and for low-level modules it is sdk/<path_to_module>/<module_name>: // load the high-level "tabs" module var tabs = require("sdk/tabs"); // load the low-level "uuid" module var uuid = require('sdk/util/uuid'); the path to specify for a low-level module is given along with the module name itself in the title of the module's documentation page (for example, system/environment).
... for example, the following add-on contains an additional module directly under "lib", and other modules under subdirectories of "lib": my-addon lib main.js password-dialog.js secrets hash.js storage password-store.js to import modules into main: // main.js code var dialog = require("./password-dialog");...
... for example, this add-on places external modules in a "dependencies" directory: my-addon lib main.js dependencies geolocation.js it can then load them in the same way it would load a local module.
... for example, to load from main: // main.js code var geo = require("./dependencies/geolocation"); freezing the sdk freezes the exports object returned by require.
Porting the Library Detector - Archive of obsolete content
this example walks through the process of porting a xul-based add-on to the sdk.
...for example, if window.jquery is defined, then the page has loaded jquery.
... you can browse and run the ported version in the sdk's examples directory.
...etcontent += htmlcontentpostamble; return widgetcontent; } function updatewidgetview(tab) { var widgetview = widget.getview(tab.window); if (!tab.libraries) { tab.libraries = []; } widgetview.content = buildwidgetviewcontent(tab.libraries); widgetview.width = tab.libraries.length * icon_width; } main.js will use the tabs module to update the widget's content when necessary (for example, when the user switches between tabs): tabs.on('activate', function(tab) { updatewidgetview(tab); }); tabs.on('ready', function(tab) { tab.libraries = []; }); showing the library detail the xul library detector displayed the detailed information about each library on mouseover in a tooltip: we can't do this using a widget, so instead will use a panel.
Working with Events - Archive of obsolete content
many event emitters may emit more than one type of event: for example, a browser window might emit both open and close events.
... for example, the following add-on registers a listener with the tabs module to listen for the ready event, and logs a string to the console reporting the event: var tabs = require("sdk/tabs"); tabs.on("ready", function () { console.log("tab loaded"); }); it is not possible to enumerate the set of listeners for a given event.
... in the latter case the options object passed to the constructor typically defines properties whose names are the names of supported event types prefixed with "on": for example, "onopen", "onready" and so on.
... for example: the actionbutton object emits an event when the button is clicked.
simple-prefs - Archive of obsolete content
usage defining and initializing preferences to define preferences and give them initial values, add a new json array called preferences to your package.json file, and give it one entry for each preference: { "fullname": "example add-on", ...
... type description example specification bool displayed as a checkbox and stores a boolean.
...by default, simple preferences are stored in a preference like: extensions.<addon-id>.<preference-name> for example, if you had a simple-pref named "somepreference" then you could get its value like so: require('sdk/preferences/service').get(['extensions', require('sdk/self').id, 'somepreference'].join('.')) this would give you the same value as: require('sdk/simple-prefs').prefs['somepreference'] the ability to change the default preferences branch is new in add-on sdk 1.15.
... example: function onprefchange(prefname) { console.log("the preference " + prefname + " value has changed!"); } require("sdk/simple-prefs").on("somepreference", onprefchange); require("sdk/simple-prefs").on("someotherpreference", onprefchange); // `""` listens to all changes in the extension's branch require("sdk/simple-prefs").on("", onprefchange); parameters prefname :...
timers - Archive of obsolete content
example var { settimeout } = require("sdk/timers"); settimeout(function() { // do something in 0 ms }, 0) cleartimeout(id) given an id returned from settimeout(), prevents the callback with the id from being called (if it hasn't yet been called).
... example var { settimeout, cleartimeout } = require("sdk/timers"); var id = settimeout(function() { // do something in 1 sec }, 1000); // to stop/cancel this timeout cleartimeout(id); setinterval(callback, ms) schedules callback to be called repeatedly every ms milliseconds.
... example var { setinterval } = require("sdk/timers"); setinterval(function() { // do something every 1 sec }, 1000) clearinterval(id) given an id returned from setinterval(), prevents the callback with the id from being called again.
... example var { setinterval, clearinterval } = require("sdk/timers"); var id = setinterval(function() { // do something every 1 sec // to stop/cancel this interval clearinterval(id); }, 1000); ...
windows - Archive of obsolete content
here's an example converting from a high-level browserwindow to a chrome window, and then back the other way: var { modelfor } = require("sdk/model/core"); var { viewfor } = require("sdk/view/core"); var browserwindows = require("sdk/windows").browserwindows; function converttochromeandback(browserwindow) { // get the chrome window for this browserwindow var chromewindow = viewfor(browserwindow); // now w...
...windows.open("http://www.example.com"); // open a new window and set a listener for "open" event.
... windows.open({ url: "http://www.example.com", onopen: function(window) { // do stuff like listen for content // loading.
... } }); returns the window that was opened: var windows = require("sdk/windows").browserwindows; var example = windows.open("http://www.example.com"); require("sdk/ui/button/action").actionbutton({ id: "read", label: "read", icon: "./read.png", onclick: function() { example.close(); } }); this example uses the action button api, which is only available from firefox 29 onwards.
dev/panel - Archive of obsolete content
note that at the moment you can't debug remote targets (for example, firefox os, the firefox os simulator, or firefox for android) using tools developed with this api.
... example here's a complete main.js: // main.js // require the sdk modules const { panel } = require("dev/panel"); const { tool } = require("dev/toolbox"); const { class } = require("sdk/core/heritage"); // define the panel constructor const mypanel = class({ extends: panel, label: "my panel", tooltip: "my new devtool's panel", icon: "./my-icon.png", url: "./my-panel.html", // when the pane...
... for example, here's a main.js which sends the listtabs message to the debugger server, and logs the response: // main.js // require the sdk modules const { panel } = require("dev/panel"); const { tool } = require("dev/toolbox"); const { class } = require("sdk/core/heritage"); const mypanel = class({ extends: panel, label: "my panel", tooltip: "my new devtool's panel", icon: "./my-icon.png", url:...
...for example, the root actor object has a method listtabs and the stylesheet actor object has a method getstylesheets.
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) { ...
... save(bookmarks).on("data", function (saved, input) { // a data event is called once for each item saved, as well // as implicit items, like `group` console.log(input === group || ~bookmarks.indexof(input)); // true }).on("end", function (saves, inputs) { // like the previous example, the "end" event returns an // array of all of our updated saves.
... for example, suppose we called search() with two query objects: [{ url: "mozilla.org", tags: ["mobile"]}, { tags: ["firefox-os"]}] this will return: all bookmark items from mozilla.org that are also tagged "mobile" all bookmark items that are tagged "firefox-os" an options object may be used to determine overall settings such as sort order and how many objects should be returned.
...for example, when creating a new bookmark group with two bookmark items as its children, and explicitly saving the two bookmark children, the unsaved parent group will also emit a data event.
ui/frame - Archive of obsolete content
for example, this html document defines a <select> element and a couple of <span> elements, and includes a css file to style the content and a javascript script to implement behavior: <!doctype html> <html> <head> <link href="city-info.css" rel="stylesheet"></link> </head> <body> <select name="city" id="city-selector"></select> <span id="time" class="info-element"></span> <span id="we...
...for example, this code is equivalent to once(): var { frame } = require("sdk/ui/frame"); var frame = new frame({ url: "./frame.html" }); frame.on("message", pong) function pong(e) { if (e.data == "ping") { e.source.postmessage("pong", "*"); } frame.removelistener("message", pong) } parameters event : string the event the listener is listening for.
... events attach this event is emitted whenever a new frame instance is constructed and the browser has started to load its document: for example, when the user opens a new browser window, if that window has a toolbar containing this frame.
... detach this event is emitted when a frame instance is unloaded: for example, when the user closes a browser window, if that window has a toolbar containing this frame.
Dialogs and Prompts - Archive of obsolete content
see working with windows in chrome code for introductory information and more discussion and examples.
...for example, to add an apply button to your dialog, use the following code: <dialog xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" id="..." buttons="accept,cancel,extra1" ondialogaccept="onaccept();" ondialogextra1="onapply();" buttonlabelextra1="apply" buttonaccesskeyextra1="a"> <!-- content --> </dialog> you can even get the element object for any of predefined button...
... example: <?xml version="1.0"?> <?xml-stylesheet href="chrome://global/skin/" type="text/css"?> <dialog xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" ondialogaccept="alert('ok!');"> <hbox> <label value="hey!"/> <spacer flex="1"/> <vbox> <button dlgtype="accept"/> <button dlgtype="cancel"/> </vbox> </hbox> </dialog> default button since firefox 1.5, ther...
...most web developers are familiar with the alert() function: this is a prime example of a prompt.
HTML to DOM - Archive of obsolete content
for that matter, we're going to load our html document first: var request = xmlhttprequest(); request.open("get", "http://example.org/file.html", false); request.send(null); our next step is to create the document object that will represent the dom into which we'll insert our newly-retrieved html: var doc = document.implementation.createhtmldocument("example"); doc.documentelement.innerhtml = request.responsetext; after this any manipulation that we might want to do will be something as simple as the following: doc.bo...
... using a hidden xul iframe (alternate example) sometimes, a browser element is overkill, or does not meet your needs, or you can't fulfill its requirements.
... as an example, i will show a browser overlay .xul file, and some javascript code to access it.
...in the example, we dump() to the console the page's url and the text contained in the first h1 tag of the page's <body>.
JS XPCOM - Archive of obsolete content
an interface is simply a list of constants and methods that can be called on the object, an example is nsifile.
...for example, var nsfile = components.constructor("@mozilla.org/file/local;1", "nsifile", "initwithpath"); var file = new nsfile(filepath); they can also be created and initialized manually: var file = components.classes["@mozilla.org/file/local;1"] .createinstance(components.interfaces.nsifile); file.initwithpath(filepath); this creates a new instance of the object with contract i...
...with the preferences service from the previous example we can do the following: var preferences = preferences.queryinterface(components.interfaces.nsiprefbranch2); this allows you to use the methods in the nsiprefbranch2 interface.
... xpcomutils - about protocol handler this example implements a quick about protocol handler in js using xpcomutils.jsm.
JavaScript Daemons Management - Archive of obsolete content
examples example #1: a standard instantiation – new daemon() <!doctype html> <html> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <title>new daemon(&hellip;)</title> <script type="text/javascript" src="daemon.js"></script> <script type="text/javascript" src="daemon-methods.js"></script> <script type="text/javascript"> function perform (nindex, nlength, bbackw) { // ...
...tton> <button onclick="orecompose.close();">close</button> <button onclick="orecompose.reclose();">reclose</button><br /> frame rate: <input type="text" id="vello" value="33" style="width: 40px;" onkeypress="return event.charcode===0||/\d/.test(string.fromcharcode(event.charcode));" onkeyup="if(isfinite(this.value)&&number(this.value)>0){orecompose.setrate(this.value);}" /></p> </body> </html> example #2: a practical instantiation – daemon.buildaround() <!doctype html> <html> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <title>daemon.buildaround(&hellip;)</title> <script type="text/javascript" src="daemon.js"></script> <script type="text/javascript" src="daemon-methods.js"></script> <script type="text/javascript"> /*\ |*| |*| :: daemon.buildaround(@cont...
...eloop</button> <button onclick="ounhide.close();">close</button> <button onclick="ounhide.reclose();">reclose</button><br /> frame rate: <input type="text" id="vello" value="33" style="width: 40px;" onkeypress="return event.charcode===0||/\d/.test(string.fromcharcode(event.charcode));" onkeyup="if(isfinite(this.value)&&number(this.value)>0){ounhide.setrate(this.value);}" /></p> </body> </html> example #3: a safe (without setinterval) instantiation – new daemon.safe() <!doctype html> <html> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <title>new daemon.safe(&hellip;)</title> <script type="text/javascript" src="daemon.js"></script> <script type="text/javascript" src="daemon-safe.js"></script> <script type="text/javascript" src="daemon-methods.js"></script> <sc...
...tton> <button onclick="orecompose.close();">close</button> <button onclick="orecompose.reclose();">reclose</button><br /> frame rate: <input type="text" id="vello" value="33" style="width: 40px;" onkeypress="return event.charcode===0||/\d/.test(string.fromcharcode(event.charcode));" onkeyup="if(isfinite(this.value)&&number(this.value)>0){orecompose.setrate(this.value);}" /></p> </body> </html> example #4: a practical and safe (without setinterval) instantiation – daemon.safe.buildaround() <!doctype html> <html> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <title>daemon.safe.buildaround(&hellip;)</title> <script type="text/javascript" src="daemon.js"></script> <script type="text/javascript" src="daemon-safe.js"></script> <script type="text/javascript" src="da...
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.
Custom about: URLs - Archive of obsolete content
setup for firefox 4+ this is a simple example of a custom about page for bootstrapped addons.
... this example creates an about page with url about:myaboutpage which takes a user to a page that writes some text out.
... this example can be easily modified, just modify the global const at in the // globals section.
...cm.registerfactory(this.component.classid, this.component.classdescription, this.component.contractid, this); } unregister() { cm.unregisterfactory(this.component.prototype.classid, this); } } instantiation firefox 4+ now in the startup procedure of your bootstrapped addon make sure to do register the factory, for example: let factory; function startup(adata, areason) { // ...
Installing Extensions and Themes From Web Pages - Archive of obsolete content
web script example <script type="application/javascript"> <!-- function install (aevent) { for (var a = aevent.target; a.href === undefined;) a = a.parentnode; var params = { "foo": { url: aevent.target.href, iconurl: aevent.target.getattribute("iconurl"), hash: aevent.target.getattribute("hash"), tostring: function () { return this.url; } } }; installtrigger.install(params); return false; } //--> </script> <a href="http://www.example.
...com/foo.xpi" iconurl="http://www.example.com/foo.png" hash="sha1:28857e60d043447c5f4550853f2d40770b326a13" onclick="return install(event);">install extension!</a> let's go through this piece by piece.
...this is used to verify the downloaded file, to protect against a corrupted file being served by a mirror download server, for example.
...the hash is specified as hash function:hash value, for example, sha1:28857e60d043447c5f4550853f2d40770b326a13.
Appendix: What you should know about open-source software licenses - Archive of obsolete content
for example, mysql is published under a dual license: gpl and a commercial license.
...japanese versions, for example, are mentioned only as reference translations.
...for example, if you are using an modified version of linux as the operating system for a web server, it’s fine if you don’t release it.
... for example, source code with a plain gpl or mpl license cannot be linked to or amended with other source code using any other kind of license.
Chapter 6: Firefox extensions and XUL applications - Archive of obsolete content
in the quicknote example, we first set one breakpoint and then stepped through it.
...if you want to use terapad2, for example, insert the following: c:\app\tpad090\terapad.exe /jl=%l %f table 1: parameters used in mozunit parameter description %f filename %l line number %c column number the author uses meadow, which is opened using gnuserv.
...let’s look inside nslocalfilewin.cpp—we’ll see, for example, that it’s checking for the presence of a “:” in the drive name.
...for example, (1+2)*(3-4) would be represented in rpn as 1 2 + 3 4 - * it uses no parentheses.
Chapter 5: Let's build a Firefox extension - Archive of obsolete content
for example, in the firefox browser window, everything other than the web page being displayed in the content area is chrome.
...chrome urls are structured as: chrome://%package name%/%package type%/%relative path to source file% for example, the chrome url for the firefox browser window is as follows: chrome://browser/content/browser.xul here, the package name is “browser”, the file “browser.xul”, and the type of the package is “content”.
... var gmyextensionbundle = components.classes["@mozilla.org/intl/stringbundle;1"].getservice(components.interfaces.nsistringbundleservice); var _bundle = gmyextensionbundle.createbundle("chrome://myextension/locale/myextension.properties") you can now use your string substitutes in the .js where they are needed: see examples below if ( password == userpassword ) { oprefs.setboolpref("access.authenticated", true); } else { alert (_bundle.getstringfromname("wrongpassmessage")); function clear() { sure = confirm(_bundle.getstringfromname("areyousuremessage")); } operations check this brings us to the operations check.
... fixme: figure 13: schematic of session saving and restorin source file structure fixme: figure 14 shows the directory structure for this project creating install manifest create your work folder, and create an install manifest with the contents of listing 1, but in this case, change em:id to sessionstore@example.org and em:name to session store.
Chapter 4: Using XPCOM—Implementing advanced processes - Archive of obsolete content
if you’re having trouble with any of the details of the interface, it is helpful to search on the source code for usage examples within firefox.
... text file input listing 15 shows an example of opening a text file encoded as shift-jis (a double-byte character encoding for japanese).
...ces.nsiconverterinputstream); converterstream.init(filestream, charset, filestream.available(), converterstream.default_replacement_character); var out = {}; converterstream.readstring(filestream.available(), out); var filecontents = out.value; converterstream.close(); filestream.close(); alert(filecontents); outputting text files fixme: not sure this example is relevant in an english context, maybe something from the snippets listing 16 shows how to take text internally represented as unicode and output it to a file encoded using euc-jp (a japanese text encoding).
...for example, using the loaduri() method on the browser element introduced in chapter 3 can open a page specified using http_referer, as shown in listing 21; listing 22 shows how to open a page using the loaduriwithflags() method, with data transmitted via the post method.
Adding Toolbars and Toolbar Buttons - Archive of obsolete content
see the back/forward buttons in the main firefox toolbar for an example.
...in this example we won't bother.
...for example, your extension logo icon will probably be the same.
... here are some examples of how the css for a toolbarbutton would look like on the 3 major platforms.
Adding menus and submenus - Archive of obsolete content
« previousnext » the hello world example in the previous sections shows the two most common ways to add menus.
...an example of one such item is the view > status bar item in the main firefox menu.
... another example of a menu like this is the view > sidebars menu.
...for example, you could have a menuitem that tells you the current time and is updated every second.
Adding sidebars - Archive of obsolete content
d="viewsidebarmenu"> <menuitem id="xulschoolhello-sidebar" label="&xulschoolhello.sidebar.title;" accesskey="&xulschoolhello.sidebar.accesskey;" type="checkbox" autocheck="false" group="sidebar" sidebarurl="chrome://xulschoolhello/content/sidebar.xul" sidebartitle="&xulschoolhello.sidebar.title;" oncommand="togglesidebar('xulschoolhello-sidebar');" /> </menupopup> the example in the mdc page includes a shortcut key combination to toggle the new sidebar.
...you can see an example of a tabbox element if you open the firefox preferences window and select the advanced section.
...in the following example, the second child will be displayed, not the first which would be the default.
...here's an example of a simple tree: <tree flex="1"> <treecols> <treecol label="&xulschoolhello.namecolumn.label;" flex="1" /> <treecol label="&xulschoolhello.greetingcolumn.label;" flex="3" /> </treecols> <treechildren> <treeitem> <treerow> <treecell label="peter" /> <treecell label="hey, what's up?" /> </treerow> </treeitem> <treeitem> <treerow> ...
Appendix C: Avoiding using eval in Add-ons - Archive of obsolete content
even if you trust the remote server; for example, because it is one you rent and administer yourself, there is a huge security risk, because of, but not limited to: you might discontinue your project or sell it, so that it is possible another person with malicious intentions takes over your domain.
...(the example is a quite simple one.
... in real life such code is often far more complex) the code might break in the future, as certain assumptions might not longer be true, for example the function signature may change (auri from above becomes aurl) or the function is replaced by a short-hand/arrow function: function addtab(auri) tabbrowser.addtab(auri); var addtab = (auri) => tabbrowser.addtab(auri); same as with "passing functions/code as strings" above, patching a function to with fragments of externally retrieved data will create security vulnerabilities.
... someexistingobject.someproperty = "abc"; // we already demonstrated with with functions in a previous example alternative: object.defineproperty() for most objects it is possible to (re-)define properties with the object.defineproperty() api, which allows to not override values, but also lets you define getters and setters.
Connecting to Remote Content - Archive of obsolete content
besides xml, it can be used to retrieve data in other formats, for example json, html and plain text.
... let url = "http://www.example.com/"; let request = components.classes["@mozilla.org/xmlextras/xmlhttprequest;1"] .createinstance(components.interfaces.nsixmlhttprequest); request.onload = function(aevent) { window.alert("response text: " + aevent.target.responsetext); }; request.onerror = function(aevent) { window.alert("error status: " + aevent.target.status); }; request.open("get", url, true); request.send(null); in this example we demonstrate how to make a xmlhttprequest call in asynchronous mode.
...this template will transform the xml you receive (in our case, the example xml document above) and convert it into xul.
...in this example code, the first child of the xul document is appended to a xul element after the transformation.
Supporting search suggestions in search plugins - Archive of obsolete content
(this means that a suggestion-supporting engine plugin will have two <url> elements, the other one being the main text/html search url.) for example, the yahoo search plugin has this <url> entry: <url type="application/x-suggestions+json" template="http://ff.search.yahoo.com/gossip?output=fxjson&command={searchterms}"/> if the user types "fir" into the search bar, then pauses, firefox inserts "fir" in place of {searchterms} and queries that url: <url type="application/x-suggestions+json" template="http://ff.search.yahoo.com/gossip?output=...
...for example: ["term 1", "term 2", "term 3", "term 4"] descriptions this optional element is an array of descriptions for each of the suggestions in thecompletion list .
...for example, if you want to offer a map link instead of just a search result page for a given suggestion, you can return an url to a map in this array.
... for example, if the search term is "fir", and you don't need to return descriptions or alternate query urls, you might return the following json: ["fir", ["firefox", "first choice", "mozilla firefox"]] note that in this example, only the query string and completion array are specified, leaving out the optional elements.
Adding preferences to an extension - Archive of obsolete content
inside that, we create a file, defaults.js, that describes the default value of our preferences: pref("extensions.stockwatcher2.symbol", "goog"); the standard for third-party preferences, such as those used in extensions, is to use the string "extensions", a period, the name of the extension, another period, then a preference name, as seen in the example above.
...in our example, we only have one preference, but you can monitor as many preferences as you wish here.
... « 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.
... this example also uses a technique to trigger an onchange function that can be defined per preference and has the old value and along with the new value of the preference.
XML data - Archive of obsolete content
this page contains an example of how you can use css with xml data.
... example data in an xml document uses <info> tags.
...other technologies can modify the structure of the display—for example, xbl can add content, and javascript can modify the dom.
... (see the tables chapter in the css specification for examples that you can adapt.) what next?
Images, Tables, and Mysterious Gaps - Archive of obsolete content
there's nothing apparently wrong with that example.
... there isn't supposed to be, since it's an example of how browsers have traditionally behaved.
...for example, you could try the following: td img {vertical-align: bottom;} this will cause the bottom edges of the images to be aligned with the bottom of the line box, instead of the baseline.
... see, for example, figure 11, where the font-size of the document has been raised to a large amount.
Using XML Data Islands in Mozilla - Archive of obsolete content
for example, a simple xml purchase order can be embedded like this: <script id="purchase-order" type="application/xml"> <purchaseorder xmlns="http://example.mozilla.org/purchaseorderml"> <lineitem> <name>line item 1</name> <price>1.25</price> </lineitem> <lineitem> <name>line item 2</name> <price>2.48</price> </lineitem> </purchaseorder> </script> the xml source text can then be retr...
...here is a complete demo (also available as an attachment): <!doctype html> <html> <head> <title>xml data block demo</title> <script id="purchase-order" type="application/xml"> <purchaseorder xmlns="http://example.mozilla.org/purchaseorderml"> <lineitem> <name>line item 1</name> <price>1.25</price> </lineitem> <lineitem> <name>line item 2</name> <price>2.48</price> </lineitem> </purchaseorder> </script> <script> function rundemo() { var ordersource = document.getelementbyid("purchase-order").textcontent; var parser = new domparser(); var doc = parser.parsefromstring(ordersourc...
...e, "application/xml"); var lineitems = doc.getelementsbytagnamens("http://example.mozilla.org/purchaseorderml", "lineitem"); var firstprice = lineitems[0].getelementsbytagnamens("http://example.mozilla.org/purchaseorderml", "price")[0].textcontent; document.body.textcontent = "the purchase order contains " + lineitems.length + " line items.
...for this demo, you must create an external document called purchase_order.xml: <!doctype html> <html> <head> <title>xml data block demo</title> <script> function rundemo() { var doc = document.getelementbyid("purchase-order").contentdocument; var lineitems = doc.getelementsbytagnamens("http://example.mozilla.org/purchaseorderml", "lineitem"); var firstprice = lineitems[0].getelementsbytagnamens("http://example.mozilla.org/purchaseorderml", "price")[0].textcontent; document.getelementbyid("output-box").textcontent = "the purchase order contains " + lineitems.length + " line items.
Repackaging Firefox - Archive of obsolete content
firefox can be customized for the needs of a particular group of users (for example, your organization's employees or clients).
... the distro extension all the changes you will want to make (for example, changing the default homepage or adding default bookmarks) can be encapsulated into a firefox extension.
... the reason is that if you create and ship a dex that supports 2 locales (for example), and later decide to ship on a 3rd locale, you will need to re-create the dex to support it.
... of course, this strategy only works when your strings either do not need localization, or are programmatically localizable (for example, simply adding the locale to a url, like http://<locale>.example.com/).
JavaScript Client API - Archive of obsolete content
ighly recommended to use the utils.makeguid() helper to generate new guids: let newguid = utils.makeguid(); your store object must implement the following methods: itemexists(id) createrecord(id, collection) changeitemid(oldid, newid) getallids() wipe() create(record) update(record) remove(record) you may also find it useful to override other methods of the base implementation, for example applyincomingbatch if the underlying storage for your data supports batch operations.
...(so for example, bookmarkstore.create() adds a new bookmark to the firefox profile).
...the .id should be al you need, anyway.) applyincomingbatch : todo example store skeleton // maintains the store of all your foo-type items and their guids.
... example here's the skeleton of a sample tracker class.
Creating a Help Content Pack - Archive of obsolete content
for example, if your glossary, index, and table of contents rdf files are all located at chrome://myapp/locale/help/*, then you could put chrome://myapp/locale/help/ here and use only the actual file names without path when needed later.
...an example of how to use this attribute follows: <!-- assumptions: win-toc.rdf contains windows- and os/2-specific info, unix-toc.rdf contains linux- and mac-specific info.
...for example, the following code uses a datasource outside the content pack you have created to include the article in a table of contents: <rdf:li> <rdf:description nc:panelid="toc" nc:datasources="chrome://help/locale/help-toc.rdf chrome://foo/locale/help/glossary.rdf"/> </rdf:li> each of the different data source t...
... here is an example of how firefox opens its help documentation: openhelp('firefox-help', 'chrome://browser/locale/help/help.rdf'); packing it all up ...
Twitter - Archive of obsolete content
for example, the twitter method for tweeting, statuses/update, maps to jetpack.lib.twitter.statuses.update().
... the examples below all use this first, simpler style.
...example: jetpack.lib.twitter.statuses.update({ data: { status: "o frabjous day!" }, username: "basic_auth_username", password: "basic_auth_password", success: function () console.log("hey!") }); user authentication you can supply a username and password to methods that require authentication using the second, more advanced call style described above.
... example usage tweeting jetpack.lib.twitter.statuses.update({ status: "o frabjous day!" }); firefox will prompt for a username and password if the user is not already authenticated with twitter.
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;jetpac...
...note that these examples create a mystorage variable to emphasize the fact that jetpack.storage.simple is just a normal javascript object.
...here's a complete real-world example.
...you can install this example from the jetpack gallery.
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; ...
...note that these examples create a mystorage variable to emphasize the fact that jetpack.storage.simple is just a normal javascript object.
...here's a complete real-world example.
...you can install this example from the jetpack gallery.
Microsummary topics - Archive of obsolete content
warning: microsummary support was removed in gecko 6.0 (firefox 6.0 / thunderbird 6.0 / seamonkey 2.3) programmatically installing a microsummary generator to programmatically install a microsummary generator -- for example, in an extension that helps users create custom generators for their favorite sites -- obtain a reference to the nsimicrosummaryservice interface implemented by the nsimicrosummaryservice component, then call its installgenerator() method, passing it an xml document containing the generator.
... for example, the following code snippet installs the microsummary generator from the creating a microsummary tutorial: var generatortext = ' \ <?xml version="1.0" encoding="utf-8"?> \ <generator xmlns="http://www.mozilla.org/microsummaries/0.1" \ name="firefox download count" \ uri="urn:{835daeb3-6760-47fa-8f4f-8e4fdea1fb16}"> \ <template> \ <transform xmlns="http://www.w3.org/1999/xsl/transform" version="1.0"> \ <output method="text"/> \ <template match="/"> \ <value-of select="id(\'download-count\')"/> \ <text> fx downloads</text> \ </template> \ </transform> \ </template> \ <pages> <include>http://(www\.)?spreadfirefox\.com/(index\.php)?</include> </pages> </generator> \ '; var dompa...
...the value of the attribute must be a valid uri, but you can specify an arbitrary identifier using a urn, for example: urn:{835daeb3-6760-47fa-8f4f-8e4fdea1fb16} to guarantee uniqueness, use urns containing uuids generated by the nsuuidgenerator component.
...for example, you might include the following header in your response to prevent firefox from making another microsummary-related request for one hour: cache-control: max-age=3600 note: because of a technical limitation (bug 346820), firefox uses the same cache for both microsummary-related requests and user-initiated requests, so the cache headers you return apply to both.
New Skin Notes - Archive of obsolete content
-- dria when a page is redirected, need to say-so and what it was redirected from, (see document for an example of such.) this is only an issue in mw1.5 so far.
...see for example the venkman tutorials (although the clears are down the page) or mdc:frequently asked questions.
...for an example of this, see creating xpcom components.
...a few examples: , .these work fine with the old theme, and i expect that this affects a lot of reference articles.
Reading textual data - Archive of obsolete content
using utf-8 for this example: */ "utf-8"; const replacementchar = components.interfaces.nsiconverterinputstream.default_replacement_character; var is = components.classes["@mozilla.org/intl/converter-input-stream;1"] .createinstance(components.interfaces.nsiconverterinputstream); is.init(fis, charset, 1024, replacementchar); now you can read string from is: var str = {}; var numchars = is.readstring(409...
...using utf-8 for this example: */ "utf-8"; var is = components.classes["@mozilla.org/intl/converter-input-stream;1"] .createinstance(components.interfaces.nsiconverterinputstream); // this assumes that fis is the nsiinputstream you want to read from is.init(fis, charset, 1024, 0xfffd); is.queryinterface(components.interfaces.nsiunicharlineinputstream); if (is instanceof components.interfaces.nsiunicharline...
...inputstream) { var line = {}; var cont; do { cont = is.readline(line); // now you can do something with line.value } while (cont); } the above example reads an entire stream until eof.
... for example: // first, get and initialize the converter var converter = components.classes["@mozilla.org/intl/scriptableunicodeconverter"] .createinstance(components.interfaces.nsiscriptableunicodeconverter); converter.charset = /* the character encoding you want, using utf-8 here */ "utf-8"; // now, read from the stream // this assumes istream is the stream you want to read from var scriptablestream = components.classes["@mozilla.org/scriptableinputstream;1"] ...
When To Use ifdefs - Archive of obsolete content
for an example of platform-specfic ifdefs, see nscrt.h.
...for an example of feature ifdefs, see layout/makefile.in.
... for an example of an application-specific ifdef that is bad and should be removed, see nsnativeappsupportwin.cpp.
...for example (at the time of writing) there are two nsiextensionmanager interfaces: toolkit version and suite version.
Working With Directories - Archive of obsolete content
for instance: var dir2 = io.getfile("desktop", "myfiles"); dir2.append("pictures"); dir2.append("vacations"); in this example, a subdirectory several levels down is referenced.
...var dir = io.getfile("desktop", "myfiles"); dir.append("pictures"); if (!dir.exists()) dir.create(dir.directory_type, 0775); this example checks if the directory exists and creates it if it does not.
...function getlatestfile() { var lastmod = 0; var homedir = io.getfile("home", ""); var items = homedir.directoryentries; while (items.hasmoreelements()) { var item = items.getnext().queryinterface(components.interfaces.nsifile); if (item.isfile() && item.lastmodifiedtime > lastmod.lastmodifiedtime) lastmod = item; } return lastmod; } this example iterates through the files in the home directory and looks for the file with the latest modification time (the last file in that directory that was written to).
...the following example returns an array of all of a directory's subdirectories: function getsubdirs() { var arr = []; var items = io.getfile("home", "").directoryentries; while (items.hasmoreelements()) { var item = items.getnext(); if (item.isdirectory()) arr.push(item); } return arr; } ...
Getting File Information - Archive of obsolete content
this example will check if a file on the desktop exists and set the variable 'filesize' to the size of the file.
... var lastmod = new date(file.lastmodifiedtime); in this example, a date object is created using the modification time of a file.
... in this example, an exeception will occur if the file cannot be written to.
... if (!file.iswritable()) throw "file cannot be modified"; if you aren't sure whether a file can be modified, for example, you may wish to check using nsifile.iswritable() first.
Building Hierarchical Trees - Archive of obsolete content
for instance, in the photo example, we have a container 'http://www.xulplanet.com/rdf/myphotos' with three photos.
...here is an example for the streets datasource: <tree flex="1" datasources="template-guide-streets.rdf" ref="http://www.xulplanet.com/rdf/myneighbourhood" flags="dont-build-content" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"> <treecols> <treecol id="address" primary="true" label="address" flex="1"/> <treecol id="floors" label="floors" flex="1"/> </treecols> <template> <rul...
...in this example, the two group elements are displayed at the first level.
...in this example, we only need to use one rule.
Recursive Generation - Archive of obsolete content
« previousnext » in the previous example, the template builder generated an extra set of two buttons for the second row.
...for the top level generation the parent insertion point is the element with the datasources attribute, in this example a <vbox>.
...if you look at the image of the example again, you will see that the buttons do have these labels.
...we'll look more at recursive templates later, but next, let's look at a more practical example.
SQLite Templates - Archive of obsolete content
this simple example shows how to display a listbox containing the values in one column in a database table.
... <query> select name, email from myfriends where gender = :wantedgender <param name="wantedgender">male</param> </query> in this example, a parameter 'wantedgender' is used.
...when the name appears in the query, preceded by a colon, as ':wantedgender' does in the example above, the value of that parameter will be filled in to the query.
...the example above used a string parameter.
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.
...the example below will create an autocomplete textbox that will search the user's history.
...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.
...window, document, or any of the functions/objects/variables bound to the window object event object example <?xml version="1.0"?> <?xml-stylesheet href="chrome://global/skin/" type="text/css"?> <window id="findfile-window" title="find files" orient="horizontal" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <script type="text/javascript"> function myfunction(e){ /* do something cool here or just say the below */ alert(e.target.nodename); ...
Creating a Window - Archive of obsolete content
in the example, each attribute is placed on a separate line but they do not have to be.
...the syntax is described below: window.open(url,windowname,flags); where the flags contains the flag "chrome" as in this example window.open("chrome://navigator/content/navigator.xul", "bmarks", "chrome,width=600,height=300"); if you are using firefox, try below: window.open("chrome://browser/content/places/places.xul", "bmarks", "chrome,width=600,height=300"); you can test lines of javascript like these in the error console.
... the findfile.xul example let's begin by creating the basic file for the find file dialog.
...(usually the browser window.) for example, we could open the find files dialog with either of the following: mozilla -chrome chrome://findfile/content/findfile.xul mozilla -chrome resource:/chrome/findfile/content/findfile.xul if you run this command from a command-line (assuming you have one on your platform), the find files dialog will open by default instead of the mozilla browser window.
Creating a Wizard - Archive of obsolete content
an example wizard source <?xml version="1.0"?> <?xml-stylesheet href="chrome://global/skin/" type="text/css"?> <wizard id="example-window" title="select a dog wizard" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <wizardpage> <description> this wizard will help you select the type of dog that is best for you." </description> <label value="why do you want a...
...in the example above, it has been placed on the second page, but not the first page.
...for example: <wizard id="example-window" title="select a dog wizard" onwizardfinish="return savedoginfo();" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> when the user clicks the finish button, the function savedoginfo() will be called, which would be defined in a script file to save the information that was entered.
...if it returns false, then the wizard does not close, which might occur if the function savedoginfo() encountered invalid input, for example.
Creating an Installer - Archive of obsolete content
let's create an example install trigger.
...here is an example: function donefn ( name , result ){ alert("the package " + name + " was installed with a result of " + result); } var xpi = new object(); xpi["calendar"] = "calendar.xpi"; installtrigger.install(xpi,donefn); first, we define a callback function donefn() which will be called when the install is complete.
... our find files example let's try this with the find files dialog.
... our find files example for the find files dialog, we'll create a structure in the archive much like the following: install.js findfile content contents.rdf findfile.xul findfile.js skin contents.rdf findfile.css locale contents.rdf findfile.dtd a directory has been added for each part of the package, the content, the skin and the locale.
Groupboxes - Archive of obsolete content
a simple groupbox example the example below shows a simple groupbox: example 1 : source view <groupbox> <caption label="answer"/> <description value="banana"/> <description value="tangerine"/> <description value="phone booth"/> <description value="kiwi"/> </groupbox> this will cause four pieces of text to be displayed surrounded by a box with the label answer.
...for example, mozilla's font preferences panel uses a drop-down menu as a caption.
...example 2 : source view <groupbox flex="1"> <caption> <checkbox label="enable backups"/> </caption> <hbox> <label control="dir" value="directory:"/> <textbox id="dir" flex="1"/> </hbox> <checkbox label="compress archived files"/> </groupbox> in this example, a checkbox has been used as a caption.
...this could be used to add extra elements within the structure, such as in the following example: example 3 : source view <radiogroup> <radio id="no" value="no" label="no number"/> <radio id="random" value="random" label="random number"/> <hbox> <radio id="specify" value="specify" label="specify number:"/> <textbox id="specificnumber"/> </hbox> </radiogroup> note that the radiogroup element does not draw a border around it.
Introduction - Archive of obsolete content
java, for example, has portability as a main selling point.
...for example xhtml or other xml languages such as mathml or svg can be inserted within it.
...however, these types of applications do not have security restrictions placed on them, so they may access local files and read and write preferences, for example.
...due to various changes in xul syntax over time, you will want to get the latest version for the examples to work properly.
Persistent Data - Archive of obsolete content
for example, the window should remember which toolbars are collapsed even after the user exits.
...for example, to save the size of a window, you would do the following: <window id="somewindow" width="200" height="300" persist="width height" .
...our find files example let's add the persist attribute to some of the elements in the find files dialog.
... find files example so far : source view next, we'll look at using style sheets with xul files.
Stacks and Decks - Archive of obsolete content
for example, a progress bar might be created using a bar and a label overlaid on top of it.
...for example, you could create an effect similar to the text-shadow property with the following: example 1 : source view <stack> <description value="shadowed" style="padding-left: 1px; padding-top: 1px; font-size: 15pt"/> <description value="shadowed" style="color: red; font-size: 15pt;"/> </stack> both description elements create text with a size of 15 points.
...shadowing is very useful for creating the disabled appearance of buttons: example 2 : source view <stack style="background-color: #c0c0c0"> <description value="disabled" style="color: white; padding-left: 1px; padding-top: 1px;"/> <description value="disabled" style="color: grey;"/> </stack> this arrangement of text and shadow colors creates the disabled look under some platforms.
... example 3 : source view <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> three pages exist here, the default being the third one.
The Chrome URL - Archive of obsolete content
for example, a chrome url lets you refer to a file in the theme such as an image without needing to know which theme the user is using.
...example: chrome://messenger/content/messenger.xul the example here refers to the messenger window.
...here are some more examples.
...in the above example, the file browser.xul is selected.
Toolbars - Archive of obsolete content
for example, the mozilla browser window contains a textbox that displays the page url.
...in the example above, only one toolbar was created.
... our find files example let's add a toolbar to the find files dialog.
... the find files example so far: source view next, we'll find out how to add a menu bar to a window.
Tree Selection - Archive of obsolete content
getrangeat example var start = new object(); var end = new object(); var numranges = tree.view.selection.getrangecount(); for (var t = 0; t < numranges; t++){ tree.view.selection.getrangeat(t,start,end); for (var v = start.value; v <= end.value; v++){ alert("item " + v + " is selected."); } } we create two objects called 'start' and 'end'.
...for example, the following code will select the row at index 5: tree.view.selection.select(5); note that you should not just change the tree's currentindex property to change the selection.
... instead, you should use the selection's select function as in the example above.
...here is an example which selects rows between index 2 and 7.
XUL Questions and Answers - Archive of obsolete content
an example of this is: var tree = document.getelementbyid('treeid'); selectedtreeitem = tree.view.getitematindex(tree.currentindex); selectedtreeitem.firstchild.setattribute('style', 'background: #ff0000'); what is an example of tab browser in xul?
... an example of tab browswer in xul how can i get uris on open tabs?
... what is an example of addprogresslistener?
... an example of this is this: // associate the progress listener for a "browser" to a listener object browserobject.addprogresslistener( listobj, components.interfaces.nsiwebprogress.notify_state_window ); // remember to define the object, something like this: listobj = new object(); listobj.wpl = components.interfaces.nsiwebprogresslistener; listobj.queryinterface = function(aiid) { if (aiid.equals(listobj.wpl) || aiid.equals(components.interfaces.nsisupportsweakreference) || aiid.equals(components.interfaces.nsisupports)) return this; throw components.results.ns_nointerface; } listobj.onstatechange = function(aprogress, arequest, aflag, astatus) { if (aflag & listobj.wpl.state_start) { // this fires when the load event is initiated } else { if (aflag...
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.
...for example, for a menuitem in a menu you can add the following css rule when you want to use the value none: menupopup > menuitem, menupopup > menu { max-width: none; } dir type: one of the values below the direction in which the child elements of the element are placed.
...for example, if the dlgtype is set to accept, the button will replace the dialog box's accept button, which is usually labeled ok.
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.
...window, document, or any of the functions/objects/variables bound to the window object event object example <?xml version="1.0"?> <?xml-stylesheet href="chrome://global/skin/" type="text/css"?> <window id="findfile-window" title="find files" orient="horizontal" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <script type="text/javascript"> function myfunction(e){ /* do something cool here or just say the below */ alert(e.target.nodename); ...
...you may use onclick when you are working with a plain colorpicker and need the currently selected color for example to display in a <textbox>.
CommandLine - Archive of obsolete content
an nsicommandline object is passed as the first argument of the launched window: example var cmdline = window.arguments[0]; cmdline = cmdline.queryinterface(components.interfaces.nsicommandline); alert(cmdline.handleflagwithparam("test", false)); see also: chrome: command line for single instance applications of course, for a single instance application (see toolkit.singletonwindowtype for more information), the last example still applies the first time your application is launched.
... however, if you'd like to retrieve the latest command line arguments (to open a file for example), a possible solution is to create your own command line handler.
... example notice the changes since gecko 2.0 (component registration has moved into the manifest file).
...ne = components.interfaces.nsicommandline; const nsicommandlinehandler = components.interfaces.nsicommandlinehandler; const nsifactory = components.interfaces.nsifactory; const nsimodule = components.interfaces.nsimodule; const class_id = components.id("178cfbb6-503c-11dc-8314-0800200c9a66"); const class_name = "applicationnameclh"; const contract_id = "@example.com/applicationname/clh;1"; const cld_category = "m-applicationname"; var apphandler = { /* nsisupports */ queryinterface : function clh_qi(aiid) { if (aiid.equals(nsicommandlinehandler) || aiid.equals(nsifactory) || aiid.equals(nsisupports)) return this; throw components.results.ns_error_no_interface; }, /* nsicommandlinehandler */ handle : function c...
Dialogs in XULRunner - Archive of obsolete content
file open and save dialogs are good examples of these.
...here is an example xul dialog: <?xml version="1.0"?> <?xml-stylesheet href="chrome://global/skin/" type="text/css"?> <dialog id="mydialog" title="my dialog" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" onload="window.sizetocontent();" buttons="accept,cancel" buttonlabelaccept="set favorite" buttonaccesskeyaccept="s" ondialogaccept="return do...
...save();" buttonlabelcancel="cancel" buttonaccesskeycancel="n" ondialogcancel="return docancel();"> <script> function dosave(){ //dosomething() return true; } function docancel(){ return true; } </script> <dialogheader title="my dialog" description="example dialog"/> <groupbox flex="1"> <caption label="select favorite fruit"/> <radiogroup> <radio id="1" label="oranges because they are fruity"/> <radio id="2" selected="true" label="strawberries because of color"/> <radio id="3" label="bananna because it pre packaged"/> </radiogroup> </groupbox> </dialog> xul window elements have a special method to open dialogs, called window.opendialog().
...in an effort to make things easier for developers and more consistent for users, xul has a mechanism to automatically create and position the core dialog buttons ("ok," "cancel," and "help" for example).
NPN_Version - Archive of obsolete content
for example, plug-in api version 4.03 has a major version number of 4 and a point release number of 3.
...for more information and an example, see getting the current version.
...for example, the plug-in could inquire on the constant npvers_has_windowless to see if it is running in a browser that supports windowless functionality.
... for more information and an example, see finding out if a feature exists.
Syndicating content with RSS - Archive of obsolete content
when this is the case, the html web page can let people and machines know about the feed by using the <link> element, like this: <link rel="alternate" type="application/rss+xml" href="http://example.com/feed" /> adding the <a> while use of the html <link> element is powerful, it is mostly hidden.
... linking from the the html web page where the data in an rss feed is also contained makes the rss feed available for use: <a rel="alternate" type="application/rss+xml" href="http://example.com/feed">...</a> feed icons rss (and other) feeds use a special icon.
...here's a simple example of it being done: accept: application/rss+xml, text/html with real production software, though, it would look more like this: accept: application/rss+xml, application/xhtml+xml, text/html here's a more complete example: get / http/1.1 host: example.com accept: application/rss+xml, application/xhtml+xml, text/html when an http server (or server-side script) gets this, it should redirect t...
...something like: http/1.1 302 found location: http://example.com/feed ...
Security Controls - Archive of obsolete content
for example, if a system has a known vulnerability that attackers could exploit, the system should be patched so that the vulnerability is removed or mitigated.
...for example, a security policy is a management control, but its security requirements are implemented by people (operational controls) and systems (technical controls).
... when usability is an issue, many users will attempt to circumvent security controls; for example, if passwords must be long and complex, users may write them down.
... for example, sensitive data on a server may be protected from external attack by several controls, including a network-based firewall, a host-based firewall, and os patching.
TCP/IP Security - Archive of obsolete content
for example, if an application needs to protect sensitive data sent across networks, the application may need to be modified to provide this protection.
... one example is secure multipurpose internet mail extensions (s/mime), which is commonly used to encrypt email messages.
... for example, all network communications between two hosts or networks can be protected at this layer without modifying any applications on the clients or the servers.
... for example, if only one or two applications need protection, a network layer control may be excessive.
Developing cross-browser and cross-platform pages - Archive of obsolete content
let's see a basic example of this approach.
...for example, firefox 1.x users and users of any/all mozilla-based browsers can customize the "general.useragent.*" string properties to any value.
... let's see a basic, simple object support detection example.
... function hideelement(id_attribute_value) { if (document.getelementbyid && document.getelementbyid(id_attribute_value) && document.getelementbyid(id_attribute_value).style ) { document.getelementbyid(id_attribute_value).style.visibility = "hidden"; }; } // example: // <button type="button" onclick="hideelement('d1');">hide div</button> // <div id="d1">some text</div> these repeated calls to document.getelementbyid are not the most efficient way to check for the existence of particular objects or features in the browser's dom implementation, but they serve to illustrate clearly how object support detection works.
Displaying notifications (deprecated) - Archive of obsolete content
for example, on android, notifications appear in the bar at the top of the screen, and in the panel that appears when you drag that bar downward.
... for example, let's simply append a little html to our document when these events fire: notification.onclick = function() { var e = document.createelement("p"); e.innerhtml = "<strong>the notification was clicked.</strong>"; document.body.appendchild(e); }; notification.onclose = function() { var e = document.createelement("p"); e.innerhtml = "<strong>the notification was closed.</strong>"; docum...
...ent.body.appendchild(e); }; displaying the notification once the notification is configured the way you want it to be, call its show() method to display the notification: notification.show(); on android, for example, the resulting notification panel looks like this: when the user taps on the "hey, check this out!" notification here, the resulting changes to the document look like this: if you're using firefox mobile, you can see this example live by tapping the button below.
... view live examples ...
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 ...
... example 1: simple generator.
... var numbers = [1, 2, 3]; // generator function (function*() { for (let i of numbers) { yield i * i; } })(); // generator comprehension (for (i of numbers) i * i ); // result: both return a generator which yields [1, 4, 9] example 2: using if in generator.
ActiveXObject - Archive of obsolete content
for example, a word-processing application may provide an application object, a document object, and a toolbar object.
...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.
...for example, for the local intranet zone, you typically need to change a custom setting to "initialize and script activex controls not marked as safe for scripting." to identify members of an automation object that you can use in your code, you may need to use a com object browser, such as the ole/com object viewer, if no reference documentation is available for the automation object.
...in the following example, you access properties and methods of the new object using the object variable excelsheet and other excel objects, including the application object and the activesheet.cells collection.
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.lan...
...g.string("hello, world"); example: accessing methods of a java object because the javaobject thestring is an instance of java.lang.string, it inherits all the public methods of java.lang.string.
... the following example uses the startswith method to check whether thestring begins with "hello".
... var thestring = new java.lang.string("hello, world"); thestring.startswith("hello"); // returns true example: accessing inherited methods because getclass is a method of object, and java.lang.string extends object, the string class inherits the getclass method.
Game monetization - Game development
specific examples can include bonus levels, better weapons or spells, or refilling the energy needed to play.
... exclusive licenses the exclusive license is a type of license for one publisher — you've built a game and you're selling all the rights to it to a single entity along with the rights to redistribute it — softgames are an example of such a publisher.
...as an example if you've got a game where a player taps items of food, you could change the food to the client's products to give them advertising.
...if you focus on sharing the knowledge first and use your games just as the examples it should be ok.
GLSL Shaders - Game development
in this article we will make a simple code example that renders a cube.
...three.js and other 3d libraries abstract a lot of things for you — if you wanted to create such an example in raw webgl, you'd have to write a lot of extra code to actually make it work.
... go to the cube.html file on github, copy all the javascript code from inside the second <script> element, and paste it into the third <script> element of the current example.
...our example doesn't do much but there are many more cool things you can do with shaders — check out some really cool ones on shadertoy for inspiration and to learn from their sources.
WebVR — Virtual Reality for the Web - Game development
note: there are of course other apis useful for creating games, for example the gamepad api for control inputs, and the device orientation api for handling display orientation on mobile.
...for example: function setcustomfov(up,right,down,left) { var testfov = new vrfieldofview(up,right,down,left); ghmd.setfieldofview(testfov,testfov,0.01,10000.0); } the gpositionsensor variable holds the positionsensorvrdevice — using this you can get the current position or orientation state (for example to update the scene view on every frame), or reset the sensor.
... for example, the below code outputs position information on the screen: function setview() { var posstate = gpositionsensor.getstate(); if(posstate.hasposition) { pospara.textcontent = 'position: x' + roundtotwo(posstate.position.x) + " y" + roundtotwo(posstate.position.y) + " z" + roundtotwo(posstate.position.z); xpos = -posstate.position.x * width * 2; ypos = posstate.position.y * height * 2; if(-posstate.position.z > 0.01) { zpos = -posstate.position.z; } else { zpos = 0.01; } } ...
...you can check the webvr boilerplate sources — it's a good example to start learning webvr from, and a starting point for any web-based vr experience.
Efficient animation for web games - Game development
it is worth documenting some of these things, as there is evidence to suggest (in popular and widely-used ui libraries, for example) that they aren’t necessarily common knowledge.
... to take a concrete example, if you start a css transition to move something from off-screen so that it is fully visible on-screen, the browser knows that the related content will end up completely visible to the user and can then pre-render that content.
...for example, it may make sense for animation setup to happen in a settimeout/cleartimeout callback rather than a requestanimationframe callback.
...modern console games, for example, tend to prioritise framerate during player movement and combat, but may prioritise image quality or physics detail when compromise to framerate and input response would be less noticeable.
Square tilemaps implementation: Static maps - Game development
this is the atlas we will be using as an example, which features five different tiles: to draw a tile from the atlas into the canvas we make use of the drawimage() method in a canvas 2d context.
...for the sake of simplicity, in the example code a plain object has been used.
...in these examples, empty tiles will be represented by index 0, so we will shift the indices of the atlases by one (and thus the first tile of the atlas will be assigned index 1, the second index 2, etc.) the gettile() helper method returns the tile contained at the specified column and row.
...in this case, we need to map the column and row to an array index: var index = row * map.cols + column; wrapping up, an example of a tilemap object could look like the following.
2D maze game with device orientation - Game development
example game by the end of the tutorial you will have a fully functional demo game: cyber orb.
...you can check it out on github where it’s open sourced, read the online documentation and go through the big collection of examples.
...it's just an example of loading the levels, and there are only 5 of them just to showcase the idea, but you can work on expanding that on your own.
...we can for example add power-ups to collect along the way that will make our ball roll faster, stop the timer for a few seconds or give the ball special powers to go through obstacles.
API - MDN Web Docs Glossary: Definitions of Web-related terms
for example: the getusermedia api can be used to grab audio and video from a user's webcam, which can then be used in any way the developer likes, for example, recording video and audio, broadcasting it to another user in a conference call, or capturing image stills from the video.
...gps), which can then be used in conjunction with the google maps apis to for example plot the user's location on a custom map and show them what tourist attractions are in their area.
... the twitter apis can be used to retrieve data from a user's twitter accounts, for example, to display their latest tweets on a web page.
... the web animations api can be used to animate parts of a web page — for example, to make images move around or rotate.
IDL - MDN Web Docs Glossary: Definitions of Web-related terms
for example, to set an <input> element's maxlength to 42 using the content attribute, you have to call setattribute("maxlength", "42") on that element.
...for example, the default type for <input> elements is "text", so if you set input.type="foobar", the <input> element will be of type text (in the appearance and the behavior) but the "type" content attribute's value will be "foobar".
... idl attributes are not always strings; for example, input.maxlength is a number (a signed long).
...html specifications try to make this as developer-friendly as possible, but for various reasons (mostly historical), some attributes behave oddly (select.size, for example) and you should read the specifications to understand how exactly they behave.
TLD - MDN Web Docs Glossary: Definitions of Web-related terms
a tld is the final component of a domain name, for example, "org" in developer.mozilla.org.
... consider an example internet address: https://developer.mozilla.org here org is the tld; mozilla.org is the second-level domain name; and developer is a subdomain name.
...example: .us for united states.
... unsponsored top-level domains domains that operate directly under policies established by icann processes for the global internet community, for example "com" and "edu".
Loop - MDN Web Docs Glossary: Definitions of Web-related terms
an example would be the process of getting an item of data and changing it, and then making sure some condition is checked such as, if a counter has reached a prescribed number.
... examples for loop syntax: for (statement 1; statement 2; statement 3){ execute code block } statement 1 is executed once before the code block is run.
... example: for(var i = 0; i < 10; i++){ console.log(i) } //this loop will print numbers 0-9, will stop when condition is met (i = 10) for the above example, the syntax is as follows: statement 1 sets the variable for the loop (var i = 0).
... example: var i = 0; while(i < 5){ console.log(i) i++ } //this loop will print number 0-4, will stop when condition becomes false (i >=5) for the above example, the syntax is as follows: the code block will continue to run as long as the variable (i) is less than 5.
Test your skills: CSS and JavaScript accessibility - Learn web development
try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor.
... try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor.
... assessment or further help you can practice these examples in the interactive editors above.
... a link to the example you want assessed or need help with, in an online shareable editor (as mentioned in step 1 above).
Test your skills: Images and Form elements - Learn web development
in the example below see if you can match the image above.
... try updating the live code below to recreate the example as displayed in the image: for assessment or further work purposes, download the starting point for this task to work in your own editor or in an online editor.
... assessment or further help you can practice these examples in the interactive editors mentioned above.
... a link to the example you want to be assessed or need help with, in an online shareable editor (as mentioned in step 1 above).
Test your skills: Overflow - Learn web development
try updating the live code below to recreate the finished example: for assessment or further work purposes, download the starting point for this task to work in your own editor or in an online editor.
... try updating the live code below to recreate the example as displayed in the image: for assessment or further work purposes, download the starting point for this task to work in your own editor or in an online editor.
... assessment or further help you can practice these examples in the interactive editors mentioned above.
... a link to the example you want to be assessed or need help with, in an online shareable editor (as mentioned in step 1 above).
How CSS works - Learn web development
a real dom representation rather than a long, boring explanation, let's look at an example to see how a real html snippet is converted into a dom.
... in the example below i have used the british english spelling for color, which makes that property invalid as it is not recognised.
...for example, some older browsers do not support calc() as a value.
...in the next article you'll use your new knowledge to restyle an example, testing out some css in the process.
Using your new knowledge - Learn web development
if you prefer you could move this css to a separate file when you create the example on your local computer.
... working with css the following live example shows a biography, which has been styled using css.
... the css properties that i have used are as follows — each one links to its property page on mdn, which will give you more examples of its use.
... a link to the example you want assessed or need help with, in an online shareable editor (as mentioned in step 1 above).
How does the Internet work? - Learn web development
deeper dive a simple network when two computers need to communicate, you have to link them, either physically (usually with an ethernet cable) or wirelessly (for example with wifi or bluetooth systems).
...well, there are already cables linked to your house, for example, electric power and telephone.
...it's an address made of a series of four numbers separated by dots, for example: 192.168.2.10.
...for example (at the time of writing; ip addresses can change) google.com is the domain name used on top of the ip address 173.194.121.32.
How do I start to design my website? - Learn web development
therefore, before jumping into the technical side—for example, code and tools—you must first step back and decide in detail what you want to do.
... let's look back at our example.
... rather than go through a long explanation, let's go back to our example with this table: goals things to do let people hear your music record music prepare some audio files usable online (could you do this with existing web services?) give people access to your music on some part of your website talk about your music write a few articles to start the discussion define how articles should l...
...(for example, should i learn how to do all this myself, ask someone to do it for me, or use third-party services?) conclusion as you can see, the simple idea "i want to make a website" generates a long to-do list, which only grows longer as you think about it.
Test your skills: Advanced styling - Learn web development
try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor.
... try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor.
... assessment or further help you can practice these examples in the interactive editors above.
... a link to the example you want assessed or need help with, in an online shareable editor (as mentioned in step 1 above).
Test your skills: HTML5 controls - Learn web development
create appropriate inputs for a user to update their details for: email website phone number favourite color try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor.
... try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor.
... assessment or further help you can practice these examples in the interactive editors above.
... a link to the example you want assessed or need help with, in an online shareable editor (as mentioned in step 1 above).
Publishing your website - Learn web development
generally speaking, these tools are relatively easy, great for learning, good for sharing code (for example, if you want to share a technique with or ask for debugging help from colleagues in a different office), and free (for basic features).
... 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.
...for example, our friend bob smith would enter bobsmith.github.io.
...for example, for the username chrisdavidmills, go to chrisdavidmills.github.io.
Marking up a letter - Learn web development
previous overview: introduction to html next we all learn to write a letter sooner or later; it is also a useful example to test our text formatting skills.
...for the location that the links point to, you may use http://example.com as the url.
... example the following screenshot shows an example of what the letter might look like after being marked up.
... a link to the example you want evaluated or need help with, in an online shareable editor (as mentioned in step 1 above).
Test your skills: Advanced HTML text - Learn web development
try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor.
... try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor.
... assessment or further help you can practice these examples in the interactive editors above.
... a link to the example you want assessed or need help with, in an online shareable editor (as mentioned in step 1 above).
Assessment: Structuring planet data - Learn web development
the finished table should look like this: you can also see the example live here (no looking at the source code — don't cheat!) steps to complete the following steps describe what you need to do to complete the table example.
...if you have trouble visualising the data, look at the live example above, or try drawing a diagram.
...you don't need a table footer for this example.
... a link to the example you want assessed or need help with, in an online shareable editor (as mentioned in step 1 above).
Build your own function - Learn web development
note: this example should work in all modern browsers fine, but the styling might look a bit funny in slightly older browsers.
...the main part we want to focus on here is the function's structure and usage, but we wanted to show something interesting for this example.
... now open your browser developer tools on the example page, go to the javascript console and type the line again there, you'll see it appear again!
... note: if you have trouble getting the example to work, feel free to check your code against the finished version on github (see it running live also), or ask us for help.
Image gallery - Learn web development
starting point to get this assessment started, you should go and grab the zip file for the example, unzip it somewhere on your computer, and do the exercise locally to begin with.
...the html body looks like this: <h1>image gallery example</h1> <div class="full-img"> <img class="displayed-img" src="images/pic1.jpg"> <div class="overlay"></div> <button class="dark">darken</button> </div> <div class="thumb-bar"> </div> the example looks like this: the most interesting parts of the example's css file: it absolutely positions the three elements inside the full-img <div> — the <img> in which the full-sized image is ...
... to give you more of an idea, have a look at the finished example (no peeking at the source code!) steps to complete the following sections describe what you need to do.
... a link to the example you want assessed or need help with, in an online shareable editor (as mentioned in step 1 above).
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.
...for example, in a game, if the player's number of lives is 0, then it's game over.
...for example, looking through a list of names.
...for example if the user clicks a button on a webpage, you might want to respond to that action by displaying an information box.
Object building practice - Learn web development
the finished example will look a little something like this: this example will make use of the canvas api for drawing the balls to the screen, and the requestanimationframe api for animating the whole display — you don't need to have any previous knowledge of these apis, and we hope that by the time you've finished this article you'll be interested in exploring them more.
...so for example, if the ball was traveling upwards (positive vely), then the vertical velocity is changed so that it starts to travel downwards instead (negative vely).
... note: if you have trouble getting this example to work, try comparing your javascript code against our finished version (also see it running live).
... summary we hope you had fun writing your own real world random bouncing balls example, using various object and object-oriented techniques from throughout the module!
The "why" of web performance - Learn web development
as an example, consider the loading experience of cnn.com, which at the time of this writing had over 400 http requests with a file size of over 22.6mb.
...our example 22.6 mb cnn.com experience would cost about 11% of the average indian's daily wage to download.
...for example, this might be making a purchase, reading an article, or subscribing to a newsletter.
... 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.
Framework main features - Learn web development
the following shows a simple jsx example: const subject = "world"; const header = ( <header> <h1>hello, {subject}!</h1> </header> ); this expression represents an html <header> element with a <h1> element inside.
... the code snippets in the rest of this section will use react as an example, and are written with jsx.
... as an example, consider a button that counts how many times it has been clicked.
... for example, our authorcredit react component might be utilized inside an article component.
Advanced Svelte: Reactivity, lifecycle, accessibility - Learn web development
for example, in the following piece of code: const foo = obj.foo foo.bar = 'baz' svelte won't update references to obj.foo.bar, unless you follow it up with obj = obj.
... note: to see another example using tick(), visit the svelte tutorial.
... our onedit() function can now be much simpler: function onedit() { editing = true // enter editing mode } as a last example before we move on, let's go back to our todo.svelte component and give focus to the edit button after the user presses save or cancel.
...in the following example, the first three declarations are props, and the rest are exported values: <script> export let bar = 'optional default initial value' // prop export let baz = undefined // prop export let format = n => n.tofixed(2) // prop // these are readonly export const thisis = 'readonly' // read-only export export fun...
Git and GitHub - Learn web development
git is an example of a vcs, and github is a web site + infrastructure that provides a git server plus a number of really useful tools for working with git repositories individually or in teams, such as reporting issues with the code, reviewing tools, project management features such as assigning tasks and task statuses, and more.
... it is also preferrable that you have some basic terminal knowledge, so for example moving between directories, creating files, and modifying the system path.
... 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.
... mastering issues (from github) issues are like a forum for your github project, where people can ask questions and report problems, and you can manage updates (for example assigning people to fix issues, clarifying the issue, letting people know things are fixed).
Gecko info for Windows accessibility vendors
for example, we may say event_alert instead of the full event_system_alert.
...for example, "3 of 5" indicates the 3rd object out of 5.
...for example, "open\tctrl+o" role_tooltip xul: <tooltip> or tooltiptext attribute role_application default role of root object of application dhtml: role="wairole:application" accname() exposes the <title> of the current pane.
... here are the methods for isimpledomdocument: hresult get_url (/* [out] */ bstr *url); // location of document hresult get_title (/* [out] */ bstr *title); // from the <title> hresult get_mimetype(/* [out] */ bstr *mimetype); // for example text/html or text/plain hresult get_doctype (/* [out] */ bstr *doctype); // from the <!doctype ..> hresult get_namespaceuriforid( // translate namespace id's from isimpledomnode /* [in] */ unsigned short namespaceid, // calls into the actual namespace uri's /* [out] */ bstr *namespaceuri); hresult put_alternateviewmediatypes(/* [in] */ bstr * commaseparatedmediatypes); // for example "a...
Multiprocess on Windows
use their moz.build and .rc files as examples.
...for example: static const mozilla::mscom::arraydata kmyarraydata[] { { // first arraydata definition }, { // second arraydata definition } }; mozilla::mscom::registerarraydata(kmyarraydata); each arraydata struct corresponds to one function; with length_is and/or size_is annotations.
...for example, if interface ifoo inherits from iunknown, the lowest possible mmethodindex for ifoo could be 3, because indices 0, 1, and 2 are occupied by the functions that ifoo inherited from iunknown.
... simple example now you know about mainthreadhandoff::wrapinterface and about the smart pointers, you're ready to wrap an interface: accessible* myaccessible = ....; mozilla::mscom::stauniqueptr<iaccessible> acctowrap; myaccessible->getnativeinterface(mozilla::mscom::getter_addrefs(acctowrap)); mozilla::mscom::proxyuniqueptr<iaccessible> wrapped; hresult hr = mozilla::mscom::mainthreadhandoff::wrapinterface(...
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.
... a common example of this is 'em' units, which depend on the font size.
Debugging on Mac OS X
once done, you should be able to open any file quickly by hitting cmd-shift-o and typing in the name of a file.) in the product menu, select scheme > new scheme and name your scheme (for example, "debug").
...# breakpoint set --name nsthread::processnextevent --thread-index 1 --auto-continue true --one-shot true breakpoint command add -s python # this script that we run does not work if we try to use the global 'lldb' # object, since it is out of date at the time that the script runs (for # example, `lldb.target.executable.fullpath` is empty).
...for example, type js to see the javascript stack.
...when that launches a child process (for example, when you start to load a webpage), xcode will notice and attach to that child process.
Gecko Logging
example usage code sample #include "mozilla/logging.h" using mozilla::loglevel; static mozilla::lazylogmodule slogger("example_logger"); static void dostuff() { moz_log(slogger, loglevel::info, ("doing stuff.")); int i = 0; int start = time::nowms(); moz_log(slogger, loglevel::debug, ("starting loop.")); while (i++ < 10) { moz_log(slogger, loglevel::verbose, ("i = %d", i)); } // ...
... set moz_log="example_logger:3" in the windows command prompt (cmd.exe), don't use quotes: set moz_log=example_logger:3 if you want this on geckoview example, use the following adb command to launch process: adb shell am start -n org.mozilla.geckoview_example/.geckoviewactivity --es env0 "moz_log=example_logger:3" there are special module names to change logging behavior.
... for example, if you want to specify "sync", "timestamp" and "rotate": set moz_log="example_logger:3,timestamp,sync,rotate:10" to adjust the logging after firefox has started, you can set prefs under the logging.
...for example, setting logging.foo to 3 will set the log module foo to start logging at level 3.
Multiple Firefox profiles
for example, you might want to have some extensions installed for web development, but not for general-purpose web browsing.
... the one being run by this firefox instance will include the bold text "this is the profile in use" for example, if you find that text beneath the entry for "profile: suzie", then you are running in a profile named suzie.
... for example, if firefox is installed in the recommended location, you would enter /applications/firefox.app/contents/macos/firefox.
... here is a complete example terminal command from steps 2-3: /applications/firefox.app/contents/macos/firefox -profile /users/suzie/library/application\ support/firefox/profiles/r99d1z7c.default if the profile manager window does not open, firefox may have been running in the background, even though it was not visible.
Frame script loading and lifetime
for example: var mm = window.messagemanager; mm.loadframescript("chrome://my-e10s-extension/content/frame-script.js", true); the script will be loaded into all tabs currently open in this window, and all new tabs opened afterwards.
...for example, from bootstrap.js: services.mm.addmessagelistener( 'my-addon-id', { receivemessage: function() { console.log('incoming message from frame script:', amsg.data); } }, true // must set this argument to true, otherwise sending message from framescript will not work during and after the unload event on the contentmessagemanager triggers ); then in your fr...
...you need to send a message to your frame scripts, telling them to disable themselves; for example, by undoing any changes they've made or removing any event listeners.
...the workaround is to randomize the frame script's url; for example, by appending "?" + math.random().
Embedding Tips
for example, the default prompt service uses xul to render prompt dialogs and embedders may wish to render them in a way more appropriate for their application and platform..
... here is a simple example which demonstrates the principle.
...for example, if you wanted to check the server response headers, you might check onstatechange for state_start | state_is_request flags, and from the nsirequest argument qi fornsihttpchanne and call methods on that to determine response codes and other information from the server.
... for an example, see browserimpl.cpp in mfcembed and its simple cbrowsertooltip class implemented in mfc.
Getting Started with Chat
if you have something long to post, a code snippet for example, use paste.mozilla.org and paste the generated url in irc instead.
...for example, "ashughes: good morning!" every channel has its own topic.
...for example, do not talk about thunderbird issues in #firefox.
...for example, you can connect using ssl or a non-secure connection, and you can configure the client to automatically connect to a server and join a particular set of channels when you start the client.
Interfacing with the Add-on Repository
this example will use the latter, in order to randomly select a recommended add-on and offer to install it.
...for example: searchfailed: function() { this.shownotification("i have no recommendations for you right now!", "oh noes!", null); }, here, we call a shownotification() method with some parameters that we'll look at shortly when we get to our shownotification() method below.
...it receives a list of the matching addons, the number of add-ons returned, and the total number of add-ons that matched the query (in case the returned number is smaller than the requested number, for example).
... for example: searchsucceeded: function(addons, addoncount, totalresults) { var num = math.floor(math.random() * addoncount); this.shownotification("would you like to try the " + addons[num].name + " addon?", "install", addons[num].install); }, this routine randomly selects one of the returned add-ons, then calls the previously mentioned shownotification() routine, passing in as parameters a prompt including the name of the returned add-on, a label for the button to show in the notification ("install"), and the addoninstall object that can be used with the add-on manager api to install the add-on.
PopupNotifications.jsm
this service is used, for example, to display geolocation related notifications.
...for example, geolocation related notifications have the id "geolocation".
...for most use cases, the value of this parameter should be date.now() plus an offset indicating the amount of time the notification should be kept open (for example, date.now() + 30000 for 30 seconds).
...the first parameter to the callback is a string identifying the state change, and may be one of the following: "dismissed" the notification has been dismissed by the user (for example, by clicking away or by switching tabs).
Task.jsm
example: task.spawn( function() { yield ...
... examples general example cu.import("resource://gre/modules/task.jsm"); task.spawn(function* () { // this is our task.
... let mypromise = getpromiseresolvedontimeoutwithvalue(1000, "value"); let result = yield mypromise; // this part is executed only after the promise above is resolved (after // one second, in this imaginary example).
...os.file.getcurrentdirectory(); let path = os.path.join(currentdir, ".mozconfig"); try { let info = yield os.file.stat(path); console.log("the .mozconfig file is " + info.size + " bytes long."); } catch (ex if ex instanceof os.file.error && ex.becausenosuchfile) { console.log("you don't have .mozconfig in " + currentdir); } }).then(null, components.utils.reporterror); in this example, if the promise returned by os.file.stat is rejected, an exception is thrown inside the task.
Mozilla Content Localized in Your Language
all we ask is that you name this page according to this example, "mozilla content in spanish (es-mx)" and add your locale code tag at the bottom.
... example: 1.23 (decimal separator) or 1,000 (thousand separator) using comma or period.
...if yes, list all forms of plural forms and examples if there is more than one.
...for example, "cancel", "clear history", "add email", "select all", etc.
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...
...localizing step-by-step dtd files in order to provide an example that can be viewed quickly in your ui, we'll start by translating a dtd file named searchbar.dtd that contains the string "manage search engines...".
... 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.
...untrusted connection in the example above), like so (example for polish): <!entity certerror.pagetitle "niezaufane połączenie"> once you have translated all the <!entity> strings in this file, you should save your work and open the next .dtd or .properties file.
QA phase
preliminary instructions we will be using the following file directories for this example: your working directory (root)/ mozilla-aurora (en-us source, pulled from http://hg.mozilla.org/releases/mozilla-aurora )/ l10n-central (directory for l10n directories, one per l10n; often referred to as "l10n base")/ your-locale-code (a directory with your l10n files, in this example we'll use x-testing) example: root/mozilla-aurora & root/l10n-central/x-testing additionally,...
...we'll use x-testing here for our example.
... enter the following command: $ hg log -l 1 you should see an output similar to the one below: changeset: 0:7c543e8f3a6a tag: tip user: your name <email@example.com> date: mon nov 23 18:08:25 2009 +0100 summary: added search bar strings now compare the local repository on your machine with the remote hg repository by entering this command: $ hg outgoing http://hg.mozilla.org/l10n-central/x-testing the hg outgoing command compares the two repositories and lists all changesets that are present locally, but not in the remote repository.
...you can expect to see output like this: comparing with http://hg.mozilla.org/l10n-central/x-testing searching for changes changeset: 0:7c543e8f3a6a tag: tip user: your name <email@example.com> date: mon nov 23 18:08:25 2009 +0100 summary: added search bar strings let's now push this changeset.
Localization formats
see the example below.
...for example, below is the entire introduction used for a certificate that was presented to those who downloaded firefox during the download day campaign.
... case study: download day in the above gettext example, notice how the web developer used "certificate_intro" as the value of the msgid.
... but, in the download day example, when changes were made to en-us, the web-developer had to push those changes to all the repositories of all the locales.
Mozilla Web Developer FAQ
for example, the existence of document.getelementbyid() can be checked as follows: if(document.getelementbyid) { /* code that uses document.getelementbyid() */ } why doesn’t mozilla display my alt tooltips?
...however, this particular display method is not required and some other browsers show the title attribute in the browser status bar, for example.
...for example, to represent ☺, you should use white smiling face (u+263a).
...for example, the body element gets no special treatment.
Mozilla Web Services Security Model
for example, to determine what web sites can access a web service at http://www.example.com/dir1/dir2/service, mozilla would load the file http://www.example.com/web-scripts-access.xml, which may choose to delegate the decision to http://www.example.com/dir1/dir2/web...pts-access.xml.
...for example, when accessing a web service at http://www.example.com/dir1/dir2/service, if the access file at http://www.example.com/web-scripts-access.xml contains a delegate element, mozilla will instead use http://www.example.com/dir1/dir2/web...ipt-access.xml to determine whether access is permitted.
...(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 ...
Power profiling overview
for example, the gecko profiler takes samples at 1000hz using a timer.
... the most notable example of a hybrid proxy measurement is the "energy impact" used by os x's activity monitor.
...this can identify specific changes that caused regressions, for example.
...for example, it can be useful to gradually remove elements from a web page and see how the power-related measurements change.
Profiling with Xperf
note that it's possible to capture even more data for the non-heap profile; for example, you might want to be able to correlate heap events with performance data, so you can do "xperf -on base -stackwalk profile".
... these refer to the time range that was selected for the summary graph; for example, something that's in the aofi category was allocated before the start of the selected time range, but the free event happened inside.
... tips in the summary views, the yellow bar can be dragged left and right to change the grouping -- for example, drag it to the left of the module column to have grouping happen only by process (stuff that's to the left), so that you get symbols in order of weight, regardless of what module they're in.
...traces can be captured fine without this option (for example, from nightlies), but the stack information will not be useful.
Research and prep
e-commerce search these search engines should allow users to get connected to new and used products they want to buy as quickly and painlessly as possible in a "trusted" site -- for example, choosing the most popular auction, general shopping, or classified type sites that have the desired user experience are good choices.
... 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.
Productization guide
for example, a search provider can deliver a very good quality of search results — but only in a specific country or language, and we have to take this into account when considering default search engines for a locale.
...for example, we ship firefox with 6 or 7 search engine plug-ins to make users’ lives easier when they’re looking for information, translation, products, multimedia, spelling and definitions, etc.
... another example: when the user clicks on a mailto: link, we suggest a couple of possible handlers chosen from the applications installed on their computer.
...for example, putting one sample news feed on the bookmarks toolbar in new profiles in firefox helps in learning about the live bookmarks.
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.
...let's take slovenian as an example.
... asymmetry the example above could benefit from another of l20n's features: local variables.
... byteunit-b = b byteunit-kb = kb byteunit-mb = mb byteunit-gb = gb byteunit-tb = tb for example in french, the unit abbreviations are as follows: byteunit-b = o byteunit-kb = ko byteunit-mb = mo byteunit-gb = go byteunit-tb = to solution in l20n, the french localizer could provide the translation of unit abbreviations locally in the localization file, without impacting the english localization file.
NSS Sample Code sample2
nss sample code 2: symmetric encryption /* example code to illustrate des enccryption/decryption using nss.
... * the example skips the details of obtaining the key & iv to use, and * just uses a hardcoded key & iv.
...this example shows the use of a raw key.
... */ #include "nss.h" #include "pk11pub.h" /* example key & iv */ unsigned char gkey[] = {0xe8, 0xa7, 0x7c, 0xe2, 0x05, 0x63, 0x6a, 0x31}; unsigned char giv[] = {0xe4, 0xbb, 0x3b, 0xd3, 0xc3, 0x71, 0x2e, 0x58}; int main(int argc, char **argv) { ck_mechanism_type ciphermech; pk11slotinfo* slot = null; pk11symkey* symkey = null; secitem* secparam = null; pk11context* enccontext = null; secitem keyitem, ivitem; secstatus rv, rv1, rv2; unsigned char data[1024], buf1[1024], buf2[1024]; int i, result_len, tmp1_outlen, tmp2_outlen; /* initialize nss * if your application code has already initialized nss, you can skip it * here.
NSS Sample Code sample4
nss sample code 4: pki encryption /* example code to illustrate pki crypto ops (encrypt with public key, * decrypt with private key) * * code assumes that you have set up a nss database with a certificate * and a private key.
...-1 -2 -5 * * there are many ways to setup a public/private key to use - this * example shows one of them.
... * * this example does not do any padding.
...for example purposes, this function hardcodes the password.
sslintro.html
these functions tell the library which cipher suites are permitted by policy (for example, to comply with export restrictions).
...these can be used, for example, when interrupting and restarting socket communications, when the application needs to change socket parameters, or when an application imports a socket into ssl after the tcp connection on that socket has already been established.
...the application's protocol (for example, http) determines which end has responsibility to talk first.
...this occurs, for example, when an https server has received a request and determines that before it can answer the request, it needs to request an authentication certificate from the client.
Rhino shell
examples invocation here the shell is invoked three times from the command line.
... $ java org.mozilla.javascript.tools.shell.main -e "print('hi')" hi $ java org.mozilla.javascript.tools.shell.main js> print('hi') hi js> 6*7 42 js> function f() { return a; } js> var a = 34; js> f() 34 js> quit() $ cat echo.js for (i in arguments) { print(arguments[i]) } $ java org.mozilla.javascript.tools.shell.main echo.js foo bar foo bar $ spawn and sync the following example creates 2 threads via spawn and uses sync to create a synchronized version of the function test.
... 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 ...
GC Rooting Guide
s suggested that these are used in preference to the template class (gecko uses the template versions): template class typedef js::rooted<js::value> js::rootedvalue js::rooted<jsobject*> js::rootedobject js::rooted<jsstring*> js::rootedstring js::rooted<jsscript*> js::rootedscript js::rooted<jsid> js::rootedid for example, instead of this: jsobject* localobj = js_getobjectofsomesort(cx); you would write this: js::rootedobject localobj(cx, js_getobjectofsomesort(cx)); spidermonkey makes it easy to remember to use js::rooted<t> types instead of a raw pointer because all of the api methods that may gc take a js::handle<t>, as described below, and js::rooted<t> autoconverts to js::handle<t> but a bare pointer doe...
... for example, instead of: jsobject * somefunction(jscontext *cx, jsobject* obj) { // ...
... typedef js::mutablehandle<js::value> js::mutablehandlevalue js::mutablehandle<jsobject*> js::mutablehandleobject js::mutablehandle<jsstring*> js::mutablehandlestring js::mutablehandle<jsscript*> js::mutablehandlescript js::mutablehandle<jsid> js::mutablehandleid js::mutablehandle<t> should be used for all out-parameters, for example instead of: bool maybegetvalue(jscontext *cx, js::value* valueout) { // ...
... for example, instead of this: struct heapstruct { jsobject* msomeobject; js::value msomevalue; }; you should write: struct heapstruct { js::heap<jsobject*> msomeobject; js::heap<js::value> msomevalue; }; tracing js::nativeobject all gc pointers stored on the heap must be traced.
How to embed the JavaScript engine
in particular, it has more and better code examples!
...eno = 1; js::compileoptions opts(cx); opts.setfileandline(filename, lineno); bool ok = js::evaluate(cx, opts, script, strlen(script), &rval); if (!ok) return 1; } jsstring *str = rval.tostring(); printf("%s\n", js_encodestring(cx, str)); } js_destroycontext(cx); js_shutdown(); return 0; } build and run the hello world example build command line depends on the os and the tools.
... copy the code example above into a text editor and save the file as helloworld.cpp in the spidermonkey js\src directory.
...// js_callfunctionname(cx, global, "func", 2, argv.begin(), rval.address()); js_callfunctionname(cx, global, "func", argv, &rval); example say the click event is for the top-most or focused ui element at position (x, y): jsobject *target, *event; js::autovaluearray<1> argv(cx); /* * find event target and make event object to represent this click.
Web Replay
for example, script compilation involves gc thing allocation, and observing changes in an object will change its shape.
... for example, incremental gcs (a non-deterministic component) work by posting events to the main thread (a deterministic component), so for now incremental gcs are disabled.
... these operations may be property accesses, evals, or object calls, and an example is accessing the font property of a canvasrenderingcontext2d.
... in general, redirections are needed for any function that is (a) not compiled as part of gecko, and either (b) may behave differently between recording and replaying, or (c) depends on data produced by other redirected functions (for example, corefoundation types like cfarrayref and cfstringref).
Gecko states
for example, menu itmes are programmatically hidden until a user activates the menu.
...for example, a list box can have both state_invisible and state_offscreen set.
...for example, a user could change the size of a window by clicking the border with a mouse and dragging the mouse.
...for example, a user can click on the titlebar for the object and drag the object to a new location.
XPCOM changes in Gecko 2.0
for example, in your component's javascript code : components.utils.import("resource://gre/modules/xpcomutils.jsm"); function mycomponent() { } mycomponent.prototype = { // this must match whatever is in chrome.manifest!
...for an up-to-date example of implementing a dynamic modules, see nssamplemodule.cpp.
...if your add-on depends upon xbl bindings attached to content objects—for example, the ability to call functions or get and set properties created by the xbl binding—you will need to use the xpcnativewrapper property wrappedjsobject to access wrapped objects.
...this may be the case if, for example, you've written an extension that adds a delete button to a web mail service, and the service defines a window.delete() function that you need to call.
XPCOM Stream Guide
MozillaTechXPCOMGuideStreams
using streams in c++ using streams in javascript input streams input streams are not scriptable - you cannot directly call .read() on them, for example.
...gestream) .getoutputstream(); var instream = components.classes["@mozilla.org/io/string-input-stream;1"] .createinstance(components.interfaces.nsistringinputstream); var data = "hello world"; instream.setdata(data, data.length); while (instream.available()) { outstream.writefrom(instream, instream.available()); } note this is an inefficient example: the only important part is how to feed the output stream.
... this can mean if you have characters beyond ascii code 255, you risk losing data using nsstringstream, for example.
... 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.
How To Pass an XPCOM Object to a New Window
a more useful example is available in the source code: toolkit/components/help/content/contexthelp.js#61 if you want to be able to call functions within an xpcom object from a xul window's code, you can do so if you pass the xpcom object as one of the arguments to the window creation method.
... for example: var ww = components.classes["@mozilla.org/embedcomp/window-watcher;1"].
... getservice(components.interfaces.nsiwindowwatcher); var win = ww.openwindow(null, "chrome://myextension/content/debug.xul", "debug history", "chrome,centerscreen,resizable", myobject); note in this example that myobject is passed to the openwindow() method; you can pass any xpcom object (or any other value, for that matter) in this way.
... to access the xpcom object from the window's code, you can access the window.arguments[] array, as shown in the example below: components.utils.reporterror(string(window.arguments[0])); this will produce output similar to "[xpconnect wrapped nsimyxpcomobject]".
Components.utils.evalInWindow
the result is structured cloned back to the original context, unless it is native (for example, if it returns a dom node, this is not structured cloned, because the original context will see that through an xraywrapper already), so it's guaranteed to behave predictably.
...even so, while the code is being evaluated it is in the content's context, so the caller has to be prepared for the possibility that the content could have redefined behavior (for example, a setter in the script may have been redefined to do something unexpected).
...if this is just native (for example, a dom node), then the function relies on xraywrappers to wrap the returned content, otherwise the result is structured-cloned.
...example suppose a page script defines a variable: // page-script.js var somelocalvariable = { name: "selection1", node: document.documentelement }; an add-on script or other privileged script can access the variable using evalinwindow(): // add-on-script.js var result = components.utils.evalinwindow("somelocalvariable", contentwindow); console.log(result); // {"name":"selection1","node":{}} the add-on code can modify the variable as well, of course: // add-on-script.js components.utils.evalinwindow("somelocalvariable.newprop = 42", contentwindow); // page-script.js console.log(window.somelocalvariable.newprop...
Language bindings
the result is structured cloned back to the original context, unless it is native (for example, if it returns a dom node, this is not structured cloned, because the original context will see that through an xraywrapper already), so it's guaranteed to behave predictably.
...for example, you can import xpcomutils.jsm to avoid copy/pasting long xpcom component registration boilerplate in your component files.components.utils.importglobalpropertiesimports various objects into a system scope.components.utils.isxraywrapperwhen privileged javascript in gecko accesses objects belonging to less-privileged code (such as untrusted web content), it does so, by default, with "xray vision":...
...for example, privileged code using an xray to a dom object sees only the original, native version of the dom object.
...pyxpcom is actively used in activestate komodo products, for example.rbxpcomrbxpcom (ruby cross-platform com) provides bindings between the popular ruby programming language and xpcom.
IAccessibleHyperlink
an example is an image map which is an image with multiple links each of which is associated with a separate non-overlapping area of the image.
...an interesting use case is an image map where each area is associated with multiple actions, for example an image map of smart tags.
...for example, for a text link this method could return the substring of the containing string where the substring is overridden with link behavior, and for an image link this method could return an iunknown variant for iaccessibleimage.
...for example this method could return a bstr variant of the uri.
nsIAccessibleRelation
when there is more than one object in the group each member may have one and the same target, for example a grouping object.
... it is also possible that each member has multiple additional targets, for example one for every other member in the group.
... relation_flows_to 0x07 content flows from this object to a target object, that is has content that flows logically to another object in a sequential way, for example text flow.
... relation_flows_from 0x08 content flows to this object from a target object, that is has content that flows logically from another object in a sequential way, for example text flow.
nsIAccessibleStates
for example, menu items are programmatically hidden until a user activates the menu.
...for example, a list box can have both state_invisible and state_offscreen set.
...for example, a user could change the size of a window by clicking the border with a mouse and dragging the mouse.
...for example, a user can click on the titlebar for the object and drag the object to a new location.
nsIAlertsService
for example, it can be used to notify the user that their downloads are complete or that they have new mail.
... exceptions thrown ns_error_not_available unable to display the notification; this may happen, for example, on mac os x if growl is not installed.
... example simple usage the following code was used to display the above notification.
... getservice(components.interfaces.nsialertsservice); try { alertsservice.showalertnotification("", "alerts service test", "click me", true, "cookie", listener, ""); } catch (e) { // this can fail on mac os x } example 2 this example shows how to use all the available observer topics: var as = cc['@mozilla.org/alerts-service;1'].getservice(ci.nsialertsservice); var notiflistener = { observe: function(asubject, atopic, adata) { console.error('incoming notification observer:', asubject, atopic, adata); if (atopic == 'alertclickcallback') { console.error('user clicked trying t...
nsIContentPrefService2
(see nsicontentpref below.) for example, if you want to remember the user's preference for a certain zoom level on www.mozilla.org pages, you might store a preference whose domain is "www.mozilla.org", whose name is "zoomlevel", and whose value is the numeric zoom level.
...as a consumer of this interface, you might choose to let a global preference override all non- global preferences of the same name, for example, for whatever definition of "override" is appropriate for your use case.
...domains may be specified either exactly, like "example.com", or as full urls, like "http://example.com/foo/bar".
... in the latter case the api extracts the full domain from the url, so if you specify "http://foo.bar.example.com/baz", the domain is taken to be "foo.bar.example.com", not "example.com".
nsIFilePicker
specify it without a leading dot, for example "jpg".
... example some example filter strings: "*.ics" "*.txt; *.doc; *.rtf" appendfilters() appends a list of file extension filters, from the predefined list, to the dialog.
...you may or multiple filters together; for example filterall | filterhtml.
... example here's an example: const nsifilepicker = components.interfaces.nsifilepicker; var fp = components.classes["@mozilla.org/filepicker;1"] .createinstance(nsifilepicker); fp.init(window, "dialog title", nsifilepicker.modeopen); fp.appendfilters(nsifilepicker.filterall | nsifilepicker.filtertext); fp.open(function (rv) { if (rv == nsifilepicker.returnok || rv == nsifilepicker.returnre...
nsIFrameScriptLoader
if this function is called on a chromemessagebroadcaster (for example, a global frame message manager or a window message manager) then: loadframescript() will load the frame script independently into each applicable frame: every open frame in the given window for the window message manager, or every frame in every window for the global message manager if aallowdelayedload is true, then the script will also be loaded into any applicable new frames opened after ...
... for example: let windowmm = window.messagemanager; windowmm.loadframescript('data:,dump("foo\n");', true); this will load a separate instance of the frame script into every tab open in the window associated with this window message manager.
...for example data:,dump("foo\n"); aallowdelayedload boolean if true, this flag means that the frame script will be loaded into any new frames opened after the loadframescript() call, until removedelayedframescript() is called for that script.
...if you used aallowdelayedload, you should call this as part of your cleanup (for example, when your add-on is disabled or uninstalled).
nsILocalFile
example #include "prlink.h" #include "nserror.h" #include "nsilocalfile.h" // load the dll corresponding to the given nsilocalfile...
... example #include <stdio.h> #include "nserror.h" #include "nsilocalfile.h" // read the contents of a nsilocalfile...
...for example, the octal value 0600 may be used to limit read and write access to the current user of the system.
... example #include "prio.h" #include "nserror.h" #include "nsilocalfile.h" // read the contents of a nsilocalfile...
nsIMsgFolder
for example, special folders cannot be deleted.
...for example, in the sent folder, recipients are more relevant than the sender.
...for example, newsgroups cannot have subfolders, and the inbox on some imap servers cannot have subfolders.
...for example, newsgroups and some special folders can't be renamed.
nsINetworkLinkService
for example, the link is down during dhcp configuration (unless there is another usable interface already configured).
... link_type_2g 5 a '2g' mobile connection (for example, gsm, gprs, edge).
... link_type_3g 6 a '3g' mobile connection (for example, umts, cdma).
... link_type_4g 7 a '4g' mobile connection (for example, lte, umb).
nsIObserver
example the following code is an implementation of nsiobserver that is registered to receive notifications for the "mytopicid" topic.
...see code snippets:preferences - using preference observers for an example.
...e); observerservice.addobserver(this, "mytopicid", false); }, unregister: function() { var observerservice = components.classes["@mozilla.org/observer-service;1"] .getservice(components.interfaces.nsiobserverservice); observerservice.removeobserver(this, "mytopicid"); } } instantiation - this should be fired once you're ready to start observing (for example a window's load event).
... observer = new myobserver(); destruction - this should be fired once you're done observing (for example a window's unload event).
nsIObserverService
see nsiobserver for a javascript example.
...see example.
... example this notifies all nsiobservers watching the "mytopicid" topic with an additional data parameter.
... usage examples are provided in the nsiobserver documentation.
nsIPipe
for example, a worker thread might write data to a pipe from which the main thread will read.
...for example, if you try to read from an empty pipe that has not yet been closed, then if that pipe's input end is non-blocking, then the read call will fail immediately with ns_base_stream_would_block as the error condition.
...this example presumes that the pipe is being filled asynchronously on some background thread.
...for example, in the case of an empty non-blocking pipe, the user can call nsiasyncinputstream.asyncwait() on the input end of the pipe to be notified when the pipe has data to read (or when the pipe becomes closed).
nsIRequest
inherits from: nsisupports last changed in gecko 1.9.1 (firefox 3.5 / thunderbird 3.0 / seamonkey 2.0) for example nsichannel typically passes itself as the nsirequest argument to the nsistreamlistener on each onstartrequest, ondataavaliable, and onstoprequest invocation.
...consider, for example, a http response with a "cache-control: no-cache" header.
... implementations must not send any notifications (for example via nsirequestobserver) synchronously from this function.
...requests do not necessarily start out pending; in some cases, requests have to be explicitly initiated (for example nsichannel implementations are only pending once asyncopen returns successfully).
nsIURL
if the url denotes a path to a directory and not a file, for example http://host/foo/bar/, then the directory attribute accesses the complete /foo/bar/ portion, and the filename is the empty string.
...if the url denotes a path to a directory and not a file, for example http://host/foo/bar/, then the directory attribute accesses the complete /foo/bar/ portion, and the filename is the empty string.
...for example, the filepath of "http://host/foo/bar.html#baz" is "/foo/bar.html".
...examples: this.spec auritocompare.spec result http://mozilla.org/ http://www.mozilla.org/ "" http://foo.com/bar/ ftp://foo.com/bar/ "" http://foo.com:8080/ http://foo.com/bar/ "" ftp://user@foo.com/ ftp://user:pw@foo.com/ "" ftp://foo.com/bar/ ftp://foo.com/bar ftp://foo.com/ ftp://foo.com/bar/ ftp://foo...
nsIXULTemplateQueryProcessor
for example, a query might have the following syntax: (?id, ?name, ?url) from bookmarks where parentfolder = ?start this query might generate a result for each bookmark within a given folder.
...the reference aref may be used to determine the reference when calculating the value for the binding, for example when a value should depend on the value of another variable.
...as an example, if the reference aref is the variable ?count which holds the value 5, and the expression aexpr is the string '+2', the value of the variable avar would be 7, assuming the query processor considers the syntax '+2' to mean add two to the reference.
...for example, for an xml source, the datasource might be an nsidomnode.
Using nsIDirectoryService
in the example below, prop is a string that references your requested file locations.
... c++ nscomptr<nsifile> dir; ns_getspecialdirectory(prop, getter_addrefs(dir)); if (!dir) return ns_error_failure; javascript: var file = components.classes["@mozilla.org/file/directory_service;1"] .getservice(components.interfaces.nsiproperties) .get("profd", components.interfaces.nsifile); (the example is taken from the code snippets section of this site.) adding a location: there are currently two ways to add a file location to the directory service: directly and delayed.
...customizing the locations is important if, for example, your application already has a profile directory or other resource directories.
...for example, in seamonkey, the profile service is a provider for locations that are relative to the current profile.
Using the clipboard
const gclipboardhelper = components.classes["@mozilla.org/widget/clipboardhelper;1"] .getservice(components.interfaces.nsiclipboardhelper); gclipboardhelper.copystring("put me on the clipboard, please."); this example will first create a clipboard helper and then copy a short string to the clipboard.
...for example, a piece of html can be represented in both its original html form and in plain text.
... the following boilerplate utility functions will be used in all later code examples.
...for example, a textbox would accept "text/unicode" (or "text/plain") while a composer window might accept html and image data.
wrappedJSObject
regular xpconnect wrappers which you can encounter, for example, when using xpcom components implemented in js.
... example component to see how the wrappedjsobject property works, we need an example xpcom component implemented in js.
...in this example we use getservice, but as long as we get the reference from xpcom, our component gets wrapped by xpconnect in the same way: var comp = components.classes["@myself.com/my-component;1"].getservice(); if we try to call the hello() method we defined in our component implementation, we get: > comp.hello(); typeerror on line 1: comp.hello is not a function this happens because, as we mentioned ea...
...for example: function helloworld() { this.wrappedjsobject = this; }; now we can get the component directly: var comp = components.classes["@myself.com/my-component;1"] .getservice().wrappedjsobject; this is a real js object: > comp [object object] so we can access any property on it: > comp.hello(); hello world!
Mail event system
for example, when a folder gets a new message, its total message count increases.
... sample control flow here is an example of a possible flow of control when a new message is added to a folder.
... in this example, there is a dialog open that shows properties for this folder including the message count.
...opertychanged notifyitemboolpropertychanged onitemboolpropertychanged notifyitemunicharpropertychanged onitemunicharpropertychanged notifyitempropertyflagchanged onitempropertyflagchanged notifyitemevent onitemevent notifyfolderloaded onfolderloaded notifydeleteormovemessages ondeleteormovemessages sample code in this example, a listener will be set up to be notified when the message count changes in a folder: // our variable to know if the listener fired var listenerhasfired = false; var totalmessageslistenerhasfired = false; // the listening function that will react to changes function myonintpropertychanged(item, property, oldvalue, newvalue) { listenerhasfired=true; var propertystring = property.getunicode...
Using the Multiple Accounts API
here's an example of a common setup.
...the above example would look like this: alecf on imap.mywork.com +- inbox +- trash +- (etc) alecf on pop.myisp.com +- inbox +- trash +- (etc) news.myisp.com +- comp.os.linux.announce +- etc..
... in the above example, the list of identities would be as follows: alec flett <alecf@mywork.com>) alec flett <alecf@myisp.com>) alec flett <alecfnospam@myisp.com>) relevant api calls: nsimsgaccount.identities nsimsgaccountmanager.allservers: a list of all servers across all accounts storage the accounts are stored in the preferences.
... as an example, the above structure would be represented in your preferences like this: user_pref("mail.accountmanager.accounts", "account1,account2,account3"); user_pref("mail.account.account1.server", "server1"); user_pref("mail.account.account1.identities", "id1"); user_pref("mail.account.account2.server", "server2"); user_pref("mail.account.account2.identities", "id3"); user_pref("mail.account.account3.server", "server3"); user_pref("mail.account.account3.identities", "id3"); user_pref("mail.account.account4.server", "server4"); user_pref("mai...
Add to iPhoto
that's not really the ideal way to do things but saved some time for this simple example.
... some of this may change as i refine the example in the future; i'll update the article if and when that happens.
...for example, the cfarray type describes an array, but cfarray objects can't be changed once they've been created.
... closing remarks this is a fairly simple example of how to use js-ctypes, but it actually does something useful, and should be a helpful demonstration not just for how to use js-ctypes, but also more specifically for developers that want to interface with mac os x system frameworks.
Browser Console - Firefox Developer Tools
below is an example of how to access it, which adds a message to the browser console.
... here is an example on how to clear the contents of the browser console: components.utils.import("resource://devtools/shared/loader.jsm"); var hudservice = devtools.require("devtools/client/webconsole/hudservice"); var hud = hudservice.getbrowserconsole(); hud.jsterm.clearoutput(true); if you would like to access the content document of the browser console this can be done with the hudservice.
... this example here makes it so that when you mouse over the "clear" button it will clear the browser console: components.utils.import("resource://devtools/shared/loader.jsm"); var hudservice = devtools.require("devtools/client/webconsole/hudservice"); var hud = hudservice.getbrowserconsole(); var clearbtn = hud.chromewindow.document.queryselector('.webconsole-clear-console-button'); clearbtn.addeventlistener('mouseover', function() { hud.jsterm.clearoutput(true); }, false); bonus features available for add-on sdk add-ons, the console api is available automatically.
... here's an example add-on that just logs an error when the user clicks a widget: widget = require("sdk/widget").widget({ id: "an-error-happened", label: "error!", width: 40, content: "error!", onclick: logerror }); function logerror() { console.error("something went wrong!"); } if you build this as an xpi file, then open the browser console, then open the xpi file in firefox and install it, you'll see a widget labeled "error!" in the add-on bar: click the icon.
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.
...in the following example, the selected node (the unordered list) is modified by adding a new child node.
Responsive Design Mode - Firefox Developer Tools
dpr (pixel ratio) - beginning with firefox 68, the dpr is no longer editable; create a custom device in order to change the dpr throttling - a drop-down list where you can select the connection throttling to apply, for example 2g, 3g, or lte enable/disable touch simulation - toggles whether or not responsive design mode simulates touch events.
...for example, many pages check for touch support on load and only add event handlers if it is supported, or only enable certain features on certain browsers.
...for example: developer toolbox with rdm you can show or hide the developer tools toolbox independently of toggling responsive design mode itself: while responsive design mode is enabled, you can continue browsing as you normally would in the resized content area.
...for example, if you've selected an iphone, then firefox identifies itself as safari.
Storage Inspector - Firefox Developer Tools
for example, "http://mozilla.org" and "https://mozilla.org" are two different origins so local storage items cannot be shared between them.
...the tree is live, so if a new origin gets added (by adding an iframe, for example), it will be added to each storage type automatically.
...for example, clicking on an origin which is a child of the cookies storage type will show all the cookies belonging to that domain.
...for example: a stringified json like '{"foo": "bar"}' is shown as the origin json: {foo: "bar"}.
AbstractRange - Web APIs
set a range endpoint within the text of an element, be sure to find the text node inside the element: let startelem = document.queryselector("p"); let endelem = startelem.queryselector("span"); let range = document.createrange(); range.setstart(startelem, 0); range.setend(endelem, endelem.childnodes[0].length/2); let contents = range.clonecontents(); document.body.appendchild(contents); this example creates a new range, rng, and sets its starting point to the third child node of the first element whose class is elementclass.
...for example, in this case, we're calling clonecontents() on the range to create a new documentfragment object providing a dom subtree which replicates the contents of the specfied range.
... in this example, the start of the specified range is found within the text node below the section's heading, which means that the new documentfragment will need to contain an <h2> and, below it, a text node.
... example consider this simple html fragment of html.
AudioListener.dopplerFactor - Web APIs
example in the following example, you can see an example of how the createpanner() method, audiolistener and pannernode would be used to control audio spatialisation.
...you might be moving a character around inside a game world for example, and wanting delivery of audio to change realistically as your character moves closer to or further away from a music player such as a stereo.
... in the example you can see this being controlled by the functions moveright(), moveleft(), etc., which set new values for the panner position via the positionpanner() function.
... to see a complete implementation, check out our panner-node example (view the source code) — this demo transports you to the 2.5d "room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes!
AudioListener.forwardX - Web APIs
example in the following example, you can see an example of how the createpanner() method, audiolistener and pannernode would be used to control audio spatialisation.
...you might be moving a character around inside a game world for example, and wanting delivery of audio to change realistically as your character moves closer to or further away from a music player such as a stereo.
... in the example you can see this being controlled by the functions moveright(), moveleft(), etc., which set new values for the panner position via the positionpanner() function.
... to see a complete implementation, check out our panner-node example (view the source code) — this demo transports you to the 2.5d "room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes!
AudioListener.forwardY - Web APIs
example in the following example, you can see an example of how the createpanner() method, audiolistener and pannernode would be used to control audio spatialisation.
...you might be moving a character around inside a game world for example, and wanting delivery of audio to change realistically as your character moves closer to or further away from a music player such as a stereo.
... in the example you can see this being controlled by the functions moveright(), moveleft(), etc., which set new values for the panner position via the positionpanner() function.
... to see a complete implementation, check out our panner-node example (view the source code) — this demo transports you to the 2.5d "room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes!
AudioListener.forwardZ - Web APIs
example in the following example, you can see an example of how the createpanner() method, audiolistener and pannernode would be used to control audio spatialisation.
...you might be moving a character around inside a game world for example, and wanting delivery of audio to change realistically as your character moves closer to or further away from a music player such as a stereo.
... in the example you can see this being controlled by the functions moveright(), moveleft(), etc., which set new values for the panner position via the positionpanner() function.
... to see a complete implementation, check out our panner-node example (view the source code) — this demo transports you to the 2.5d "room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes!
AudioListener.positionX - Web APIs
example in the following example, you can see an example of how the createpanner() method, audiolistener and pannernode would be used to control audio spatialisation.
...you might be moving a character around inside a game world for example, and wanting delivery of audio to change realistically as your character moves closer to or further away from a music player such as a stereo.
... in the example you can see this being controlled by the functions moveright(), moveleft(), etc., which set new values for the panner position via the positionpanner() function.
... to see a complete implementation, check out our panner-node example (view the source code) — this demo transports you to the 2.5d "room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes!
AudioListener.positionY - Web APIs
example in the following example, you can see an example of how the createpanner() method, audiolistener and pannernode would be used to control audio spatialisation.
...you might be moving a character around inside a game world for example, and wanting delivery of audio to change realistically as your character moves closer to or further away from a music player such as a stereo.
... in the example you can see this being controlled by the functions moveright(), moveleft(), etc., which set new values for the panner position via the positionpanner() function.
... to see a complete implementation, check out our panner-node example (view the source code) — this demo transports you to the 2.5d "room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes!
AudioListener.positionZ - Web APIs
example in the following example, you can see an example of how the createpanner() method, audiolistener and pannernode would be used to control audio spatialisation.
...you might be moving a character around inside a game world for example, and wanting delivery of audio to change realistically as your character moves closer to or further away from a music player such as a stereo.
... in the example you can see this being controlled by the functions moveright(), moveleft(), etc., which set new values for the panner position via the positionpanner() function.
... to see a complete implementation, check out our panner-node example (view the source code) — this demo transports you to the 2.5d "room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes!
AudioListener.setOrientation() - Web APIs
example in the following example, you can see an example of how the createpanner() method, audiolistener and pannernode would be used to control audio spatialisation.
...you might be moving a character around inside a game world for example, and wanting delivery of audio to change realistically as your character moves closer to or further away from a music player such as a stereo.
... in the example you can see this being controlled by the functions moveright(), moveleft(), etc., which set new values for the panner position via the positionpanner() function.
... to see a complete implementation, check out our panner-node example (view the source code) — this demo transports you to the 2.5d "room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes!
AudioListener.setPosition() - Web APIs
example in the following example, you can see an example of how the createpanner() method, audiolistener and pannernode would be used to control audio spatialisation.
...you might be moving a character around inside a game world for example, and wanting delivery of audio to change realistically as your character moves closer to or further away from a music player such as a stereo.
... in the example you can see this being controlled by the functions moveright(), moveleft(), etc., which set new values for the panner position via the positionpanner() function.
... to see a complete implementation, check out our panner-node example (view the source code) — this demo transports you to the 2.5d "room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes!
AudioListener.speedOfSound - Web APIs
example in the following example, you can see an example of how the createpanner() method, audiolistener and pannernode would be used to control audio spatialisation.
...you might be moving a character around inside a game world for example, and wanting delivery of audio to change realistically as your character moves closer to or further away from a music player such as a stereo.
... in the example you can see this being controlled by the functions moveright(), moveleft(), etc., which set new values for the panner position via the positionpanner() function.
... to see a complete implementation, check out our panner-node example (view the source code) — this demo transports you to the 2.5d "room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes!
AudioListener.upX - Web APIs
WebAPIAudioListenerupX
example in the following example, you can see an example of how the createpanner() method, audiolistener and pannernode would be used to control audio spatialisation.
...you might be moving a character around inside a game world for example, and wanting delivery of audio to change realistically as your character moves closer to or further away from a music player such as a stereo.
... in the example you can see this being controlled by the functions moveright(), moveleft(), etc., which set new values for the panner position via the positionpanner() function.
... to see a complete implementation, check out our panner-node example (view the source code) — this demo transports you to the 2.5d "room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes!
AudioListener.upY - Web APIs
WebAPIAudioListenerupY
example in the following example, you can see an example of how the createpanner() method, audiolistener and pannernode would be used to control audio spatialisation.
...you might be moving a character around inside a game world for example, and wanting delivery of audio to change realistically as your character moves closer to or further away from a music player such as a stereo.
... in the example you can see this being controlled by the functions moveright(), moveleft(), etc., which set new values for the panner position via the positionpanner() function.
... to see a complete implementation, check out our panner-node example (view the source code) — this demo transports you to the 2.5d "room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes!
AudioListener.upZ - Web APIs
WebAPIAudioListenerupZ
example in the following example, you can see an example of how the createpanner() method, audiolistener and pannernode would be used to control audio spatialisation.
...you might be moving a character around inside a game world for example, and wanting delivery of audio to change realistically as your character moves closer to or further away from a music player such as a stereo.
... in the example you can see this being controlled by the functions moveright(), moveleft(), etc., which set new values for the panner position via the positionpanner() function.
... to see a complete implementation, check out our panner-node example (view the source code) — this demo transports you to the 2.5d "room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes!
AudioNode.connect() - Web APIs
WebAPIAudioNodeconnect
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.
... for example, you might send the audio from a mediaelementaudiosourcenode—that is, the audio from an html5 media element such as <audio>—through a band pass filter implemented using a biquadfilternode to reduce noise before then sending the audio along to the speakers.
... this example creates an oscillator, then links it to a gain node, so that the gain node controls the volume of the oscillator node.
... var audiocontext = window.audiocontext || window.webkitaudiocontext; var audioctx = new audiocontext(); var oscillator = audioctx.createoscillator(); var gainnode = audioctx.creategain(); oscillator.connect(gainnode); gainnode.connect(audioctx.destination); audioparam example in this example, we will be altering the gain value of a gainnode using an oscillatornode with a slow frequency value.
AudioParam - Web APIs
examples first, a basic example showing a gainnode having its gain value set.
... gain is an example of an a-rate audioparam, as the value can potentially be set differently for each sample frame of the audio.
... var audiocontext = window.audiocontext || window.webkitaudiocontext; var audioctx = new audiocontext(); var gainnode = audioctx.creategain(); gainnode.gain.value = 0; next, an example showing a dynamicscompressornode having some param values maniuplated.
... these are examples of k-rate audioparam's, as the values are set for the entire audio block at once.
BaseAudioContext.createPanner() - Web APIs
example in the following example, you can see an example of how the createpanner() method, audiolistener and pannernode would be used to control audio spatialisation.
...you might be moving a character around inside a game world for example, and wanting delivery of audio to change realistically as your character moves closer to or further away from a music player such as a stereo.
... in the example you can see this being controlled by the functions moveright(), moveleft(), etc., which set new values for the panner position via the positionpanner() function.
... to see a complete implementation, check out our panner-node example (view the source code) — this demo transports you to the 2.5d "room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes!
BaseAudioContext.decodeAudioData() - Web APIs
example in this section we will first cover the older callback-based system and then the newer promise-based syntax.
... older callback syntax in this example, the getdata() function uses xhr to load an audio track, setting the responsetype of the request to arraybuffer so that it returns an array buffer as its response that we then store in the audiodata variable .
... the buttons in the example simply run getdata() to load the track and start it playing, and stop it playing, respectively.
... note: you can run the example live (or view the source.) // define variables var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); var source; var pre = document.queryselector('pre'); var myscript = document.queryselector('script'); var play = document.queryselector('.play'); var stop = document.queryselector('.stop'); // use xhr to load an audio track, and // decodeaudiodata to decode it and stick it in a buffer.
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.
... the first of these three (supportedinstruments in the example below) contains a data property that has to conform to the structure defined by the basiccardrequest dictionary.
... 56notes disabled notes available only in nightly builds.disabled from version 56: this feature is behind the dom.payments.request.enabled preference (needs to be set to true) and the dom.payments.request.supportedregions preference (needs to be set to a comma-delineated list of one or more 2-character iso country codes indicating the countries in which to support payments (for example, us,ca.).
... 56notes disabled notes available only in nightly builds.disabled from version 56: this feature is behind the dom.payments.request.enabled preference (needs to be set to true) and the dom.payments.request.supportedregions preference (needs to be set to a comma-delineated list of one or more 2-character iso country codes indicating the countries in which to support payments (for example, us,ca.).
Using the Beacon API - Web APIs
this document contains examples of the beacon interfaces.
... the following example specifies a handler for the load and beforeunload events.
... window.onload = window.onunload = function analytics(event) { if (!navigator.sendbeacon) return; var url = "https://example.com/analytics"; // create the data to send var data = "state=" + event.type + "&location=" + location.href; // send the beacon var status = navigator.sendbeacon(url, data); // log the data and result console.log("sendbeacon: url = ", url, "; data = ", data, "; status = ", status); }; the following example creates a submit handler and when that event is fired, the handler calls sendbeacon().
... in the following example, a worker sends a beacon using the url and data from the global context.
CanvasRenderingContext2D.arcTo() - Web APIs
examples how arcto works one way to think about arcto() is to imagine two straight segments: one from the starting point to a first control point, and another from there to a second control point.
...; ctx.linewidth = 5; ctx.moveto(200, 20); ctx.arcto(200,130, 50,20, 40); ctx.stroke(); // start point ctx.beginpath(); ctx.fillstyle = 'blue'; ctx.arc(200, 20, 5, 0, 2 * math.pi); ctx.fill(); // control points ctx.beginpath(); ctx.fillstyle = 'red'; ctx.arc(200, 130, 5, 0, 2 * math.pi); // control point one ctx.arc(50, 20, 5, 0, 2 * math.pi); // control point two ctx.fill(); result in this example, the path created by arcto() is thick and black.
... creating a rounded corner this example creates a rounded corner using arcto().
...in this example, the arc's connecting line goes above, instead of below, the coordinate specified by moveto().
Drawing text - Web APIs
a filltext example the text is filled using the current fillstyle.
... function draw() { var ctx = document.getelementbyid('canvas').getcontext('2d'); ctx.font = '48px serif'; ctx.filltext('hello world', 10, 50); } <canvas id="canvas" width="300" height="100"></canvas> draw(); a stroketext example the text is filled using the current strokestyle.
... function draw() { var ctx = document.getelementbyid('canvas').getcontext('2d'); ctx.font = '48px serif'; ctx.stroketext('hello world', 10, 50); } <canvas id="canvas" width="300" height="100"></canvas> draw(); styling text in the examples above we are already making use of the font property to make the text a bit larger than the default size.
... a textbaseline example edit the code below and see your changes update live in the canvas: ctx.font = '48px serif'; ctx.textbaseline = 'hanging'; ctx.stroketext('hello world', 0, 100); playable code <canvas id="canvas" width="400" height="200" class="playable-canvas"></canvas> <div class="playable-buttons"> <input id="edit" type="button" value="edit" /> <input id="reset" type="button" value="reset" /> </div> ...
Using channel messaging - Web APIs
for example, what if you wanted to add a contact to the address book from the main site, add high scores from your game into your main profile, or add new background music choices from the audio player onto the game?
... simple examples to get your started, we have published a couple of demos on github.
... we'll be focusing on the latter example in this article.
...for this initial port transfering this message could be an empty string but in this example it is set to 'init'.
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.
...a url for a cached media file, for example, can't be indexed directly.
... examples all the following examples assume a service worker has been registered.
...dd indexed content async function registercontent(data) { const registration = await navigator.serviceworker.ready; // feature detect content index if (!registration.index) { return; } // register content try { await registration.index.add(data); } catch (e) { console.log('failed to register content: ', e.message); } } retrieving items within the current index the below example shows an asynchronous function that retrieves items within the content index and iterates over each entry, building a list for the interface.
DataTransfer.setData() - Web APIs
example data types are text/plain and text/uri-list.
... return value void example this example shows the use of the datatransfer object's getdata(), setdata() and cleardata() methods.
... <!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 drag has started ev.currenttarget.style.border = "dashed"; // set the drag's format and data.
...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 z...
DataTransfer.types - Web APIs
some values that are not mime types are special-cased for legacy reasons (for example "text").
... example this example shows the use of the types and items properties.
... <!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 tree ev.datatransfer.setdata("text/plain", ev.target.id); ev.datatransfer.effectallowed = "move"; } function drop_handler(ev) { console.log("drop: target.id = " + ev.target.id); ev.preventdefault(); // get the id of the target and add the moved element to the target's dom var data = ev.datatransfer.getdata("text"); ev.target.appendchild(document.ge...
...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);">d...
DataTransferItem.webkitGetAsEntry() - Web APIs
example in this example, a drop zone is created, which responds to the drop event by scanning through the dropped files and directories, outputting a hierarchical directory listing.
... <p>drag files and/or directories to the box below!</p> <div id="dropzone"> <div id="boxtitle"> drop files here </div> </div> <h2>directory tree:</h2> <ul id="listing"> </ul> css content the styles used by the example are shown here.
...in chromium-based browsers, the following example will only return a max of 100 entries.
...the container is always a list element in this example, as you'll see shortly.
DataTransferItemList.add() - Web APIs
some example types are text/html and text/plain.
...if the drag item couldn't be created (for example, if the associated datatransfer object has no data store), null is returned.
... example this example shows the use of the add() method.
...paragraph ...</p>", "text/html"); datalist.add("http://www.example.org","text/uri-list"); } function drop_handler(ev) { console.log("drop"); ev.preventdefault(); var data = event.datatransfer.items; // loop through the dropped items and log their data for (var i = 0; i < data.length; i++) { if ((data[i].kind == 'string') && (data[i].type.match('^text/plain'))) { // this item is the target node data[i].getasstring(function (s){ ...
Document: keyup event - Web APIs
for example, a lowercase "a" will be reported as 65 by keydown and keyup, but as 97 by keypress.
...some changes are not detectable by keyup, for example pasting text from the context menu in a text input.
...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.
... addeventlistener keyup example <p>focus the iframe first (e.g.
Document.lastModified - Web APIs
syntax var string = document.lastmodified; examples simple usage this example alerts the value of lastmodified.
... alert(document.lastmodified); // returns: tuesday, december 16, 2017 11:09:42 transforming lastmodified into a date object this example transforms lastmodified into a date object.
... let olastmodif = new date(document.lastmodified); transforming lastmodified into milliseconds this example transforms lastmodified into the number of milliseconds since january 1, 1970, 00:00:00, local time.
...here is a possible example of how to show an alert message when the page changes (see also: javascript cookies api): if (date.parse(document.lastmodified) > parsefloat(document.cookie.replace(/(?:(?:^|.*;)\s*last_modif\s*\=\s*([^;]*).*$)|^.*$/, "$1") || "0")) { document.cookie = "last_modif=" + date.now() + "; expires=fri, 31 dec 9999 23:59:59 gmt; path=" + location.pathname; alert("this page has changed!"); } …the same example, but skipping the first visit: var nlastvisit = parsefloat(document.cookie.replace(/(?:(?:^|.*;)\s*last_modif\s*\=\s*([^;]*).*$)|^.*$/, "$1")), nlastmodif = date.parse(document.lastmodified)...
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.
... this may include, for example, the user switching applications using an application switcher interface or the "home" button on a mobile device.
...this can happen if, for example, the hardware supports palm rejection to prevent a hand resting on the display while using a stylus from accidentally triggering events.
... 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 ...
DocumentOrShadowRoot.activeElement - Web APIs
for example, on macos systems, elements that aren't text input elements are not typically focusable by default.
... example html <p>select some text from one of the text areas below:</p> <form> <textarea name="ta-example-one" id="ta-example-one" rows="7" cols="40">this is text area one.
...donec tincidunt, lorem a porttitor molestie, odio nibh iaculis libero, et accumsan nunc orci eu dui.</textarea> <textarea name="ta-example-two" id="ta-example-two" rows="7" cols="40">this is text area two.
...ent.activeelement; const selection = activetextarea.value.substring( activetextarea.selectionstart, activetextarea.selectionend ); const outputelement = document.getelementbyid('output-element'); const outputtext = document.getelementbyid('output-text'); outputelement.innerhtml = activetextarea.id; outputtext.innerhtml = selection; } const textarea1 = document.getelementbyid('ta-example-one'); const textarea2 = document.getelementbyid('ta-example-two'); textarea1.addeventlistener('mouseup', onmouseup, false); textarea2.addeventlistener('mouseup', onmouseup, false); result specifications specification status comment html living standardthe definition of 'activeelement' in that specification.
Locating DOM elements using selectors - Web APIs
this is much faster than past techniques, wherein it was necessary to, for example, use a loop in javascript code to locate the specific items you needed to find.
... 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.
...for example, to select all paragraph (p) elements in a document whose css class is either warning or note, you can do the following: var special = document.queryselectorall( "p.warning, p.note" ); you can also query by id.
... for example: var el = document.queryselector( "#main, #basic, #exclamation" ); after executing the above code, el contains the first element in the document whose id is one of main, basic, or exclamation.
EffectTiming.fill - Web APIs
WebAPIEffectTimingfill
for example, setting fill to "none" means the animation's effects are not applied to the element if the current time is outside the range of times during which the animation is running, while "forwards" ensures that once the animation's end time has been passed, the element will continue to be drawn in the state it was in at its last rendered frame.
... examples here are a few examples.
...lign: center; margin-top: 0px; padding-top: 2px; padding-bottom: 4px; color: white; background-color: darkgreen; font: 14px "open sans", "arial", sans-serif; } #text { width: 160px; padding: 10px; position: relative; text-align: center; align-self: center; color: white; font: bold 2em "lucida grande", "open sans", sans-serif; } while there's other css involved in this example, the part that really matters for our purposes is the css that styles the "box" element that we'll be animating.
... follow the white rabbit example in the follow the white rabbit example, the white rabbit's animation is formed by coupling a keyframeeffect with an animation object.
Element: click event - Web APIs
the interval is also likely to be affected by user preferences; for example, accessibility options may extend this interval to make it easier to perform multiple clicks with adaptive interfaces.
...see this live example for a demonstration.
...see this live example for a demonstration.
... examples this example displays the number of consecutive clicks on a <button>.
Element.getAttributeNS() - Web APIs
examples the following svg document reads the value of the foo attribute in a custom namespace.
... <svg xmlns="http://www.w3.org/2000/svg" xmlns:test="http://www.example.com/2014/test" width="40" height="40"> <circle id="target" cx="12" cy="12" r="10" stroke="#444" stroke-width="2" fill="none" test:foo="hello namespaced attribute!"/> <script type="text/javascript"> var ns = 'http://www.example.com/2014/test'; var circle = document.getelementbyid( 'target' ); console.log( 'attribute test:foo: "' + circle.getattributens( ns, 'foo' ) + '"' ); </script> </svg> in an html5 document the attribute has to be accessed with test:foo since namespaces are not supported.
... <!doctype html> <html> <body> <svg xmlns="http://www.w3.org/2000/svg" xmlns:test="http://www.example.com/2014/test" width="40" height="40"> <circle id="target" cx="12" cy="12" r="10" stroke="#444" stroke-width="2" fill="none" test:foo="foo value"/> </svg> <script type="text/javascript"> var ns = 'http://www.example.com/2014/test'; var circle = document.getelementbyid( 'target' ); console.log('attribute value: ' + circle.getattribute('test:foo')); </script> </body> </html> notes namespaces are only supported in xml documents.
... getattributens() differs from getattribute() in that it allows you to further specify the requested attribute as being part of a particular namespace, as in the example above, where the attribute is part of the fictional "specialspace" namespace on mozilla.
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.q...
...[...document.queryselectorall(`[class^="funnel-chart-percent"]`)]; // const refs = [...document.queryselectorall(`[class$="funnel-chart-percent"]`)]; // const refs = [...document.queryselectorall(`[class~="funnel-chart-percent"]`)]; obtaining a list of matches to obtain a nodelist of all of the <p> elements contained within the element "mybox": var matches = mybox.queryselectorall("p"); this example returns a list of all <div> elements within "mybox" with a class of either "note" or "alert": var matches = mybox.queryselectorall("div.note, div.alert"); here, we get a list of the document's <p> elements whose immediate parent element is a div with the class "highlighted" and which are located inside a container whose id is "test".
... var container = document.queryselector("#test"); var matches = container.queryselectorall("div.highlighted > p"); this example uses an attribute selector to return a list of the iframe elements in the document that contain an attribute named "data-src": var matches = document.queryselectorall("iframe[data-src]"); here, an attribute selector is used to return a list of the list items contained within a list whose id is "userlist" which have a "data-active" attribute whose value is "1": var container = document.queryselector("#userlist"); var matches = container.queryselectorall("li[data-active='1']"); accessing the matches once the nodelist of matching elements is returned, you can examine it just like any array.
... in this example, when selecting ".outer .inner" in the context the <div> with the class "select", the element with the class ".inner" is still found, even though .outer is not a descendant of the base element on which the search is performed (".select").
Element.requestFullscreen() - Web APIs
detecting full-screen activation you can determine whether or not your attempt to switch to full-screen mode is successful by using the promise returned by requestfullscreen(), as seen in the example below.
...it's also important to listen for fullscreenchange to be aware when, for example, the user manually toggles full-screen mode, or when the user switches applications, causing your application to temporarily exit full-screen mode.
... examples this function toggles the first <video> element found in the document into and out of full-screen mode.
... you can see this example in action or view or remix the code on glitch.
Element - Web APIs
WebAPIElement
for example, the htmlelement interface is the base interface for html elements, while the svgelement interface is the basis for all svg elements.
...for example, the browser might fire this event when the user presses the esc key or clicks a "close dialog" button which is part of the browser's ui.
...for example, if a script has an execution error or an image can't be found or is invalid.
... touch events touchcancel fired when one or more touch points have been disrupted in an implementation-specific manner (for example, too many touch points are created).
Event.composed - Web APIs
WebAPIEventcomposed
for example, this includes synthetic events that are created without their composed option wil set to true.
... 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 first definition looks like this, for example: customelements.define('open-shadow', class extends htmlelement { constructor() { super(); let pelem = document.createelement('p'); pelem.textcontent = this.getattribute('text'); let shadowroot = this.attachshadow({mode: 'open'}) .appendchild(pelem); } }); we then insert one of each element into our page: <open-shadow text="i have an open shadow root"></open-shadow> <closed-shadow text="i have a closed shadow root"></closed-shadow> then include a click event listener on the <html> element: document.queryselector('html').addeventlistener('click',function(e) { console.lo...
... 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.preventDefault() - Web APIs
syntax event.preventdefault(); examples blocking default click handling toggling a checkbox is the default action of clicking on a checkbox.
... this example demonstrates how to prevent that from happening: javascript document.queryselector("#id-checkbox").addeventlistener("click", function(event) { document.getelementbyid("output-box").innerhtml += "sorry!
... <code>preventdefault()</code> won't let you check this!<br>"; event.preventdefault(); }, false); html <p>please click on the checkbox control.</p> <form> <label for="id-checkbox">checkbox:</label> <input type="checkbox" id="id-checkbox"/> </form> <div id="output-box"></div> result stopping keystrokes from reaching an edit field the following example demonstrates how invalid text input can be stopped from reaching the input field with preventdefault().
...it's not an elegant function but does the job for the purposes of this example: var warningtimeout; var warningbox = document.createelement("div"); warningbox.classname = "warning"; function displaywarning(msg) { warningbox.innerhtml = msg; if (document.body.contains(warningbox)) { window.cleartimeout(warningtimeout); } else { // insert warningbox after mytextbox mytextbox.parentnode.insertbefore(warningbox, mytextbox.nextsibling); } warningtimeout...
EventSource - Web APIs
for example, eventsource is a useful approach for handling things like social media status updates, news feeds, or delivering data into a client-side storage mechanism like indexeddb or web storage.
...this limit is per browser + domain, so that means that you can open 6 sse connections across all of the tabs to www.example1.com and another 6 sse connections to www.example2.com.
... 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.
... note: you can find a full example on github — see simple sse demo using php.
FileSystemDirectoryReader.readEntries() - Web APIs
example in this example, a drop zone is created, which responds to the drop event by scanning through the dropped files and directories, outputting a hierarchical directory listing.
... <p>drag files and/or directories to the box below!</p> <div id="dropzone"> <div id="boxtitle"> drop files here </div> </div> <h2>directory tree:</h2> <ul id="listing"> </ul> css content the styles used by the example are shown here.
...in chromium-based browsers, the following example will only return a max of 100 entries.
...the container is always a list element in this example, as you'll see shortly.
Using the Gamepad API - Web APIs
t.gamepad; // note: // gamepad === navigator.getgamepads()[gamepad.index] if (connecting) { gamepads[gamepad.index] = gamepad; } else { delete gamepads[gamepad.index]; } } window.addeventlistener("gamepadconnected", function(e) { gamepadhandler(e, true); }, false); window.addeventlistener("gamepaddisconnected", function(e) { gamepadhandler(e, false); }, false); this previous example also demonstrates how the gamepad property can be held after the event has completed — a technique we will use for device state querying later.
...for example, the first code example above you be rewritten as shown below: window.addeventlistener("gamepadconnected", function(e) { var gp = navigator.getgamepads()[e.gamepad.index]; console.log("gamepad connected at index %d: %s.
... using button information let's look at a simple example that displays connection information for one gamepad (it ignores subsequent gamepad connections) and allows you to move a ball around the screen using the four gamepad buttons on the right hand side of the gamepad.
... []); if (!gamepads) { return; } var gp = gamepads[0]; if (buttonpressed(gp.buttons[0])) { b--; } else if (buttonpressed(gp.buttons[2])) { b++; } if (buttonpressed(gp.buttons[1])) { a++; } else if (buttonpressed(gp.buttons[3])) { a--; } ball.style.left = a * 2 + "px"; ball.style.top = b * 2 + "px"; start = requestanimationframe(gameloop); } complete example: displaying gamepad state this example shows how to use the gamepad object, as well as the gamepadconnected and gamepaddisconnected events in order to display the state of all gamepads connected to the system.
Using the Geolocation API - Web APIs
the geolocation api is used to retrieve the user's location, so that it can for example be used to display their position using a mapping api.
...devices with a gps, for example, can take a minute or more to get a gps fix, so less accurate data (ip location or wifi) may be returned to getcurrentposition().
... navigator.geolocation.getcurrentposition((position) => { dosomething(position.coords.latitude, position.coords.longitude); }); the above example will cause the dosomething() function to execute when the location is obtained.
... 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.
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.
... this may include, for example, the user switching applications using an application switcher interface or the "home" button on a mobile device.
...this can happen if, for example, the hardware supports palm rejection to prevent a hand resting on the display while using a stylus from accidentally triggering events.
... 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 pointer events obsolete ...
HTMLImageElement.srcset - Web APIs
for example, to provide an image resource to be used when the renderer needs a 450 pixel wide image, use the width descriptor string 450w.
...as an example, to state that the corresponding image should be used when the pixel density is double the standard density, you can give the pixel density descriptor 2x or 2.0x.
... example html the html below indicates that the default image is the 200 pixel wide version of the clock image we use in several places throughout our documentation.
... for additional examples, see our guide to responsive images.
HTMLMediaElement.srcObject - Web APIs
see below for an example.
... examples basic example in this example, a mediastream from a camera is assigned to a newly-created <video> element.
... const mediastream = await navigator.mediadevices.getusermedia({video: true}); const video = document.createelement('video'); video.srcobject = mediastream; in this example, a new mediasource 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.
Using microtasks in JavaScript with queueMicrotask() - Web APIs
).then(data => { this.cache[url] = data; this.data = data; this.dispatchevent(new event("load")); }); } }; the problem introduced here is that by using a task in one branch of the if...else statement (in the case in which the image is available in the cache) but having promises involved in the else clause, we have a situation in which the order of operations can vary; for example, as seen below.
... examples simple microtask example in this simple example, we see that enqueueing a microtask causes the microtask's callback to run after the body of this top-level script is done running.
... log("before enqueueing the microtask"); queuemicrotask(() => { log("the microtask has run.") }); log("after enqueueing the microtask"); result timeout and microtask example in this example, a timeout is scheduled to fire after zero milliseconds (or "as soon as possible").
... microtask from a function this example expands slightly on the previous one by adding a function that does some work.
IDBDatabaseException - Web APIs
constant value description abort_err 8 a request was aborted, for example, through a call to idbtransaction.abort.
...for example, an object, such as an object store or index, already exists and a request attempted to create a new one.
... not_found_err 3 the operation failed because the requested database object could not be found; for example, an object store did not exist but was being opened.
... unknown_err 1 the operation failed for reasons unrelated to the database itself, and it is not covered by any other error code--for example, a failure due to disk io errors.
KeyboardEvent.getModifierState() - Web APIs
for example, on windows, pressing ctrl key may make it return true.
...for example, firefox users can customize this with a pref, "ui.key.accelkey".
... example // ignore if following modifier is active.
... event.preventdefault(); // consume the key event break; } } although this example uses .getmodifierstate() with "alt", "control", "meta" and "shift", using event.altkey, event.ctrlkey, event.metakey and event.shiftkey may be more preferable.
Keyboard API - Web APIs
the key value takes into account the keyboard's locale (for example, 'en-us'), layout (for example, 'qwerty'), and modifier-key state (shift, control, etc.).
... the following example demonstrates how to get the location-specific or layout-specific string associated with the key labeled w on an english qwerty keyboard.
...examples of such key/key combinations include escape, alt+tab, and ctrl+n.
... those keys and key combinations are typically captured by the user agent or the underlying operating system, as illustrated in the following example.
KeyframeEffect.setKeyframes() - Web APIs
element.animate([ { opacity: 1, easing: 'ease-out' }, { opacity: 0.1, easing: 'ease-in' }, { opacity: 0 } ], 2000); in this example, the specified easing only applies from the keyframe where it is specified until the next keyframe.
...for example, consider this simple animation — the keyframe object looks like so: let rotate360 = [ { transform: 'rotate(360deg)' } ]; we have only specified the end state of the animation, and the beginning state is implied.
...the property names are specified using camel-case so for example background-color becomes backgroundcolor and background-position-x becomes backgroundpositionx.
... 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' } ); spe...
MediaQueryList - Web APIs
for example, if the media query is (min-width: 400px), the change event is fired any time the width of the document's viewport changes such that its width moves across the 400px boundary in either direction.
... 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.
...ss */ 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'; } } mql.addeventlistener('change', screentest); note: you can find this example on github (see the source code, and also see it running live).
... 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.
... using a boolean value in this example, we provide a simple value of true for the audio property.
... result using a mediatrackconstraints object now let's look at a similar example that uses a set of constraints based on the mediatrackconstraints dictionary: html content <p>click the start button below to begin the demonstration.</p> <div id="startbutton" class="button"> start </div> <audio id="audio" autoplay controls></audio><br> <div id="log"></div> css content body { font: 14px "open sans", "arial", sans-serif; } audio { margin-top: 20px; border: 1px solid...
Navigator.onLine - Web APIs
for example, the property should return false when users click links soon after they lose internet connection.
... example view a live example.
... to check if you are online, query window.navigator.online, as in the following example: if (navigator.online) { console.log('online'); } else { console.log('offline'); } if the browser doesn't support navigator.online the above example will always come out as false/undefined.
... to see changes in the network state, use addeventlistener to listen for the events on window.online and window.offline, as in the following example: window.addeventlistener('offline', function(e) { console.log('offline'); }); window.addeventlistener('online', function(e) { console.log('online'); }); specifications specification status comment html living standardthe definition of 'navigator.online' in that specification.
Node.insertBefore() - Web APIs
WebAPINodeinsertBefore
example example 1 <div id="parentelement"> <span id="childelement">foo bar</span> </div> <script> // create the new node to insert let newnode = document.createelement("span") // get a reference to the parent node let parentdiv = document.getelementbyid("childelement").parentnode // begin test case [ 1 ] : existing childelement (all works correctly) let sp2 = document.getelementbyid("childelement...
...ined // non-existent node of id "childelement" parentdiv.insertbefore(newnode, sp2) // implicit dynamic cast to type node // end test case [ 2 ] // begin test case [ 3 ] : childelement is of type "undefined" ( string ) let sp2 = "undefined" // non-existent node of id "childelement" parentdiv.insertbefore(newnode, sp2) // generates "type error: invalid argument" // end test case [ 3 ] </script> example 2 <div id="parentelement"> <span id="childelement">foo bar</span> </div> <script> // create a new, plain <span> element let sp1 = document.createelement("span") // get the reference element let sp2 = document.getelementbyid("childelement") // get the parent element let parentdiv = sp2.parentnode // insert the new element into before sp2 parentdiv.insertbefore(sp1, sp2) </script> note: th...
... in the previous example, sp1 could be inserted after sp2 using: parentdiv.insertbefore(sp1, sp2.nextsibling) if sp2 does not have a next sibling, then it must be the last child — sp2.nextsibling returns null, and sp1 is inserted at the end of the child node list (immediately after sp2).
... example 3 insert an element before the first child element, using the firstchild property.
Node - Web APIs
WebAPINode
for example, attempting to add children to a node type that cannot have children will throw an exception.
... examples remove all children nested within a node function removeallchildren(element) { while (element.firstchild) { element.removechild(element.firstchild) } } sample usage /* ...
... sample usage the following example prints the textcontent properties of each <span> tag in a <div> element named "box": <div id="box"> <span>foo</span> <span>bar</span> <span>baz</span> </div> const box = document.getelementbyid("box") eachnode(box, function(node) { if (null != node.textcontent) { console.log(node.textcontent) } }) the above will result in the following strings printing to the user's console: "\n...
...e if (node.nodetype !== node.text_node) { return } if (typeof pattern === "string") { if (-1 !== node.textcontent.indexof(pattern)) { matches.push(node) } } else if (pattern.test(node.textcontent)) { if (!pattern.global) { endscan = true matches = node } else { matches.push(node) } } }) return matches } for example, to find text nodes that contain typos: const typos = ["teh", "adn", "btu", "adress", "youre", "msitakes"] const pattern = new regexp("\\b(" + typos.join("|") + ")\\b", "gi") const mistakes = grep(document.body, pattern) console.log(mistakes) specifications specification status comment domthe definition of 'node' in that specification.
Notification.requestPermission() - Web APIs
read using the notifications api for a good example of how to feature detect this and run code as appropriate.
...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 ...
...to see a example in action, check out our to-do list example (also see the app running live.) note: in the above example we spawn notifications in response to a user gesture (clicking a button).
...firefox is already doing this from version 72, for example.
Page Visibility API - Web APIs
for example, if your web app is playing a video, it can pause the video when the user puts the tab into the background, and resume playback when the user returns to the tab.
...for example, watching for blur and focus events on the window helps you know when your page is not the active page, but it does not tell you that your page is actually hidden to the user.
... example view live example (video with sound).
... the example, which pauses the video when you switch to another tab and plays again when you return to its tab, was created with the following code: // set the name of the hidden property and the change event for visibility var hidden, visibilitychange; if (typeof document.hidden !== "undefined") { // opera 12.10 and firefox 18 and later support hidden = "hidden"; visibilitychange = "visibilitychange"; } else if (typeof document.mshidden !== "undefined") { hidden = "mshidden"; visibilitychange = "msvisibilitychange"; } else if (typeof document.webkithidden !== "undefined") { hidden = "webkithidden"; visibilitychange = "webkitvisibilitychange"; } var videoelement = document.getelementbyid("videoelement"); // if the page is hidden, pause the video; // if the page is shown, play the ...
PaintWorklet - Web APIs
examples the following three examples go together to show creating, loading, and using a paintworklet.
... create a paintworklet the following shows an example worklet module.
...ght/size; y++) { for(let x = 0; x < geom.width/size; x++) { const color = colors[(x + y) % colors.length]; ctx.beginpath(); ctx.fillstyle = color; ctx.rect(x * size, y * size, size, size); ctx.fill(); } } } } // register our class under a specific name registerpaint('checkerboard', checkerboardpainter); load a paintworklet the following example demonstrates loading the above worklet from its js file and does so by feature detection.
... <script> if ('paintworklet' in css) { css.paintworklet.addmodule('checkerboard.js'); } </script> use a paintworklet this example shows how to use a paintworklet in a stylesheet, including the simplest way to provide a fallback if paintworklet isn't supported.
PannerNode.distanceModel - Web APIs
example in the following example, you can see an example of how the createpanner() method, audiolistener and pannernode would be used to control audio spatialisation.
...you might be moving a character around inside a game world for example, and wanting delivery of audio to change realistically as your character moves closer to or further away from a music player such as a stereo.
... in the example you can see this being controlled by the functions moveright(), moveleft(), etc., which set new values for the panner position via the positionpanner() function.
... to see a complete implementation, check out our panner-node example (view the source code) — this demo transports you to the 2.5d "room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes!
PannerNode.maxDistance - Web APIs
example in the following example, you can see an example of how the createpanner() method, audiolistener and pannernode would be used to control audio spatialisation.
...you might be moving a character around inside a game world for example, and wanting delivery of audio to change realistically as your character moves closer to or further away from a music player such as a stereo.
... in the example you can see this being controlled by the functions moveright(), moveleft(), etc., which set new values for the panner position via the positionpanner() function.
... to see a complete implementation, check out our panner-node example (view the source code) — this demo transports you to the 2.5d "room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes!
PannerNode.panningModel - Web APIs
example in the following example, you can see an example of how the createpanner() method, audiolistener and pannernode would be used to control audio spatialisation.
...you might be moving a character around inside a game world for example, and wanting delivery of audio to change realistically as your character moves closer to or further away from a music player such as a stereo.
... in the example you can see this being controlled by the functions moveright(), moveleft(), etc., which set new values for the panner position via the positionpanner() function.
... to see a complete implementation, check out our panner-node example (view the source code) — this demo transports you to the 2.5d "room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes!
PannerNode.setOrientation() - Web APIs
example in the following example, you can see an example of how the createpanner() method, audiolistener and pannernode would be used to control audio spatialisation.
...you might be moving a character around inside a game world for example, and wanting delivery of audio to change realistically as your character moves closer to or further away from a music player such as a stereo.
... in the example you can see this being controlled by the functions moveright(), moveleft(), etc., which set new values for the panner position via the positionpanner() function.
... to see a complete implementation, check out our panner-node example (view the source code) — this demo transports you to the 2.5d "room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes!
PannerNode.setPosition() - Web APIs
example in the following example, you can see an example of how the createpanner() method, audiolistener and pannernode would be used to control audio spatialisation.
...you might be moving a character around inside a game world for example, and wanting delivery of audio to change realistically as your character moves closer to or further away from a music player such as a stereo.
... in the example you can see this being controlled by the functions moveright(), moveleft(), etc., which set new values for the panner position via the positionpanner() function.
... to see a complete implementation, check out our panner-node example (view the source code) — this demo transports you to the 2.5d "room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes!
PannerNode.setVelocity() - Web APIs
example in the following example, you can see an example of how the createpanner() method, audiolistener and pannernode would be used to control audio spatialisation.
...you might be moving a character around inside a game world for example, and wanting delivery of audio to change realistically as your character moves closer to or further away from a music player such as a stereo.
... in the example you can see this being controlled by the functions moveright(), moveleft(), etc., which set new values for the panner position via the positionpanner() function.
... to see a complete implementation, check out our panner-node example (view the source code) — this demo transports you to the 2.5d "room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes!
PaymentRequest.PaymentRequest() - Web APIs
for example, the basic card payment method is selected by specifying the string basic-card here.
... modifiers modifiers for specific payment methods; for example, adjusting the total amount based on the payment method.
...for example, in english speaking countries you would say "pizza delivery" not "pizza shipping".
... examples the following example shows minimal functionality and focuses instead on showing the complete context of instantiating a paymentrequest object.
PublicKeyCredentialCreationOptions.rp - Web APIs
"login.example.com").
..."example.com").
..."example corp").
... 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 }) .then(function (newcredentialinfo) { // send attestation response and client extensions // to the server to proceed with the registration // of the credential }).catch(function (err) { console.error(err); }); specifications specification status comment web authentication: an api for accessing public key credentials level 1the definition of ...
PushManager.subscribe() - Web APIs
example this.onpush = function(event) { console.log(event.data); // from here we can write the data to indexeddb, send it to any open // windows, display a notification, etc.
... var options = { uservisibleonly: true, applicationserverkey: applicationserverkey }; serviceworkerregistration.pushmanager.subscribe(options).then( function(pushsubscription) { console.log(pushsubscription.endpoint); // the push subscription details needed by the application // server are now available, and can be sent to it using, // for example, an xmlhttprequest.
... console.log(error); } ); }); responding to user gestures subscribe() calls should be done in response to a user gesture, such as clicking a button, for example: btn.addeventlistener('click', function() { serviceworkerregistration.pushmanager.subscribe(options) .then(function(pushsubscription) { // handle subscription }); }) this is not only best practice — you should not be spamming users with notifications they didn't agree to — but going forward browsers will explicitly disallow notifications not triggered in response to a user gesture...
...firefox is already doing this from version 72, for example.
RTCConfiguration.iceTransportPolicy - Web APIs
this includes, for example, those candidates relayed by a stun or turn server.
...for example, in a video calling application, the app may want to prevent unknown callers from learning the callee's ip addresses until the callee has agreed to receive the call.
... examples in this example, a new connection is configured to only accept relay candidates.
... let config = { iceservers: [ { urls: [ "stun:stun.example.com" ] }, ], icetransportpolicy: "relay" }; let pc = new rtcpeerconnection(config); specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtccandidate.icetransportpolicy' in that specification.
RTCPeerConnection.addTrack() - Web APIs
for example, if all you're sharing with the remote peer is a single stream with an audio track and a video track, you don't need to deal with managing what track is in what stream, so you might as well just let the transceiver handle it for you.
... here's an example showing a function that uses getusermedia() to obtain a stream from a user's camera and microphone, then adds each track from the stream to the peer connection, without specifying a stream for each track: async opencall(pc) { const gumstream = await navigator.mediadevices.getusermedia( {video: true, audio: true}); for (const track of gumstream.gettracks()) { pc.addtrack(track); } } the result is a set of tracks being sent to the remote peer, with no stream associations.
... for example, consider this function that an application might use to begin streaming a device's camera and microphone input over an rtcpeerconnection to a remote peer: async opencall(pc) { const gumstream = await navigator.mediadevices.getusermedia( {video: true, audio: true}); for (const track of gumstream.gettracks()) { pc.addtrack(track, gumstream); } } the remote pee...
... example this example is drawn from the code presented in the article signaling and video calling and its corresponding sample code.
RTCPeerConnection.setRemoteDescription() - Web APIs
return value a promise which is fulfilled once the value of the connection's remotedescription is successfully changed or rejected if the change cannot be applied (for example, if the specified description is incompatible with one or both of the peers on the connection).
...for example, if the type is rollback and the signaling state is one of stable, have-local-pranswer, or have-remote-pranswer, this exception is thrown, because you can't roll back a connection that's either fully established or is in the final stage of becoming connected.
... example here we see a function which handles an offer received from the remote peer.
... this code is derived from the example and tutorial in the article signaling and video calling; take a look at that for more details and a more in-depth explanation of what's going on.
RTCRemoteOutboundRtpStreamStats.localId - Web APIs
you can examine, try out, and experiment with this example on glitch.
... example in this example, we have a pair of functions: the first, networkteststart(), captures an initial report, and the second, networkteststop(), captures a second report, then uses the two reports to output some information about the network conditions...
... the output log, given the styles used by the example, looks like this: in the screenshot, we see a heading followed by the scrollable <div> we refer to as statsbox.
... try it and fork it this example is available on glitch for you to try out, examine, or remix.
ReadableStreamDefaultReader.read() - Web APIs
examples example 1 - simple example this example shows the basic api usage, but doesn't try to deal with complications like stream chunks not ending on line boundaries for example.
... in this example stream is a previously-created custom readablestream.
...(see our simple random stream example for the full code).
...current chunk = ' + chunk; list2.appendchild(listitem); result += chunk; // read some more, and call this function again return reader.read().then(processtext); }); } example 2 - handling text line by line this example shows how you might fetch a text file and handle it as a stream of text lines.
Request.mode - Web APIs
WebAPIRequestmode
cors — allows cross-origin requests, for example to access various apis offered by 3rd party vendors.
... for example, when a request object is created using the request.request constructor, the value of the mode property for that request is set to cors.
... however, for requests created other than by the request.request constructor, no-cors is typically used as the mode; for example, for embedded resources where the request is initiated from markup, unless the crossorigin attribute is present, the request is in most cases made using the no-cors mode — that is, for the <link> or <script> elements (except when used with modules), or <img>, <audio>, <video>, <object>, <embed>, or <iframe> elements.
... 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 request mode in a variable: var myrequest = new request('flowers.jpg'); var mymode = myrequest.mode; // returns "cors" by default specifications specification status comment fetchthe definition of 'mode' in that specification.
ServiceWorkerRegistration.showNotification() - Web APIs
badge: a usvstring containing the url of an image to represent the notification when there is not enough space to display the notification itself such as for example, the android notification bar.
...for example, this could be in the past when a notification is used for a message that couldn’t immediately be delivered because the device was offline, or in the future for a meeting that is about to start.
...for example, [300, 100, 400] would vibrate 300ms, pause 100ms, then vibrate 400ms.
... examples navigator.serviceworker.register('sw.js'); function shownotification() { notification.requestpermission(function(result) { if (result === 'granted') { navigator.serviceworker.ready.then(function(registration) { registration.shownotification('vibration sample', { body: 'buzz!
Service Worker API - Web APIs
you can listen for the installevent; a standard action is to prepare your service worker for usage when this fires, for example by creating a cache using the built in storage api, and placing assets inside it that you'll want for running your app offline.
... for a complete tutorial to show how to build up your first basic example, read using service workers.
... performance enhancements, for example pre-fetching resources that the user is likely to need in the near future, such as the next few pictures in a photo album.
...interestingly, other specifications can and will start to make use of the service worker context, for example: background synchronization: start up a service worker even when no users are at the site, so caches can be updated, etc.
SubtleCrypto.deriveBits() - Web APIs
otherwise it will be the initial key material for the derivation function: for example, for pbkdf2 it might be a password, imported as a cryptokey using subtlecrypto.importkey().
... examples note: you can try the working examples on github.
... ecdh in this example alice and bob each generate an ecdh key pair.
... derivesharedsecret(aliceskeypair.privatekey, bobskeypair.publickey); }); }); pbkdf2 in this example we ask the user for a password, then use it to derive some bits using pbkdf2.
SubtleCrypto.exportKey() - Web APIs
examples note: you can try the working examples out on github.
... raw export this example exports an aes key as an arraybuffer containing the bytes for the key.
...*/ window.crypto.subtle.generatekey( { name: "aes-gcm", length: 256, }, true, ["encrypt", "decrypt"] ).then((key) => { const exportbutton = document.queryselector(".raw"); exportbutton.addeventlistener("click", () => { exportcryptokey(key); }); }); pkcs #8 export this example exports an rsa private signing key as a pkcs #8 object.
... 4096-bit key for systems that require long-term security moduluslength: 2048, publicexponent: new uint8array([1, 0, 1]), hash: "sha-256", }, true, ["sign", "verify"] ).then((keypair) => { const exportbutton = document.queryselector(".pkcs8"); exportbutton.addeventlistener("click", () => { exportcryptokey(keypair.privatekey); }); }); subjectpublickeyinfo export this example exports an rsa public encryption key as a pem-encoded subjectpublickeyinfo object.
SubtleCrypto.wrapKey() - Web APIs
examples note: you can try the working examples out on github.
... raw wrap this example wraps an aes key.
...*/ window.crypto.subtle.generatekey( { name: "aes-gcm", length: 256, }, true, ["encrypt", "decrypt"] ) .then((secretkey) => { return wrapcryptokey(secretkey); }) .then((wrappedkey) => { console.log(wrappedkey); }); pkcs #8 wrap this example wraps an rsa private signing key.
...tekey( { name: "rsa-pss", // consider using a 4096-bit key for systems that require long-term security moduluslength: 2048, publicexponent: new uint8array([1, 0, 1]), hash: "sha-256", }, true, ["sign", "verify"] ) .then((keypair) => { return wrapcryptokey(keypair.privatekey); }) .then((wrappedkey) => { console.log(wrappedkey); }); subjectpublickeyinfo wrap this example wraps an rsa public encryption key.
TextTrackList - Web APIs
the individual tracks can be accessed using array syntax or functions such as foreach() for example.
...see onaddtrack and onremovetrack for details and examples.
... examples getting a video element's text track list to get a media element's texttracklist, use its texttracks property.
... var texttracks = document.queryselector("video").texttracks; monitoring track count changes in this example, we have an app that displays information about the number of channels available.
URLSearchParams - Web APIs
an object implementing urlsearchparams can directly be used in a for...of structure, for example the following two lines are equivalent: for (const [key, value] of mysearchparams) {} for (const [key, value] of mysearchparams.entries()) {} note: this feature is available in web workers.
... examples var paramsstring = "q=urlutils.searchparams&topic=api"; var searchparams = new urlsearchparams(paramsstring); //iterate the search parameters.
... var paramsstring1 = "http://example.com/search?query=%40"; var searchparams1 = new urlsearchparams(paramsstring1); searchparams1.has("query"); // false searchparams1.has("http://example.com/search?query"); // true searchparams1.get("query"); // null searchparams1.get("http://example.com/search?query"); // "@" (equivalent to decodeuricomponent('%40')) var paramsstring2 = "?query=value"; var searchparams2 = new urlsearchparams(par...
...amsstring2); searchparams2.has("query"); // true var url = new url("http://example.com/search?query=%40"); var searchparams3 = new urlsearchparams(url.search); searchparams3.has("query") // true specifications specification status comment urlthe definition of 'urlsearchparams' in that specification.
VideoTrack - Web APIs
for example, the main video track would have a kind of "main".
...for example, a track whose kind is "sign" might have a label of "a sign-language interpretation".
... this first example gets the first video track on the media: var firsttrack = tracks[0]; the next example scans through all of the media's video tracks, activating the first video track that is in the user's preferred language (taken from a variable userlanguage).
...for us english, this would be "en-us", for example.
VideoTrackList - Web APIs
the individual tracks can be accessed using array syntax or functions such as foreach() for example.
...see onaddtrack and onremovetrack for details and examples.
... examples getting a media element's video track list to get a media element's videotracklist, use its videotracks property.
... var videotracks = document.queryselector("video").videotracks; monitoring track count changes in this example, we have an app that displays information about the number of channels available.
Hello GLSL - Web APIs
« previousnext » this webgl example demonstrates a very basic glsl shader program that draws a solid color square.
... note: this example will most likely work in all modern desktop browsers.
...if the canvas remains blank, you can check the output of the next example, which draws exactly the same thing.
...webgl"); if (!gl) { var paragraph = document.queryselector("p"); paragraph.innerhtml = "failed to get webgl context." + "your browser or device may not support webgl."; return null; } gl.viewport(0, 0, gl.drawingbufferwidth, gl.drawingbufferheight); gl.clearcolor(0.0, 0.0, 0.0, 1.0); gl.clear(gl.color_buffer_bit); return gl; } })(); the source code of this example is also available on github.
Raining rectangles - Web APIs
in this example, we use an object-oriented approach for the displayed rectangles, which helps to keep the state of the rectangle (its position, color, and so on) organized in one place, and the overall code more compact and reusable.
... this example combines clearing the drawing buffer with solid colors and scissoring operations.
... in addition, the example demonstrates how to integrate the webgl function calls within a game loop.
...webgl"); if (!gl) { var paragraph = document.queryselector("p"); paragraph.innerhtml = "failed to get webgl context." + "your browser or device may not support webgl."; return null; } gl.viewport(0, 0, gl.drawingbufferwidth, gl.drawingbufferheight); gl.clearcolor(0.0, 0.0, 0.0, 1.0); gl.clear(gl.color_buffer_bit); return gl; } })(); the source code of this example is also available on github.
Animating textures in WebGL - Web APIs
« previous in this demonstration, we build upon the previous example by replacing our static textures with the frames of an mp4 video file that's playing.
... this example uses the glmatrix library to perform its matrix and vertex math.
...it's nearly identical to the image onload function in the previous example — except when we call teximage2d(), instead of passing an image object, we pass in the <video> element.
... then in main() in place of the call to loadtexture() in the previous example, we call inittexture() followed by setupvideo() .
Using textures in WebGL - Web APIs
this example uses the glmatrix library to perform its matrix and vertex math.
... an example of a repeated texture is tiling an image of a few bricks to cover a brick wall.
... see this hacks.mozilla.org article for an explanation of how to use cors-approved images as webgl textures, with a self-contained example.
...a 2d <canvas> becomes tainted, for example, when a cross-domain image is drawn on it.
WebGL: 2D and 3D graphics for the web - Web APIs
WebAPIWebGL API
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.
... webgl by example a series of live samples with short explanations that showcase webgl concepts and capabilities.
... the examples are sorted according to topic and level of difficulty, covering the webgl rendering context, shader programming, textures, geometry, user interaction, and more.
Writing a WebSocket server in Java - Web APIs
introduction this example shows you how to create a websocket api server using oracle java.
... although other server-side languages can be used to create a websocket server, this example uses oracle java to simplify the example code.
... let us extend our example.
... decoding algorithm decoded byte = encoded byte xor (position of encoded byte bitwise and 0x3)th byte of key example in java: byte[] decoded = new byte[6]; byte[] encoded = new byte[] { (byte) 198, (byte) 131, (byte) 130, (byte) 182, (byte) 194, (byte) 135 }; byte[] key = new byte[] { (byte) 167, (byte) 225, (byte) 225, (byte) 210 }; for (int i = 0; i < encoded.length; i++) { decoded[i] = (byte) (encoded[i] ^ key[i & 0x3]); } } } finally { s.close(); } } finally {...
Geometry and reference spaces in WebXR - Web APIs
while you can use webxr for everything from augmenting the world with annotations to 360° video playback to scientific simulations to virtual reality training systems or anything else you can imagine, let's take a 3d video game as an example of a typical webxr application.
...for a more detailed look at how to use reference spaces to manage the player's viewpoint, see the article in the case of our game avatar example, it's rare for an avatar (or any other moving creature or machine) to be a simple blob sliding around the world.
...for example, there's simply no way for a basic headset such as a gearvr device to be made to work in an app that requires support for allowing the user to walk around the environment by tracking their real-world movements.
... for an example and a more detailed, code-level explanation of how to position, orient, and move objects in virtual space, see the article movement, orientation, and motion.
Lighting a WebXR setting - Web APIs
ambient light can also be used to apply a color tint to a scene; for example, in a game in which the player has a special pair of yellow-tinted glasses, you can add a yellow ambient light.
... the most common example of a directional light is the sun.
...light bulbs, candles, and the like are examples of point light sources.
... if two or more devices access content that uses the same third-party script, that script can be used to correlate lighting information and how it changes over time to attempt to determine a spatial relationship between the devices; this could in theory indicate that the devices are in the same general area, for example.
Advanced techniques: Creating and sequencing audio - Web APIs
to do so, we need to pass real and imaginary values into the baseaudiocontext.createperiodicwave() method.: let wave = audioctx.createperiodicwave(wavetable.real, wavetable.imag); note: in our example the wavetable is held in a separate javascript file (wavetable.js), because there are so many values.
... it is taken from a repository of wavetables, which can be found in the web audio api examples from google chrome labs.
...so in the example below the gain is being increased to 1, at a linear rate, over the time the attack range input has been set to.
...much of the code here is taken from his metronome example, which he references in said article.
Web Audio API best practices - Web APIs
you can see an example of how to use this with the web audio api in the using the web audio api tutorial.
...here is a simple example of creating the context from inside a click event: const button = document.queryselector('button'); button.addeventlistener('click', function() { const audioctx = new audiocontext(); }, false); if however, you create the context outside of a user gesture, its state will be set to suspended and it will need to be started after user interaction.
... we can use the same click event example here, test for the state of the context and start it, if it is suspended, using the resume() method.
...if for example, you want the gain value to be raised to 1 in 2 seconds time, you can do this: gainnode.gain.setvalueattime(1, audioctx.currenttime + 2); it will override the previous example (as it should), even if it were to come later in your code.
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>.
...for example, border-bottom-width instead of the border-width and border shorthand property names.
...an example difference between pre- and post-layout values includes the resolution of percentages for width or height, as those will be replaced by their pixel equivalent only for used values.
...see plugging the css history leak and privacy-related changes coming to css :visited for examples of how this is implemented.
Window.open() - Web APIs
WebAPIWindowopen
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"...
... example: status=yes, status=1, and status have identical results.
...you can examine an example explaining how to use the focus() method.
... tell the user that something like that will happen." world wide web consortium accessibility initiative regarding popups "use link titles to provide users with a preview of where each link will take them, before they have clicked on it." ten good deeds in web design, jakob nielsen, october 1999 using link titles to help users predict where they are going, jakob nielsen, january 1998 example "new window" icons & cursors always use the target attribute if javascript support is disabled or non-existent, then the user agent will create a secondary window accordingly or will render the referenced resource according to its handling of the target attribute: e.g.
Window.openDialog() - Web APIs
WebAPIWindowopenDialog
example var win = opendialog("http://example.tld/zzz.xul", "dlg", "", "pizza", 6.98); notes new features all - initially activates (or deactivates ("all=no")) all chrome (except the behavior flags chrome, dialog and modal).
... passing extra parameters to the dialog to pass extra parameters into the dialog, you can simply supply them after the windowfeatures parameter: opendialog("http://example.tld/zzz.xul", "dlg", "", "pizza", 6.98); the extra parameters will then get packed into a property named arguments of type array, and this property gets added to the newly opened dialog window.
...(another example).
... var retvals = { address: null, delivery: null }; opendialog("http://example.tld/zzz.xul", "dlg", "modal", "pizza", 6.98, retvals); if you set the properties of the retvals object in the dialog code as described below, you can now access them via the retvals array after the opendialog() call returns.
Window - Web APIs
WebAPIWindow
see also using navigation timing for additional information and examples.
...for example, if a script has an execution error or an image can't be found or is invalid.
...this happens, for example, when the user clicks the back button or when they click the forward button to move ahead in session history.
... messaging events message fired when the window receives a message, for example from a call to window.postmessage() from another browsing context.
Worker.prototype.postMessage() - Web APIs
example the following code snippet shows the creation of a worker object using the worker() constructor.
... var myworker = new worker('worker.js'); first.onchange = function() { myworker.postmessage([first.value,second.value]); console.log('message posted to worker'); } second.onchange = function() { myworker.postmessage([first.value,second.value]); console.log('message posted to worker'); } for a full example, see ourbasic dedicated worker example (run dedicated worker).
... transfer example this example shows a firefox add-on that transfers an arraybuffer from the main thread to the chromeworker, and then the chromeworker transfers it back to the main thread.
...to see a full working example of this firefox demo add-on see here: github :: chromeworker - demo-transfer-arraybuffer specifications specification status comment html living standardthe definition of 'worker.postmessage()' in that specification.
WritableStream.WritableStream() - Web APIs
examples the following example illustrates several features of this interface.
...ild(listitem); result += decoded; resolve(); }); }, close() { var listitem = document.createelement('li'); listitem.textcontent = "[message received] " + result; list.appendchild(listitem); }, abort(err) { console.log("sink error:", err); } }, queuingstrategy); sendmessage("hello, world.", writablestream); you can find the full code in our simple writer example.
...in this example, it's the maximum amount of data that can be sent to defaultwriter.write() (line 11).
...this is why the example calls defaultwriter.ready twice (lines 9 and 22).
WritableStream - Web APIs
examples the following example illustrates several features of this interface.
...ild(listitem); result += decoded; resolve(); }); }, close() { var listitem = document.createelement('li'); listitem.textcontent = "[message received] " + result; list.appendchild(listitem); }, abort(err) { console.log("sink error:", err); } }, queuingstrategy); sendmessage("hello, world.", writablestream); you can find the full code in our simple writer example.
...in this example, it's the maximum amount of data that can be sent to defaultwriter.write() (line 11).
...this is why the example calls defaultwriter.ready twice (lines 9 and 22).
XPathResult.resultType - Web APIs
this is useful for example, in an xpath expression using the count() function.
...this is useful for example, in an xpath expression using the not() function.
... example the following example shows the use of the resulttype property.
... html <div>xpath example</div> <div>is xpath result a node set: <output></output></div> javascript var xpath = "//div"; var result = document.evaluate(xpath, document, null, xpathresult.any_type, null); document.queryselector("output").textcontent = result.resulttype >= xpathresult.unordered_node_iterator_type && result.resulttype <= xpathresult.first_ordered_node_type; result specifications specification status comment document object model (dom) level 3 xpath specificationthe definition of 'xpathresult.resulttype' in that specification.
XRSession - Web APIs
WebAPIXRSession
for example: for button or trigger actions, this means the button has been released; for spoken commands, it means the user has finished speaking.
...this indicates that the device being squeezed has been released, and may represent dropping a grabbed object, for example.
...this may be, for example, a trigger which is used to represent grabbing objects, or might represent actual squeezing when wearing a haptic glove.
... example this example establishes a new xrsession in inline mode so that it can be displayed within an html element, avoiding the need for a dedicated ar or vr viewing device such as a headset.
XRSystem: devicechange event - Web APIs
a devicechange event is fired on an xrsystem object whenever the whenever the availability of immersive xr devices has changed; for example, a vr headset or ar goggles have been connected or disconnected.
... you can use this event to, for example, monitor for the availability of a webxr-compatible device so that you can enable a ui element which the user can use to activate immersive mode.
... this is shown in the example below.
... example the example shown here handles the devicechange event by toggling the availability of the "enter xr" button based on whether or not any immersive devices are currently available.
XRViewerPose - Web APIs
each xrviewerpose can have multiple views to represent, for example, the slight separation between the left and right eye.
...for example, every player in a mmorpg might have an instance of xrviewerpose to provide a way to calculate what they can see; if the game provides a mechanism that tells the player if another player sees them, or that they see another player, this information becomes crucial.
... examples in this example—part of the code to render an xrframe, getviewerpose() is called to get an xrviewerpose using the same reference space the code is using as its base reference space.
... this code is derived from drawing a frame in movement, orientation, and motion: a webxr example.
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> </div> example 2: a close button in the example below, a link that functions as a 'close' button on a dialog is described elsewhere in the document.
... <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 article role - Accessibility
examples of an article include web log posts, newspaper or magazine articles and use-submitted comments.
... it is independent in that its contents could stand alone, for example in syndication.
... articles can be nested; for example, a web log entry on a site that accepts user-submitted comments could represent the comments as articles nested within the article for the web log entry.
... 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 ...
Using the log role - Accessibility
for example, chat logs, messaging history or an error log.
... 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="liveregion" class="region" role="log"></div> example 2: snippet from an example application this snippet creates the chat log in an ajax chat application.
... <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".
ARIA: application role - Accessibility
in a slides application, for example, a widget could be created that uses the arrow keys to position elements on the slide, and uses audio feedback via an aria live region to communicate the position and overlap status with other objects.
...the one exception is if focus is set to a standard widget inside the application that supports keyboard navigation from the browser, for example an input element.
... 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.
...if used, the application role should be added to the lowest common container possible, not on the <body> element, for example.
ARIA: article role - Accessibility
</div> this example shows two articles side by side on one page that could be structured similarly and are related.
...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.
... collapsible dropdown listbox example: single-select collapsible listbox that expands when activated, similar to html select with the attribute size="1".
... 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.
ARIA - Accessibility
for example, aria enables accessible navigation landmarks in html4, javascript widgets, form hints and error messages, live content updates, and more.
...in this example, the role="progressbar" attribute informs the browser that this element is actually a javascript-powered progress bar widget.
... 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).
Web accessibility for seizures and physical reactions - Accessibility
for example, "spinners" commonly used to display while pages load, can easily "flicker" while spinning.
...for example, the page for trace research & development center’s photosensitive epilepsy analysis tool notes that “photosensitive seizures can be provoked by certain types of flashing in web or computer content, including mouse-overs that cause large areas of the screen to rapidly flash on and off repeatedly.” other physical reactions nausea, vertigo (or dizziness), and disorientation are very nonspecific symptoms associated with all kinds of diseases and not particularly suggestive of seizures (except maybe disorientation, which is seen in seizures).
... @media screen and (prefers-reduced-motion: reduce) { } @media screen and (prefers-reduced-motion) { } to see a great example of how to use the code prefers-reduced-motion, visit the mdn document, prefers-reduced-motion, or see the example below from the section on new in chrome 74.
...for example, many users have difficulty reading text that has a small difference in contrast to the text background and would prefer a larger contrast." sometimes there can be such a thing as too much contrast; a halo effect around text can occur in such situations and actually reduce legibility.
::before (:before) - CSS: Cascading Style Sheets
WebCSS::before
examples adding quotation marks one simple example of using ::before pseudo-elements is to provide quotation marks.
... html <q>some quotes,</q> he said, <q>are better than none.</q> css q::before { content: "«"; color: blue; } q::after { content: "»"; color: red; } result decorative example we can style text or images in the content property almost any way we want.
... html <span class="ribbon">notice where the orange box is.</span> css .ribbon { background-color: #5bc8f7; } .ribbon::before { content: "look at this orange box."; background-color: #ffba10; border-color: black; border-style: dotted; } result to-do list in this example we will create a simple to-do list using pseudo-elements.
...color: #009933; border-style: solid; border-width: 0 0.3em 0.25em 0; height: 1em; top: 1.3em; left: 0.6em; margin-top: -1em; transform: rotate(45deg); width: 0.5em; } javascript var list = document.queryselector('ul'); list.addeventlistener('click', function(ev) { if (ev.target.tagname === 'li') { ev.target.classlist.toggle('done'); } }, false); here is the above code example running live.
:host-context() - CSS: Cascading Style Sheets
one typical use of this is with a descendant selector expression — for example h1 — to select only instances of the custom element that are inside an <h1>.
... another typical use would be to allow inner elements to react to classes or attributes on any anscestor elements - for example, applying a different text color when a .dark-theme class is applied to <body>.
...'='<attr-modifier> = i | s examples selectively styling shadow hosts the following snippets are taken from our host-selectors example (see it live also).
... in this example we have a simple custom element — <context-span> — that you can wrap around text: <h1>host selectors <a href="#"><context-span>example</context-span></a></h1> inside the element's constructor, we create style and span elements, fill the span with the content of the custom element, and fill the style element with some css rules: let style = document.createelement('style'); let span = document.createelement('span'); span.textcontent = this.textcontent; const shadowroot = this.attachshadow({mode: 'open'}); shadowroot.appendchild(style); shadowroot.appendchild(span); style.textcontent = 'span:hover { text-decoration: underline; }' + ':host-context(h1) { font-style: italic; }' + ':host-context(h1):after { content: " - no links in heade...
:is() (:matches(), :any()) - CSS: Cascading Style Sheets
WebCSS:is
'='<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 {...
...for example, the following css: /* 3-deep (or more) unordered lists use a square */ ol ol ul, ol ul ul, ol menu ul, ol dir ul, ol ol menu, ol ul menu, ol menu menu, ol dir menu, ol ol dir, ol ul dir, ol menu dir, ol dir dir, ul ol ul, ul ul ul, ul menu ul, ul dir ul, ul ol menu, ul ul menu, ul menu menu, ul dir menu, ul ol dir, ul ul dir, ul menu dir, ul...
... for example, without :is(), styling all the <h1> elements at different depths could be very complicated: /* level 0 */ h1 { font-size: 30px; } /* level 1 */ section h1, article h1, aside h1, nav h1 { font-size: 25px; } /* level 2 */ section section h1, section article h1, section aside h1, section nav h1, article section h1, article article h1, article aside h1, article nav h1, aside section h1, aside a...
...this is demonstrated by the example on the :where() reference page.
update - CSS: Cascading Style Sheets
example: documents printed on paper.
...examples: e-book readers or severely underpowered devices.
...example: computer screens.
... 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
WebCSS@media
for example, prefers-reduced-motion to detect if the user has requested that the system minimize the amount of animation or motion it uses.
...a browser might also offer additional measures in this area; for example, if firefox's "resist fingerprinting" setting is enabled, many media queries report default values rather than values representing the actual device state.
...<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 ...
...less 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.
Attribute selectors - CSS: Cascading Style Sheets
/* <a> elements with a title attribute */ a[title] { color: purple; } /* <a> elements with an href matching "https://example.org" */ a[href="https://example.org"] { color: green; } /* <a> elements with an href containing "example" */ a[href*="example"] { font-size: 2em; } /* <a> elements with an href ending ".org" */ a[href$=".org"] { font-style: italic; } /* <a> elements whose class attribute contains the word "logo" */ a[class~="logo"] { padding: 2px; } syntax [attr] represents elements with an attribute name of attr.
... 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 mat...
...ching capitalization */ a[href*="case" s] { color: pink; } /* links that end in ".org" */ a[href$=".org"] { color: red; } /* links that start with "https" and end in ".org" */ a[href^="https"][href$=".org"] { color: green; } html <ul> <li><a href="#internal">internal link</a></li> <li><a href="http://example.com">example link</a></li> <li><a href="#insensitive">insensitive internal link</a></li> <li><a href="http://example.org">example org link</a></li> <li><a href="https://example.org">example https org link</a></li> </ul> result languages css /* all divs with a `lang` attribute are bold.
...*/ ol[type="a"] { list-style-type: lower-alpha; background: red; } ol[type="a" s] { list-style-type: lower-alpha; background: lime; } ol[type="a" s] { list-style-type: upper-alpha; background: lime; } html <ol type="a"> <li>example list</li> </ol> result specifications specification status comment selectors level 4the definition of 'attribute selectors' in that specification.
Using URL values for the cursor property - CSS: Cascading Style Sheets
for example, the following value would be allowed: cursor: url(foo.cur), url(http://www.example.com/bar.gif), auto; this will first try loading foo.cur.
...an example of the css3 syntax is: .foo { cursor: auto; cursor: url(cursor1.png) 4 12, auto; } .bar { cursor: pointer; cursor: url(cursor2.png) 2 2, pointer; } /* falls back onto 'auto' and 'pointer' in ie, but must be set separately */ the first number is the x-coordinate, and the second number is the y-coordinate.
... the example will set the hotspot to be the pixel at (4,12) from the top left (0,0).
...javascript, css animation, and declarative smil inside an svg image are ignored; you can't use svg to create an animated cursor, for example.
CSS Containment - CSS: Cascading Style Sheets
basic example many webpages contain a number of sections which are independent of each other.
... for example a listing of article headlines and content, as in the mark-up below.
...for example, it might not render articles that are outside the viewable area.
... special values there are two special values of contain: content strict we encountered the first in the example above.
In Flow and Out of Flow - CSS: Cascading Style Sheets
in the following example i have a heading, paragraph, a list and a final paragraph which contains a strong element.
... floated items in this example i have a div, and then two paragraphs.
...in the next example i have three paragraph elements, the second element has position absolute, with offset values of top: 30px and right: 30px.
...the space that it would have been placed in normal flow is reserved however, as you can see in the example below.
Using the :target pseudo-class in selectors - CSS: Cascading Style Sheets
for example, the url http://developer.mozilla.org/en/docs/using_the_:target_selector#example contains the fragment identifier #example.
...thus, the example url would point to the heading "example" in this document.
...thus, to add a border to the #example fragment, we would write: #example:target { border: 1px solid black; } targeting all elements if the intent is to create a "blanket" style that will apply to all targeted elements, then the universal selector comes in handy: :target { color: red; } example in the following example, there are five links that point to elements in the same document.
... selecting the "first" link, for example, will cause <h1 id="one"> to become the target element.
Using CSS transforms - CSS: Cascading Style Sheets
examples here is an unaltered image of the mdn logo: rotating here is the mdn logo rotated 90 degrees from its bottom-left corner.
... setting perspective this example shows a cube with the perspective set at different positions.
... changing the perspective origin this example shows cubes with popular perspective-origin values.
...0% -200%;</code></caption> <div class="container"> <div class="cube po200200"> <div class="face front">1</div> <div class="face back">2</div> <div class="face right">3</div> <div class="face left">4</div> <div class="face top">5</div> <div class="face bottom">6</div> </div> </div> </figure> </section> css /* perspective-origin values (unique per example) */ .potl { perspective-origin: top left; } .potm { perspective-origin: top; } .potr { perspective-origin: top right; } .poml { perspective-origin: left; } .pomm { perspective-origin: 50% 50%; } .pomr { perspective-origin: right; } .pobl { perspective-origin: bottom left; } .pobm { perspective-origin: bottom; } .pobr { perspective-origin: bottom right; } .po200200neg { perspec...
Inline formatting context - CSS: Cascading Style Sheets
in the example below, the two (<div>) elements with the black borders form a block formatting context, inside which each word participates in an inline formatting context.
...in the next example there is a (<span>) element wrapping a set of words wrapping onto two lines.
...in the example below you can see how the margin, border, and padding on the inline <span> element are added.
...in the example below the large text is making the line box of the first sentence larger, therefore the vertical-align property can be used to align the inline boxes either side of it.
Cookbook template - CSS: Cascading Style Sheets
recipe change the path to the example below to point to your merged example.
... the last parameter is the live example height, which you can change as needed.
... download the example choices made explain your decisions when creating the pattern.
...if you want to add an additional example here — for example a version with fallbacks, please do.
Shorthand properties - CSS: Cascading Style Sheets
for example, the following css ...
...the live example below allows you to play with the css and see what happens when you make changes.
... for example: the second list item has the class my-class-1 applied.
... which of the links will change color if you define a new color for the <a> element — for example a { color: red; }?
align-content - CSS: Cascading Style Sheets
the interactive example below use grid layout to demonstrate some of the values of this property.
... the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...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; j...
align-items - CSS: Cascading Style Sheets
the interactive example below demonstrates some of the values for align-items using grid layout.
... the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...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; jus...
animation-delay - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...for example, if you specify -1s as the animation delay time, the animation will begin immediately but will start 1 second into the animation sequence.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...for example, an ease-in timing function becomes ease-out.
... 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-fill-mode - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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-iteration-count - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...you may specify non-integer values to play part of an animation cycle: for example, 0.5 will play half of the animation cycle.
... 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 - CSS: Cascading Style Sheets
WebCSSanimation
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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-image - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... if a specified image cannot be drawn (for example, when the file denoted by the specified uri cannot be loaded), browsers handle it as they would a none value.
...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.
border-bottom-style - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...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>...
... </table> css /* define look of the table */ table { border-width: 3px; background-color: #52e385; } tr, td { padding: 3px; } /* border-bottom-style example classes */ .b1 {border-bottom-style: none;} .b2 {border-bottom-style: hidden;} .b3 {border-bottom-style: dotted;} .b4 {border-bottom-style: dashed;} .b5 {border-bottom-style: solid;} .b6 {border-bottom-style: double;} .b7 {border-bottom-style: groove;} .b8 {border-bottom-style: ridge;} .b9 {border-bottom-style: inset;} .b10 {border-bottom-style: outset;} result specifications specification status comment css backgrounds and borders module level 3the definition of 'border-bottom-style' in that specification.
border-image-outset - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...for example, if an element has border-width: 1em 2px 0 1.5rem, and border-image-outset: 2, the final border-image-outset would be calculated as 2em 4px 0 3rem.
...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 backgrounds and borders module level 3the definition of 'border-image-o...
border-image-slice - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...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.
... the source image for the borders is as follows: the diamonds are 30px across, therefore setting 30 pixels as the value for both border-width and border-image-slice will get you complete and fairly crisp diamonds in your border: border-width: 30px; border-image-slice: 30; these are the default values we have used in this example.
border-left-style - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...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...
... the table */ table { border-width: 2px; background-color: #52e385; } tr, td { padding: 3px; } /* border-left-style example classes */ .b1 {border-left-style: none;} .b2 {border-left-style: hidden;} .b3 {border-left-style: dotted;} .b4 {border-left-style: dashed;} .b5 {border-left-style: solid;} .b6 {border-left-style: double;} .b7 {border-left-style: groove;} .b8 {border-left-style: ridge;} .b9 {border-left-style: inset;} .b10 {border-left-style: outset;} result specifications specification status comment css backgrounds and borders module level 3the definition of 'border-left-style' in that specification.
border-radius - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... for example: border-radius: 1em/5em; /* ...
...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: das...
border-right-style - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...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 /*...
... define look of the table */ table { border-width: 2px; background-color: #52e385; } tr, td { padding: 3px; } /* border-right-style example classes */ .b1 {border-right-style: none;} .b2 {border-right-style: hidden;} .b3 {border-right-style: dotted;} .b4 {border-right-style: dashed;} .b5 {border-right-style: solid;} .b6 {border-right-style: double;} .b7 {border-right-style: groove;} .b8 {border-right-style: ridge;} .b9 {border-right-style: inset;} .b10 {border-right-style: outset;} result specifications specification status comment css backgrounds and borders module level 3the definition of 'border-right-style' in that specification.
border-style - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...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.
... <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 the table */ table { border-width: 3px; background-color: #52e396; } tr, td { padding: 2px; } /* border-style example classes */ .b1 {border-style:none;} .b2 {border-style:hidden;} .b3 {border-style:dotted;} .b4 {border-style:dashed;} .b5 {border-style:solid;} .b6 {border-style:double;} .b7 {border-style:groove;} .b8 {border-style:ridge;} .b9 {border-style:inset;} .b10 {border-style:outset;} result specifications specification status comment css backgrounds and borders module lev...
border-top-style - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...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...
... the table */ table { border-width: 2px; background-color: #52e385; } tr, td { padding: 3px; } /* border-top-style example classes */ .b1 {border-top-style: none;} .b2 {border-top-style: hidden;} .b3 {border-top-style: dotted;} .b4 {border-top-style: dashed;} .b5 {border-top-style: solid;} .b6 {border-top-style: double;} .b7 {border-top-style: groove;} .b8 {border-top-style: ridge;} .b9 {border-top-style: inset;} .b10 {border-top-style: outset;} result specifications specification status comment css backgrounds and borders module level 3the definition of 'border-top-style' in that specification.
caret-color - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...for example, many browsers have a “navigation caret,” which acts similarly to an insertion caret but can be moved around in non-editable text.
...)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; } ...
clip-path - CSS: Cascading Style Sheets
WebCSSclip-path
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...| [ [ 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"> <...
...circle(25% at 25% 25%); } .shape9 { clip-path: content-box circle(25% at 25% 25%); } .defs { width: 0; height: 0; margin: 0; } pre { margin-bottom: 0; } svg { margin: 1em; font-family: sans-serif; width: 192px; height: 192px; } svg rect { stroke: pink; stroke-width: 16px; } svg text { fill: pink; text-anchor: middle; } svg text.em { font-style: italic; } complete example html <img id="clipped" src="https://udn.realityripple.com/samples/db/4f9fbd7dfb.svg" alt="mdn logo"> <svg height="0" width="0"> <defs> <clippath id="cross"> <rect y="110" x="137" width="90" height="90"/> <rect x="0" y="110" width="90" height="90"/> <rect x="137" y="0" width="90" height="90"/> <rect x="0" y="0" width="90" height="90"/> </clippath> </defs> ...
<easing-function> - CSS: Cascading Style Sheets
for example, a color component greater than 255 or smaller than 0 will be clipped to the closest allowed value (255 and 0, respectively).
... 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.
font-language-override - CSS: Cascading Style Sheets
for example, a lot of fonts have a special character for the digraph fi that merge the dot on the "i" with the "f." however, if the language is set to turkish the typeface will likely know not to use the merged glyph; turkish has two versions of the "i," one with a dot (i) and one without (ı), and using the ligature would incorrectly transform a dotted "i" into a dotless "i." the font-language-override pro...
...this is useful, for example, when the typeface you're using lacks proper support for the language.
...for example, "eng" is english, and "kor" is korean.
...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-language-override' in that specification.
font-style - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... for the example below to work, you'll need a browser that supports the css fonts level 4 syntax in which font-style: oblique can accept an <angle>.
... 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-sty...
font-variant-caps - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...for example: in turkic languages, such as turkish (tr), azerbaijani (az), crimean tatar (crh), volga tatar (tt), and bashkir (ba), there are two kinds of i (one with the dot, one without) and two case pairings: i/İ and ı/i.
...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 3t...
font-weight - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... for the example below to work, you'll need a browser that supports the css fonts level 4 syntax in which font-weight can be any number between 1 and 1000.
...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>...
gap (grid-gap) - CSS: Cascading Style Sheets
WebCSSgap
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...however, in order to support browsers that implemented grid-gap and not gap for grid, you will need to use the prefixed property as in the interactive example above.
... 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><...
justify-content - CSS: Cascading Style Sheets
the interactive example below demonstrates some of the values using grid layout.
... the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...[ <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</opt...
margin - CSS: Cascading Style Sheets
WebCSSmargin
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...for example, in certain cases this value can be used to center an element.
... 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; /* all sides: 10px margin */ margin: 1.6em 20px; /* top and bottom: 1.6em margin */ /* left and right: 20px margin */ margin: 10px 3% -1em; /* top: 10px margin */ /* left and right: 3% margin */ /* bottom: -1em margin...
max-block-size - CSS: Cascading Style Sheets
see the example in writing-mode, which shows the different writing modes in action.
... the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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.
min() - CSS: Cascading Style Sheets
WebCSSmin
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... in the first above example, the width will be at most 200px, but will be smaller if the viewport is less than 400px wide (in which case 1vw would be 4px, so 50vw would be 200px).
... 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.
opacity - CSS: Cascading Style Sheets
WebCSSopacity
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...for example: background: rgba(0, 0, 0, 0.4); accessibility concerns if text opacity is adjusted, it is important to ensure that the contrast ratio between the color of the text and the background the text is placed over is high enough that people experiencing low vision conditions will be able to read the content of the page.
... 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: ...
overflow - CSS: Cascading Style Sheets
WebCSSoverflow
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...the content can be scrolled programmatically (for example, by setting the value of a property such as offsetleft), so the element is still a scroll container.
...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.
perspective-origin - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...| [ [ 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.
...-200%;</code></figcaption> <div class="container"> <div class="cube po200200"> <div class="face front">1</div> <div class="face back">2</div> <div class="face right">3</div> <div class="face left">4</div> <div class="face top">5</div> <div class="face bottom">6</div> </div> </div> </figure> </section> css /* perspective-origin values (unique per example) */ .potl { perspective-origin: top left; } .potm { perspective-origin: top; } .potr { perspective-origin: top right; } .poml { perspective-origin: left; } .pomm { perspective-origin: 50% 50%; } .pomr { perspective-origin: right; } .pobl { perspective-origin: bottom left; } .pobm { perspective-origin: bottom; } .pobr { perspective-origin: bottom right; } .po200200neg { perspec...
quotes - CSS: Cascading Style Sheets
WebCSSquotes
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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.
... that's the question!</q> css q { quotes: '"' '"' "'" "'"; } q::before { content: open-quote; } q::after { content: close-quote; } result auto quotes for most browsers, the default value of quotes is auto (firefox 70+), or the browser otherwise had this default behavior (chromiums, safari, edge), so this example works without it being explicitly being set.
radial-gradient() - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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-cor...
...ner at 40px 40px, #f35 0%, #43e 100%); } more radial-gradient examples please see using css gradients for more examples.
repeating-linear-gradient() - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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 { widt...
... note: please see using css gradients for more examples.
repeating-radial-gradient() - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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-gradien...
... note: please see using css gradients for more examples.
resize - CSS: Cascading Style Sheets
WebCSSresize
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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.
...in the example below, a resizable <div> contains a resizable paragraph (<p> element).
revert - CSS: Cascading Style Sheets
WebCSSrevert
for example, the initial value for the display property is inline, whereas a normal user-agent stylesheet sets the default display value of <div>s to block, of <table>s to table, etc.
... examples revert vs unset although revert and unset are similar they differ for some properties for some elements.
... so in the below example, we set custom font-weight in a global stylesheet, but then try to unset and revert.
...so to iterate on above example instead of reverting font-weight and color separately you could just revert all of them.
right - CSS: Cascading Style Sheets
WebCSSright
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...if the element cannot stretch to satisfy both -- for example, if a width is declared -- the position of the element is over-constrained.
... 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; rig...
row-gap (grid-row-gap) - CSS: Cascading Style Sheets
WebCSSrow-gap
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...however, in order to support browsers that implemented grid-row-gap and not row-gap for grid, you will need to use the prefixed property as in the interactive example above.
...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...
shape-image-threshold - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...for example, a value of 0.5 means that the shape will enclose all the pixels that are more than 50% opaque.
... 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.
text-decoration-color - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...for example, change of text and text-decoration-color alone is not enough to indicate a link has focus.
...)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 def...
text-decoration - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...for example, in the markup <p>this text has <em>some emphasized words</em> in it.</p>, the style rule p { text-decoration: underline; } would cause the entire paragraph to be underlined.
...-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 ...
text-overflow - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...for example: overflow: hidden; white-space: nowrap; the text-overflow property only affects content that is overflowing a block container element in its inline progression direction (not text overflowing at the bottom of a box, for example).
... 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 comp...
text-transform - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... in irish (ga), certain prefixed letters remain in lowercase when the base initial is capitalized, so for example text-transform: uppercase will change ar aon tslí to ar aon tslÍ and not, as one might expect, ar aon tslÍ (firefox only).
...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.
scaleZ() - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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 ...
translateZ() - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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.
<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.
... html <main> <section id="example-element"> <div class="face front">1</div> <div class="face back">2</div> <div class="face right">3</div> <div class="face left">4</div> <div class="face top">5</div> <div class="face bottom">6</div> </section> <div class="select-form"> <label>select a transform function</label> <select> <option selected>choose a function</option> <option>rotate(360deg)</option> <option>rotatex(360deg)</option> <option>rotatey(360deg)</option> <option>rotatez(360deg...
...atez(100px)</option> <option>translate3d(50px, 50px, 50px)</option> <option>perspective(200px)</option> <option>matrix(1, 2, -1, 1, 80, 80)</option> <option>matrix3d(1,0,0,0,0,1,3,0,0,0,1,0,50,100,0,1.1)</option> </select> </div> </main> css main { width: 400px; height: 200px; padding: 50px; background-image: linear-gradient(135deg, white, cyan, white); } #example-element { width: 100px; height: 100px; transform-style: preserve-3d; transition: transform 1.5s; transform: rotate3d(1, 1, 1, 30deg); } .face { display: flex; align-items: center; justify-content: center; width: 100%; height: 100%; position: absolute; backface-visibility: inherit; font-size: 60px; color: #fff; } .front { background: rgba(90,90,90,.7); transfo...
...slatez(50px); } .left { background: rgba(0,0,210,.7); transform: rotatey(-90deg) translatez(50px); } .top { background: rgba(210,210,0,.7); transform: rotatex(90deg) translatez(50px); } .bottom { background: rgba(210,0,210,.7); transform: rotatex(-90deg) translatez(50px); } .select-form { margin-top: 50px; } javascript const selectelem = document.queryselector('select'); const example = document.queryselector('#example-element'); selectelem.addeventlistener('change', () => { if(selectelem.value === 'choose a function') { return; } else { example.style.transform = `rotate3d(1, 1, 1, 30deg) ${selectelem.value}`; settimeout(function() { example.style.transform = 'rotate3d(1, 1, 1, 30deg)'; }, 2000) } }) result specifications specificatio...
transform-origin - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...for example, the transformation origin of the rotate() function is the center of rotation.
... 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">&nbsp;</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">&nbsp;</div> .box2 { margin: 0.5em; width: 3em;...
var() - CSS: Cascading Style Sheets
WebCSSvar
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...for example, var(--foo, red, blue) defines a fallback of red, blue; that is, anything between the first comma and the end of the function is considered a fallback value.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...for example, it could be used to vertically position an <img> in a line of text: <p> top:<img style="vertical-align:top" src="https://udn.realityripple.com/samples/16/ed9c61c3b6.png"/> middle:<img style="vertical-align:middle" src="https://udn.realityripple.com/samples/16/ed9c61c3b6.png"/> bottom:<img style="vertical-align:bottom" src="https://udn.realityripple.com/samples/16/ed9c61c3b6.png"/> super:<img style="vertical-align:super" src="https://udn.realityripple.com/samples/16/ed9c61c3b6.png"/> sub:<img style="vertical-align:sub" src="https://udn.realityripple.com/samples/16/ed9c61c3b6.png"/> </p> <p> text-top:<img style="vertical-align:text-top" src="https...
...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/...
visibility - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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.
... notice the second paragraph is still occupying space.</p> css .visible { visibility: visible; } .not-visible { visibility: hidden; } table example html <table> <tr> <td>1.1</td> <td class="collapse">1.2</td> <td>1.3</td> </tr> <tr class="collapse"> <td>2.1</td> <td>2.2</td> <td>2.3</td> </tr> <tr> <td>3.1</td> <td>3.2</td> <td>3.3</td> </tr> </table> css .collapse { visibility: collapse; } table { border: 1px solid red; } td { border: 1px solid gray; } specifications specification status comment css flexible box layout modulethe definition of 'visibility' in that specification.
Video player styling basics - Developer guides
the example in action you can find the code for the updated, styled example on github, and view it live.
... preliminary modifications from the original example this section summarises the modifications that were made to the original video player example to make the styling task easier, before the bulk of the work was started.
... note: in some cases some basic css is omitted from the code examples here as its use is either obvious or not specifically relevant to styling the video player.
... for example, the play/pause button has the following background image definitions (the full base64 strings have been omitted for brevity): .controls button[data-state="play"] { background-image: url('data:image/png;base64,ivborw0kggoaaa ...
Web Audio playbackRate explained - Developer guides
playbackrate basics let's starting by looking at a brief example of playbackrate usage: var myaudio = document.createelement('audio'); myaudio.setattribute('src','audiofile.mp3'); myaudio.playbackrate = 0.5; here we create an <audio> element, and set its src to a file of our choice.
... next we set playbackrate to 0.5, which represents half normal speed (the playbackrate is a multiplier applied to the original rate.) a complete example let's create a <video> element first, and set up video and playback rate controls in html: <video id="myvideo" controls> <source src="https://udn.realityripple.com/samples/6f/08625b424a.m4v" type='video/mp4' /> <source src="https://udn.realityripple.com/samples/5b/8cd6da9c65.webm" type='video/webm' /> </video> <form> <input id="pbr" type="range" value="1" min="0.5" max="4" step="0.1" > <p>playback rate <span id="currentpbr">1</span></p> </form> and apply some javascript to it: window.onload = function () { var v = document.getelementbyid("myvideo"); var p = document.getelementbyid("pbr"); var c = document.getelementbyid("curr...
... note: try out this example live, and try adjusting the playback rate control to see the effect.
... defaultplaybackrate and ratechange in addition to playbackrate, we also have a defaultplaybackrate property available, which lets us set the default playback rate: the playback rate to which the media resets; for example, if we change the source of the video, or (in some browsers) when an ended event is generated.
Writing Web Audio API code that works in every browser - Developer guides
for example, the way to create instances of gainnode used to be var gain = audiocontext.creategainnode(); but nowadays it is just var gain = audiocontext.creategain(); since the old method names are not present in firefox, existing code may crash with something like creategainnode is not a function, and you now know why.
...if it's using, for example, oscillatornode, you will have to wait until it is supported, or maybe, if you're really eager, hack in some replacement using scriptprocessornode, which allows you to write a node with callbacks that get called periodically, so that your javascript code generates or processes audio.
...for example, up until a couple of days ago pannernode did not support the default hrtf panning model yet, and attempting to use a pannernode with that configuration simply resulted in silence or a mono output coming out from that node, depending on the build you used.
...if you're a person that learns by example, it might be interesting to have a look at their source and see how they have resolved the compatibility issues.
DOM onevent handlers - Developer guides
for example, given a button object mybutton, you can do mybutton.onclick(myeventobject) to call the event handler directly.
...for example, for the progress event on instances of xmlhttprequest: const xhr = new xmlhttprequest(); xhr.onprogress = function() { … }; html onevent attributes html elements have attributes named onevent which can be used to register a handler for an event directly within the html code.
...for example: if ("onsomenewfeature" in window) { /* do something amazing */ } event handlers and prototypes you can't set or access the values of any idl-defined attributes on dom prototype objects.
... that means you can't, for example, change window.prototype.onload.
Localizations and character encodings - Developer guides
to specify that a page is using, for example, the utf-8 character encoding (as per the recommendation), simply place the following line in the <head> block: <meta charset="utf-8"> details and browser internals when the encoding is declared by web content like the html specification requires, firefox will use that encoding for turning the bytes into the internal representation.
...(for example, the fallback encoding for the polish, hungarian and czech locales should probably continue to be iso-8859-2 even though ie has a different fallback encoding.) when in doubt, use windows-1252 as the fallback encoding.
...for example, for a localization for minority language in russia, it is appropriate to copy the settings from the russian localization.
...for example, the fallback encoding for japanese is shift_jis, but there are other legacy encodings: iso-2022-jp and euc-jp.
Printing - Developer guides
examples here are some common examples.
... open and automatically close a popup window when finished if you want to be able to automatically close a popup window (for example, the printer-friendly version of a document) after the user prints its contents, you can use code like this: <!doctype html> <html> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <title>javascript window close example </title> <script type="text/javascript"> function popuponclick() { my_window = window.open('', 'mywindow', 'status=1,width=350,height=150'); my_window.document.write('<html><head><title>print me</title></head>'); my_window.document.write('<body onafterprint="self.close()">'); my_window.document.write('<p>when you print this window, it will close afterward.</p>'); my_window.document.
...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 following is a possible example which will print a file named externalpage.html: <!doctype html> <html> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <title>mdn example</title> <script type="text/javascript"> function closeprint () { document.body.removechild(this.__container__); } function setprint () { this.contentwindow.__container__ = this; this.contentwindow.onbeforeunload = closeprint; this.contentwindow.onafterprint = closeprint; this.contentwindow.focus(); // required for ie this.contentwindow.print(); } function printpage (surl) { var ohiddframe = document.createelement("iframe"); ohiddframe.onload = setprint; ohiddframe.style.position = "fixed"; ohiddframe.style.right = "0"; ohiddframe.style.bottom = "0"; ohiddframe.style.wi...
disabled - HTML: Hypertext Markup Language
if this attribute is not specified, the control inherits its setting from the containing element, for example fieldset; if there is no containing element with the disabled attribute set, and the control itself does not have the attribute, then the control is enabled.
...if this attribute isn't set, the button can still be disabled from a containing element, for example <fieldset>; if there is no containing element with the disabled attribute set, then the button is enabled.
... 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
WebHTMLElementa
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...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...
... using the download attribute to save a <canvas> as a png to save a <canvas> element’s contents as an image, you can create a link with a download attribute and the canvas data as a data: url: example painting app with save link html <p>paint by holding down the mouse button and moving it.
<b>: The Bring Attention To element - HTML: Hypertext Markup Language
WebHTMLElementb
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... it is a good practice to use the class attribute on the <b> element in order to convey additional semantic information as needed (for example <b class="lead"> for the first sentence in a paragraph).
... examples <p> this article describes several <b class="keywords">text-level</b> elements.
<bdo>: The Bidirectional Text Override element - HTML: Hypertext Markup Language
WebHTMLElementbdo
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... the text's characters are drawn from the starting point in the given direction; the individual characters' orientation is not affected (so characters don't get drawn backward, for example).
... 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.
<big>: The Bigger Text element - HTML: Hypertext Markup Language
WebHTMLElementbig
the obsolete html big element (<big>) renders the enclosed text at a font size one level larger than the surrounding text (medium becomes large, for example).
... examples here we see examples showing the use of <big> followed by an example showing how to accomplish the same results using modern css syntax instead.
... using <big> this example uses the obsolete <big> element to increase the size of some text.
...<big>this whole sentence is in bigger letters.</big> </p> result using css font-size this example uses the css font-size property to increase the font size by one level.
<br>: The Line Break element - HTML: Hypertext Markup Language
WebHTMLElementbr
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... as you can see from the above example, a <br> element is included at each point where we want the text to break.
... 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.
<button>: The Button element - HTML: Hypertext Markup Language
WebHTMLElementbutton
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... example <button name="button">press me</button> accessibility concerns icon buttons buttons that only show an icon to represent do not have an accessible name.
... example <button name="favorite"> <svg aria-hidden="true" viewbox="0 0 10 10"><path d="m7 9l5 8 3 9v6l1 4h3l1-3 1 3h3l7 6z"/></svg> add to favorites </button> if you want to visually hide the button's text, an accessible way to do so is to use a combination of css properties to remove it visually from the screen, but keep it parseable by assistive technology.
<caption>: The Table Caption element - HTML: Hypertext Markup Language
WebHTMLElementcaption
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... example this simple example presents a table that includes a caption.
... <table> <caption>example caption</caption> <tr> <th>login</th> <th>email</th> </tr> <tr> <td>user1</td> <td>user1@sample.com</td> </tr> <tr> <td>user2</td> <td>user2@sample.com</td> </tr> </table> caption { caption-side: top; align: right; } table { border-collapse: collapse; border-spacing: 0px; } table, th, td { border: 1px solid black; } table {background: red;} do not alter caption.
<cite>: The Citation element - HTML: Hypertext Markup Language
WebHTMLElementcite
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... usage notes in the context of the <cite> element, a creative work that might be cited could be, for example, one of the following: a book a research paper an essay a poem a musical score a song a play or film script a film a television show a game a sculpture a painting a theatrical production a play an opera a musical an exhibition a legal case report a computer program a web site a web page a blog post or comment a forum post or comment a tweet a facebook post a written o...
... example <p>more information can be found in <cite>[iso-0000]</cite>.</p> the html above outputs: specifications specification status comment html living standardthe definition of '<cite>' in that specification.
<div>: The Content Division element - HTML: Hypertext Markup Language
WebHTMLElementdiv
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... examples a simple example <div> <p>any kind of content here.
...you name it!</p> </div> the result looks like this: a styled example this example creates a shadowed box by applying a style to the <div> using css.
<dl>: The Description List element - HTML: Hypertext Markup Language
WebHTMLElementdl
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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.
<figure>: The Figure with Optional Caption element - HTML: Hypertext Markup Language
WebHTMLElementfigure
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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...
... details using <code>navigator</code>.</figcaption> <pre> function navigatorexample() { var txt; txt = "browser codename: " + navigator.appcodename + "; "; txt+= "browser name: " + navigator.appname + "; "; txt+= "browser version: " + navigator.appversion + "; "; txt+= "cookies enabled: " + navigator.cookieenabled + "; "; txt+= "platform: " + navigator.platform + "; "; txt+= "user-agent header: " + navigator.useragent + "; "; console.log("navigatorexample", txt); } </pre> </figure> quotations <figure> <figcaption><cite>edsger dijkstra:</cite></figcaption> <blockquote>if debugging is the process of removing software bugs, then programming must be the process of putting them in.</blockquote> </figure> poems <figure> <p style="white-space:pre"> bid me discour...
<form> - HTML: Hypertext Markup Language
WebHTMLElementform
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...in html5, it is a name/keyword for a browsing context (for example, tab, window, or iframe).
... 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 ...
<hgroup> - HTML: Hypertext Markup Language
WebHTMLElementhgroup
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...there are a variety of ways an <hgroup> might be shown in a rendered outline; for example: an <hgroup> might be shown in a rendered outline in with a colon character and space (“: ”) or other such punctuation after the primary heading and before the first secondary heading (and with the same or similar punctuation before any other secondary headings an <hgroup> might be shown in a rendered outline in with the primary heading followed by parentheses around the secondary heading...
... 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.
<hr>: The Thematic Break (Horizontal Rule) element - HTML: Hypertext Markup Language
WebHTMLElementhr
the html <hr> element represents a thematic break between paragraph-level elements: for example, a change of scene in a story, or a shift of topic within a section.
... the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... example html <p> this is the first paragraph of text.
<label> - HTML: Hypertext Markup Language
WebHTMLElementlabel
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...this means that, for example, a screenreader will read out the label when the user is focused on the form input, making it easier for an assistive technology user to understand what data should be entered.
... 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.
<meter>: The HTML Meter element - HTML: Hypertext Markup Language
WebHTMLElementmeter
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...for example, if it is between the min attribute and the low attribute, then the lower range is considered preferred.
... 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.
<picture>: The Picture element - HTML: Hypertext Markup Language
WebHTMLElementpicture
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...cropping or modifying images for different media conditions (for example, loading a simpler version of an image which has too many details, on smaller displays).
... examples these examples demonstrate how different attributes of the <source> element change the selection of the image inside <picture>.
<pre>: The Preformatted Text element - HTML: Hypertext Markup Language
WebHTMLElementpre
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... example html <p>using css to change the font color is easy.</p> <pre> body { color: red; } </pre> result accessibility concerns it is important to provide an alternate description for any images or diagrams created using preformatted text.
... example <figure role="img" aria-labelledby="cow-caption"> <pre> ___________________________ < i'm an expert in my field.
<rp>: The Ruby Fallback Parenthesis element - HTML: Hypertext Markup Language
WebHTMLElementrp
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
WebHTMLElementrt
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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 specifica...
<section>: The Generic Section element - HTML: Hypertext Markup Language
WebHTMLElementsection
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... as an example, a navigation menu should be wrapped in a <nav> element, but a list of search results and a map display and its controls don't have specific elements, and could be put inside a <section>.
... example before <div> <h1>heading</h1> <p>bunch of awesome content</p> </div> after <section> <h1>heading</h1> <p>bunch of awesome content</p> </section> specifications specification status comment html living standardthe definition of '<section>' in that specification.
<style>: The Style Information element - HTML: Hypertext Markup Language
WebHTMLElementstyle
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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 ov...
... <!doctype html> <html> <head> <style> p { color: white; background-color: blue; padding: 5px; border: 1px solid black; } </style> <style> p { color: blue; background-color: yellow; } </style> </head> <body> <p>this is my paragraph.</p> </body> </html> including a media query in this example we build on the previous one, including a media attribute on the second <style> element so it is only applied when the viewport is less than 500px in width.
<table>: The Table element - HTML: Hypertext Markup Language
WebHTMLElementtable
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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 tbo...
... example <table> <caption>color names and values</caption> <tbody> <tr> <th scope="col">name</th> <th scope="col">hex</th> <th scope="col">hsla</th> <th scope="col">rgba</th> </tr> <tr> <th scope="row">teal</th> <td><code>#51f6f6</code></td> <td><code>hsla(180, 90%, 64%, 1)</code></td> <td><code>rgba(81, 246, 246, 1)</code></td> </tr> ...
<time> - HTML: Hypertext Markup Language
WebHTMLElementtime
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...for example, this can help a user agent offer to add an event to a user's calendar.
...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.
<u>: The Unarticulated Annotation (Underline) element - HTML: Hypertext Markup Language
WebHTMLElementu
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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.
<var>: The Variable element - HTML: Hypertext Markup Language
WebHTMLElementvar
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...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.
...in this example, variable names are rendered using bold courier if it's available, otherwise it falls back to the default monospace font.
<wbr> - HTML: Hypertext Markup Language
WebHTMLElementwbr
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... example the yahoo style guide recommends breaking a url before punctuation, to avoid leaving a punctuation mark at the end of the line, which the reader might mistake for the end of the url.
... <p>http://this<wbr>.is<wbr>.a<wbr>.really<wbr>.long<wbr>.example<wbr>.com/with<wbr>/deeper<wbr>/level<wbr>/pages<wbr>/deeper<wbr>/level<wbr>/pages<wbr>/deeper<wbr>/level<wbr>/pages<wbr>/deeper<wbr>/level<wbr>/pages<wbr>/deeper<wbr>/level<wbr>/pages</p> specifications specification status comment html living standardthe definition of '<wbr>' in that specification.
hidden - HTML: Hypertext Markup Language
for example, it can be used to hide elements of the page that can't be used until the login process has been completed.
... the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... for example, it would be incorrect to use the href attribute to link to a section marked with the hidden attribute.
Inline elements - HTML: Hypertext Markup Language
block-level elements: a demonstration this is most easily demonstrated with a simple example.
... first, some simple css that we'll be using: .highlight { background-color:#ee3; } inline let's look at the following example which demonstrates an inline element: <div>the following span is an <span class="highlight">inline element</span>; its background has been colored to display both the beginning and end of the inline element's influence.</div> in this example, the <div> block-level element contains some text.
...for example, by changing the value of display from "inline" to "block", you can tell the browser to render the inline element in a block box rather than an inline box, and vice versa.
...for example, even if the display of the span element is changed to "block", it still would not allow to nest a div element inside it.
Choosing between www and non-www URLs - HTTP
for example, if you've chosen to use non-www urls as the canonical type, you should redirect all www urls to their equivalent url without the www.
... example: a server receives a request for http://www.example.org/whaddup (when the canonical domain is example.org) the server answers with a code 301 with the header location: http://example.org/whaddup.
... the client issues a request to the canonical domain: http://example.org/whatddup the html5 boilerplate project has an example on how to configure an apache server to redirect one domain to the other.
...in the previous example, http://www.example.org/whaddup would serve the same content as http://example.org/whaddup, but with an additional <link> element in the head: <link href="http://example.org/whaddup" rel="canonical"> unlike the previous case, browser history will consider non-www and www urls as independent entries.
Identifying resources on the Web - HTTP
a more complex example might look like this: http://www.example.com:80/path/to/myfile.html?key1=value1&key2=value2#somewhereinthedocument urns a uniform resource name (urn) is a uri that identifies a resource by name in a particular namespace.
... transfer protocol http/https hyper text transfer protocol (secure) javascript url-embedded javascript code mailto electronic mail address ssh secure shell tel telephone urn uniform resource names view-source source code of the resource ws/wss (encrypted) websocket connections authority www.example.com is the domain name or authority that governs the namespace.
...on an html document, for example, the browser will scroll to the point where the anchor is defined; on a video or audio document, the browser will try to go to the time the anchor represents.
... 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 ...
Resource URLs - HTTP
syntax resource urls are composed of two parts: a prefix (resource:), and a url pointing to the resource you want to load: resource://<url> an example: resource://gre/res/svg.css when arrows are found in the resource url's ('->'), it means that the first file loaded the next one: resource://<file-loader> -> <file-loaded> please refer to identifying resources on the web for more general details.
... for example, a script on browserleaks highlights what firefox reveals when queried by a simple script running on the site (you can find the code in https://browserleaks.com/firefox#more).
...for example: http://searchfox.org/mozilla-central/rev/48ea452803907f2575d81021e8678634e8067fc2/browser/app/profile/firefox.js#575 web sites can easily collect firefox default preferences by overriding this pref() function and using the script resource:///defaults/preferences/firefox.js.
... for example, if you open the view source page (view page source or view selection source), you will find it requires viewsource.css through a resource: uri.
HTTP caching - HTTP
WebHTTPCaching
for example, an isp or your company might have set up a web proxy as part of its local network infrastructure to serve many users so that popular resources are reused a number of times, reducing network traffic and latency.
...this includes static files such as images, css files and javascript files, for example.
... here is an example of this process with a shared cache proxy: the freshness lifetime is calculated based on several headers.
... this can be useful for serving content dynamically, for example.
Feature-Policy: fullscreen - HTTP
<origin(s)>: the feature is allowed for specific origins (for example, https://example.com).
... examples general example securecorp inc.
... wants to disable the fullscreen api within all browsing contexts except for its own origin and those whose origin is https://example.com.
... it can do so by delivering the following http response header to define a feature policy: feature-policy: fullscreen 'self' https://example.com with an <iframe> element fastcorp inc.
Feature-Policy: geolocation - HTTP
<origin(s)>: the feature is allowed for specific origins (for example, https://example.com).
... examples general example securecorp inc.
... wants to disable the geolocation api within all browsing contexts except for its own origin and those whose origin is https://example.com.
... it can do so by delivering the following http response header to define a feature policy: feature-policy: geolocation 'self' https://example.com with an <iframe> element fastcorp inc.
Large-Allocation - HTTP
for complex games, for example, these allocations can be quite large, sometimes as large as 1gb.
... the large-allocation tells the browser that the web content in the to-be-loaded page is going to want to perform a large contiguous memory allocation and the browser can react to this header by starting a dedicated process for the to-be-loaded document, for example.
... examples large-allocation: 0 large-allocation: 500 troubleshooting errors the large-allocation header throws warnings or error messages when used incorrectly.
...this could be caused due to the document being loaded by a form submission, for example.
Strict-Transport-Security - HTTP
description if a website accepts a connection through http and redirects to https, visitors may initially communicate with the non-encrypted version of the site before being redirected, if, for example, the visitor types http://www.foo.com/ or even just foo.com.
... an example scenario you log into a free wifi access point at an airport and start surfing the web, visiting your online banking service to check your balance and pay a couple of bills.
... 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.
... strict-transport-security: max-age=31536000; includesubdomains in the following example, max-age is set to 2 years, raised from what was a former limit max-age of 1 year.
Firefox user agent string reference - HTTP
see below for further details and examples.
...for example: mozilla/5.0 (android 4.4; mobile; rv:41.0) gecko/41.0 firefox/41.0 mozilla/5.0 (android 4.4; tablet; rv:41.0) gecko/41.0 firefox/41.0 the version numbers are not relevant.
... firefox os devices identify themselves without any operating system indication; for example: "mozilla/5.0 (mobile; rv:15.0) gecko/15.0 firefox/15.0".
...a few common examples are given below.
Protocol upgrade mechanism - HTTP
this means that a typical request that includes upgrade would look something like: get /index.html http/1.1 host: www.example.com connection: upgrade upgrade: example/1, foo/2 other headers may be required depending on the requested protocol; for example, websocket upgrades allow additional headers to configure details about the websocket connection as well as to offer a degree of security in opening the connection.
...if it does not (or cannot) upgrade the connection, it ignores the upgrade header and sends back a regular response (for example, a 200 ok).
...for example, opening a websocket connection is as simple as: websocket = new websocket("ws://destination.server.ext", "optionalprotocol"); the websocket() constructor does all the work of creating an initial http/1.1 connection then handling the handshaking and upgrade process for you.
... for example: sec-websocket-extensions: superspeed, colormode; depth=16 sec-websocket-key provides information to the server which is needed in order to confirm that the client is entitled to request an upgrade to websocket.
HTTP range requests - HTTP
partial requests are useful for large media or downloading files with pause and resume functions, for example.
...you can check this by issuing a head request with curl, for example.
... curl http://www.example.com -i -h "range: bytes=0-50, 100-150" the server responses with the 206 partial content status and a content-type: multipart/byteranges; boundary=3d6b6a416f9b5 header, indicating that a multipart byterange follows.
... http/1.1 206 partial content content-type: multipart/byteranges; boundary=3d6b6a416f9b5 content-length: 282 --3d6b6a416f9b5 content-type: text/html content-range: bytes 0-50/1270 <!doctype html> <html> <head> <title>example do --3d6b6a416f9b5 content-type: text/html content-range: bytes 100-150/1270 eta http-equiv="content-type" content="text/html; c --3d6b6a416f9b5-- conditional range requests when resuming to request more parts of a resource, you need to guarantee that the stored resource has not been modified since the last fragment has been received.
A typical HTTP session - HTTP
WebHTTPSession
sending a client request once the connection is established, the user-agent can send the request (a user-agent is typically a web browser, but can be anything else, a crawler, for example).
... example requests fetching the root page of developer.mozilla.org, i.e.
... for example, sending the result of a form: post /contact_form.php http/1.1 host: developer.mozilla.org content-length: 64 content-type: application/x-www-form-urlencoded name=joe%20user&request=send%20me%20one%20of%20your%20catalogue request methods http defines a set of request methods indicating the desired action to be performed upon a resource.
... example responses successful web page response: http/1.1 200 ok content-type: text/html; charset=utf-8 content-length: 55743 connection: keep-alive cache-control: s-maxage=300, public, max-age=0 content-language: en-us date: thu, 06 dec 2018 17:37:18 gmt etag: "2e77ad1dc6ab0b53a2996dfd4653c1c3" server: meinheld/0.6.1 strict-transport-security: max-age=63072000 x-content-type-options: nosniff x-frame-op...
Equality comparisons and sameness - JavaScript
the second is that floating point includes the concept of a not-a-number value, nan, to represent the solution to certain ill-defined mathematical problems: negative infinity added to positive infinity, for example.
...for example, someone might say that double equals is an extended version of triple equals, because the former does everything that the latter does, but with type conversion on its operands.
...for example, using math.pow to raise -infinity to the power of any negative, odd exponent evaluates to -0.
...for example: var f2b = x => new uint8array(new float64array([x]).buffer); var b2f = x => new float64array(x.buffer)[0]; var n = f2b(nan); n[0] = 1; var nan2 = b2f(n); nan2; // > nan object.is(nan2, nan); // > true f2b(nan); // > uint8array(8) [0, 0, 0, 0, 0, 0, 248,127) f2b(nan2); // > uint8array(8) [1, 0, 0, 0, 0, 0, 248,127) ...
Introduction - JavaScript
inside a host environment (for example, a web browser), javascript can be connected to the objects of its environment to provide programmatic control over them.
...core javascript can be extended for a variety of purposes by supplementing it with additional objects; for example: client-side javascript extends the core language by supplying objects to control a browser and its document object model (dom).
... for example, client-side extensions allow an application to place elements on an html form and respond to user events such as mouse clicks, form input, and page navigation.
...for example, server-side extensions allow an application to communicate with a database, provide continuity of information from one invocation to another of the application, or perform file manipulations on a server.
Iterators and generators - JavaScript
here is an example which can do just that.
... we can now adapt the example from above.
... function* makeiterator() { yield 1; yield 2; } const it = makeiterator(); for (const ititem of it) { console.log(ititem); } console.log(it[symbol.iterator]() === it) // true; // this example show us generator(iterator) is iterable object, // which has the @@iterator method return the it (itself), // and consequently, the it object can iterate only _once_.
...for example: the for-of loops, yield*.
Meta programming - JavaScript
for example, getting a property on an object: let handler = { get: function(target, name) { return name in target?
... additional examples are available on the proxy reference page.
...see the reference pages for detailed explanations and examples.
... with reflect.has() for example, you get the in operator as a function: reflect.has(object, 'assign') // true a better apply function in es5, you typically use the function.prototype.apply() method to call a function with a given this value and arguments provided as an array (or an array-like object).
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.
... for example, a belongs to the latin script and ε to the greek script.
...as shown in this example, it might be a bit clumsy to work with non latin texts.
TypeError: "x" is not a function - JavaScript
for example, javascript objects have no map function, but the javascript array object does.
...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 an...
...in this example, array.prototype.map() is used, which will work with array objects only.
... an example helpers library (helpers.js) let helpers = function () { }; helpers.groupby = function (objectarray, property) { return objectarray.reduce(function (acc, obj) { var key = obj[property]; if (!acc[key]) { acc[key] = []; } acc[key].push(obj); return acc; }, {}); } export default helpers; the correct import usage (app.js): import helpers from './helpers' ...
Array.prototype.reduce() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... it is almost always safer to provide an initialvalue, because there can be up to four possible output types without initialvalue, as shown in the following example: let maxcallback = ( acc, cur ) => math.max( acc.x, cur.x ); let maxcallback2 = ( max, cur ) => math.max( max, cur ); // reduce without initialvalue [ { x: 2 }, { x: 22 }, { x: 42 } ].reduce( maxcallback ); // nan [ { x: 2 }, { x: 22 } ].reduce( maxcallback ); // 22 [ { x: 2 } ].reduce( maxcallback ); // { x: 2 } [ ].reduce( maxcal...
... 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 object...
Array.prototype.reduceRight() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... some example run-throughs of the function would look like this: [0, 1, 2, 3, 4].reduceright(function(accumulator, currentvalue, index, array) { return accumulator + currentvalue; }); the callback would be invoked four times, with the arguments and return values in each call being as follows: callback accumulator currentvalue index array return value first call 4 ...
...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 ...
Array.prototype.every() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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.find() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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: 'ap...
...ples', quantity: 2}, {name: 'bananas', quantity: 0}, {name: 'cherries', quantity: 5} ]; const result = inventory.find( ({ name }) => name === 'cherries' ); console.log(result) // { name: 'cherries', quantity: 5 } find a prime number in an array the following example finds an element in the 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 ...
Array.prototype.findIndex() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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.
... function isprime(num) { for (let i = 2; num > i; i++) { if (num % i == 0) { return false; } } return num > 1; } console.log([4, 6, 8, 9, 12].findindex(isprime)); // -1, not found console.log([4, 6, 7, 9, 12].findindex(isprime)); // 2 (array[2] is 7) find index using arrow function the following example finds the index of a fruit using an arrow function: const fruits = ["apple", "banana", "cantaloupe", "blueberries", "grapefruit"]; const index = fruits.findindex(fruit => fruit === "blueberries"); console.log(index); // 3 console.log(fruits[index]); // blueberries specifications specification ecmascript (ecma-262)the definition of 'array.prototype.findindex' in that specification.
Array.prototype.includes() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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.
... the example below illustrates includes() method called on the function's arguments object.
Array.prototype.join() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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.
... var a = ['wind', 'water', 'fire']; a.join(); // 'wind,water,fire' a.join(', '); // 'wind, water, fire' a.join(' + '); // 'wind + water + fire' a.join(''); // 'windwaterfire' joining an array-like object the following example joins array-like object (arguments), by calling function.prototype.call on array.prototype.join.
Array.prototype.lastIndexOf() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... examples using lastindexof the following example uses lastindexof to locate values in an array.
... var numbers = [2, 5, 9, 2]; numbers.lastindexof(2); // 3 numbers.lastindexof(7); // -1 numbers.lastindexof(2, 3); // 3 numbers.lastindexof(2, 2); // 0 numbers.lastindexof(2, -2); // 0 numbers.lastindexof(2, -1); // 3 finding all the occurrences of an element the following example uses lastindexof to find all the indices of an element in a given array, using push to add them to another array as they are found.
Array.prototype.reverse() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... examples reversing the elements in an array the following example creates an array a, containing three elements, then reverses the array.
... const a = [1, 2, 3]; console.log(a); // [1, 2, 3] a.reverse(); console.log(a); // [3, 2, 1] reversing the elements in an array-like object the following example creates an array-like object a, containing three elements and a length property, then reverses the array-like object.
Array.prototype.shift() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... examples removing an element from an array the following code displays the myfish array before and after removing its first element.
...in the following example every iteration will remove the next element from an array, until it is empty: var names = ["andrew", "edward", "paul", "chris" ,"john"]; while( (i = names.shift()) !== undefined ) { console.log(i); } // andrew, edward, paul, chris, john specifications specification ecmascript (ecma-262)the definition of 'array.prototype.shift' in that specification.
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.
...for example, slice(1,4) extracts the second element through the fourth element (elements indexed 1, 2, and 3).
... 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.
...the arguments inside a function is an example of an 'array-like object'.
Atomics.and() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...the truth table for the and operation is: a b a & b 0 0 0 0 1 0 1 0 0 1 1 1 for example, a bitwise and of 5 & 1 results in 0001 which is 1 in decimal.
... 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.or() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...the truth table for the or operation is: a b a | b 0 0 0 0 1 1 1 0 1 1 1 1 for example, a bitwise or of 5 & 1 results in 0101 which is 5 in decimal.
... 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.xor() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...the truth table for the xor operation is: a b a ^ b 0 0 0 0 1 1 1 0 1 1 1 0 for example, a bitwise xor of 5 ^ 1 results in 0100 which is 4 in decimal.
... 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.prototype.toLocaleString() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... examples using tolocalestring in basic use without specifying a locale, a formatted string in the default locale and with default options is returned.
...english locale using locales this example shows some of the variations in localized number formats.
BigInt.prototype.toString() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...for example, for hexadecimal numbers (base 16) a through f are used.
... 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.
DataView() constructor - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... for example, if the buffer is 16 bytes long, the byteoffset is 8, and the bytelength is 10, this error is thrown because the resulting view tries to extend 2 bytes past the total length of the buffer.
... 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.
Date() constructor - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...see the example below.
... 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.prototype.getDay() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... examples using getday() the second statement below assigns the value 1 to weekday, based on the value of the date object xmas95.
... var xmas95 = new date('december 25, 1995 23:15:30'); var weekday = xmas95.getday(); console.log(weekday); // 1 note: if needed, the full name of a day ("monday" for example) can be obtained by using intl.datetimeformat with an options parameter.
Date.prototype.getFullYear() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...for dates between the years 1000 and 9999, getfullyear() returns a four-digit number, for example, 1995.
... examples using getfullyear() the following example assigns the four-digit value of the current year to the variable year.
Date.prototype.getMonth() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... examples using getmonth() the second statement below assigns the value 11 to the variable month, based on the value of the date object xmas95.
... var xmas95 = new date('december 25, 1995 23:15:30'); var month = xmas95.getmonth(); console.log(month); // 11 note: if needed, the full name of a month ("january" for example) can be obtained by using intl.datetimeformat() with an options parameter.
Date.prototype.getTime() - JavaScript
for example, a client browser in one timezone, gettime() will be the same as a client browser in any other timezone.
... the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... examples using gettime() for copying dates constructing a date object with the identical time value.
Date.prototype.getTimezoneOffset() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...for example, for time zone utc+10:00 (australian eastern standard time, vladivostok time, chamorro standard time), -600 will be returned.
... 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 = labourday.gettimezoneoffset() / 60; spe...
Date.prototype.getUTCFullYear() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... description the value returned by getutcfullyear() is an absolute number that is compliant with year-2000, for example, 1995.
... examples using getutcfullyear() the following example assigns the four-digit value of the current year to the variable year.
Date.prototype.setDate() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... for example, if 0 is provided for dayvalue, the date will be set to the last day of the previous month.
... 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.setdate(-50); // 1962-08-11 (11th of august 1962) specifications specification ecmascript (ecma-262)the definition of 'date.prototype.setdate' in that specificati...
Date.prototype.setHours() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...for example, if you use 100 for secondsvalue, the minutes will be incremented by 1 (minutesvalue + 1), and 40 will be used for seconds.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...for example, if you specify 1005, the number of seconds is incremented by 1, and 5 is used for the milliseconds.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...for example, if you use 100 for secondsvalue, the minutes will be incremented by 1 (minutesvalue + 1), and 40 will be used for seconds.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...for example, if you use 100 for secondsvalue, the minutes stored in the date object will be incremented by 1, and 40 will be used for seconds.
... 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.setUTCDate() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...for example, if you use 40 for dayvalue, and the month stored in the date object is june, the day will be changed to 10 and the month will be incremented to july.
... 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.setUTCHours() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...for example, if you use 100 for secondsvalue, the minutes will be incremented by 1 (minutesvalue + 1), and 40 will be used for seconds.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...for example, if you use 1100 for millisecondsvalue, the seconds stored in the date object will be incremented by 1, and 100 will be used for milliseconds.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...for example, if you use 100 for secondsvalue, the minutes will be incremented by 1 (minutesvalue + 1), and 40 will be used for seconds.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...for example, if you use 15 for monthvalue, the year will be incremented by 1, and 3 will be used for month.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...for example, if you use 100 for secondsvalue, the minutes stored in the date object will be incremented by 1, and 40 will be used for seconds.
... 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.toLocaleDateString() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... examples using tolocaledatestring() in basic use without specifying a locale, a formatted string in the default locale and with default options is returned.
...to check whether an implementation supports them already, you can use the requirement that illegal language tags are rejected with a rangeerror exception: function tolocaledatestringsupportslocales() { try { new date().tolocaledatestring('i'); } catch (e) { return e.name === 'rangeerror'; } return false; } using locales this example shows some of the variations in localized date formats.
Date.prototype.toLocaleTimeString() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... examples using tolocaletimestring() in basic use without specifying a locale, a formatted string in the default locale and with default options is returned.
...to check whether an implementation supports them already, you can use the requirement that illegal language tags are rejected with a rangeerror exception: function tolocaletimestringsupportslocales() { try { new date().tolocaletimestring('i'); } catch (e) { return e​.name === 'rangeerror'; } return false; } using locales this example shows some of the variations in localized time formats.
Intl.DateTimeFormat() constructor - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...unicode extension are supported (for example "en-us-u-ca-buddhist").
... examples using datetimeformat in basic use without specifying a locale, datetimeformat uses the default locale and default options.
Intl.DateTimeFormat.prototype.format() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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.DateTimeFormat - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... examples using datetimeformat in basic use without specifying a locale, datetimeformat uses the default locale and default options.
... var date = new date(date.utc(2012, 11, 20, 3, 0, 0)); // tolocalestring without arguments depends on the implementation, // the default locale, and the default time zone console.log(new intl.datetimeformat().format(date)); // → "12/19/2012" if run with en-us locale (language) and time zone america/los_angeles (utc-0800) using locales this example shows some of the variations in localized date and time formats.
Intl.ListFormat - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... examples using format the following example shows how to create a list formatter using the english language.
...e.log(new intl.listformat('en-gb', { style: 'long', type: 'conjunction' }).format(list)); // > motorcycle, bus and car console.log(new intl.listformat('en-gb', { style: 'short', type: 'disjunction' }).format(list)); // > motorcycle, bus or car console.log(new intl.listformat('en-gb', { style: 'narrow', type: 'unit' }).format(list)); // > motorcycle bus car using formattoparts the following example shows how to create a list formatter returning formatted parts const list = ['motorcycle', 'bus', 'car']; console.log(new intl.listformat('en-gb', { style: 'long', type: 'conjunction' }).formattoparts(list)); // [ { "type": "element", "value": "motorcycle" }, // { "type": "literal", "value": ", " }, // { "type": "element", "value": "bus" }, // { "type": "literal", "value": ", and " }, // ...
Intl.Locale.prototype.maximize() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...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.
Intl.NumberFormat - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... examples basic usage in basic use without specifying a locale, a formatted string in the default locale and with default options is returned.
... var number = 3500; console.log(new intl.numberformat().format(number)); // → '3,500' if in us english locale using locales this example shows some of the variations in localized number formats.
Intl.RelativeTimeFormat - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... examples basic format usage the following example shows how to use a relative time formatter for the english language.
...rtf.format(1, "day"); // > "in 1 day" using formattoparts the following example shows how to create a relative time formatter returning formatted parts const rtf = new intl.relativetimeformat("en", { numeric: "auto" }); // format relative time using the day unit.
Intl - JavaScript
for example: "hi": hindi (language) "de-at": german (language) as used in austria (region) "zh-hans-cn": chinese (language) written in simplified characters (script) as used in china (region) "en-emodeng": english (language) in the "early modern english" dialect (variant) the subtags identifying languages, scripts, regions (including countries), and (rarely used) variants in unicode bcp 47 locale ide...
...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.
...for example, the "co" key (collation) is only supported by collator, and its "phonebk" value is only supported for german.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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.
...if the reviver function returns undefined (or returns no value, for example, if execution falls off the end of the function), the property is deleted from the object.
Math.fround() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...however, sometimes you may be working with 32-bit floating-point numbers, for example if you are reading values from a float32array.
... 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; // f...
Math.hypot() - JavaScript
the math.hypot() function returns the square root of the sum of squares of its arguments, that is: math.hypot(v1,v2,…,vn)=∑i=1nvi2=v12+v22+…+vn2\mathtt{\operatorname{math.hypot}(v_1, v_2, \dots, v_n)} = \sqrt{\sum_{i=1}^n v_i^2} = \sqrt{v_1^2 + v_2^2 + \dots + v_n^2} the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...for example, math.sqrt(1e200*1e200 + 1e200*1e200) = infinity .
...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.log() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... if you need a logarithm to other bases, use math.log(x) / math.log(otherbase) as in the example below; you might want to precalculate 1 / math.log(otherbase) .
... 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.
Number.MAX_SAFE_INTEGER - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...for example, number.max_safe_integer + 1 === number.max_safe_integer + 2 will evaluate to true, which is mathematically incorrect.
... 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.isSafeInteger() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... for example, 253 - 1 is a safe integer: it can be exactly represented, and no other integer rounds to it under any ieee-754 rounding mode.
... 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.
Number.parseFloat() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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.
Number.prototype.toLocaleString() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... examples using tolocalestring in basic use without specifying a locale, a formatted string in the default locale and with default options is returned.
... using locales this example shows some of the variations in localized number formats.
Number.prototype.toString() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...for example, for hexadecimal numbers (base 16), a through f are used.
... 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 '-11111...
Object.assign() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... in case of an error, for example if a property is non-writable, a typeerror is raised, and the target object is changed if any properties are added before the error is raised.
...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.freeze() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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.
...the following example shows that a frozen object is not constant (freeze is shallow).
Object.prototype.hasOwnProperty() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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.
... inherited properties the following example differentiates between direct properties and properties inherited through the prototype chain: o = new object(); o.prop = 'exists'; o.hasownproperty('prop'); // returns true o.hasownproperty('tostring'); // returns false o.hasownproperty('hasownproperty'); // returns false iterating over the properties of an object the following example shows how to iterate over the properties of an object without executing on inherited properties.
Object.prototype.isPrototypeOf() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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.l...
... for example, check if baz object descends from foo.prototype: if (foo.prototype.isprototypeof(baz)) { // do something safe } specifications specification ecmascript (ecma-262)the definition of 'object.prototype.isprototypeof' in that specification.
Object.prototype.propertyIsEnumerable() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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.
... built-in objects the following example demonstrates the enumerability of user-defined vs.
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 o...
...for example, this (untested) code will pre-conditionally execute custom logic before the built-in logic or someone else's extension is executed.
...for example, in the call myfn(a, b, c), the arguments within myfn's body will contain 3 array-like elements corresponding to (a, b, c).
...for example: var person = function(name) { this.name = name; this.cantalk = true; }; person.prototype.greet = function() { if (this.cantalk) { console.log('hi, i am ' + this.name); } }; var employee = function(name, title) { person.call(this, name); this.title = title; }; employee.prototype = object.create(person.prototype); employee.prototype.constructor = employee; //if you don't set ob...
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.
... following, an example to demonstrate the asynchronicity of the then method.
... 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!
...in the following example, the first then() will return 42 wrapped in a resolving promise even though the previous promise in the chain was rejected.
handler.set() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... for example: suppose a script does obj.name = "jen", and obj is not a proxy, and has no own property .name, but it has a proxy on its prototype chain.
... examples trap setting of a property value the following code traps setting a property value.
handler.setPrototypeOf() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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.
... for example, object.setprototypeof() will create and throw a typeerror itself.
Reflect.construct() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...gs, otherclass) // ...has the same result as this: let obj2 = object.create(otherclass.prototype) oneclass.apply(obj2, args) console.log(obj1.name) // 'one' console.log(obj2.name) // 'one' console.log(obj1 instanceof oneclass) // false console.log(obj2 instanceof oneclass) // false console.log(obj1 instanceof otherclass) // true console.log(obj2 instanceof otherclass) // true //another example to demonstrate below: function func1(a, b, c, d) { console.log(arguments[3]); } function func2(d, e, f, g) { consol.log(arguments[3]); } let obj1 = reflect.construct(func1, ['i', 'love', 'my', 'india']) obj1 however, while the end result is the same, there is one important difference in the process.
...} 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.
RegExp.prototype[@@match]() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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[@@replace]() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...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.multiline - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...for example, if "m" is used, "^" and "$" change from matching at only the start or end of the entire string to the start or end of any line within the string.
... 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.sticky - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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 ^ asserti...
... 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 specifica...
RegExp.prototype.unicode - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...with the "u" flag, any unicode code point escapes will be interpreted as such, for example.
... 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.
SharedArrayBuffer.prototype.slice() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... for example, slice(1,4) extracts the second element through the fourth element (elements indexed 1, 2, and 3).
... examples using slice var sab = new sharedarraybuffer(1024); sab.slice(); // sharedarraybuffer { bytelength: 1024 } sab.slice(2); // sharedarraybuffer { bytelength: 1022 } sab.slice(-2); // sharedarraybuffer { bytelength: 2 } sab.slice(0, 1); // sharedarraybuffer { bytelength: 1 } specifications specification ecmascript (ecma-262)the definition of 'sharedarraybuffer.prototype.slice' in that specification.
String.prototype.charAt() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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) + "'"); conso...
...t(i - 1) // (could change last hex to 0xdb7f to treat high private surrogates // as single characters) if (0xd800 > prev || prev > 0xdbff) { throw 'low surrogate without preceding high surrogate' } // return the next character instead (and increment) return [str.charat(i + 1), i + 1] } fixing charat() to support non-basic-multilingual-plane (bmp) characters while the previous example may be more useful for programs that must support non-bmp characters (since it does not require the caller to know where any non-bmp character might appear), in the event that one does wish, in choosing a character by index, to treat the surrogate pairs within a string as the single characters they represent, one can use the following: function fixedcharat(str, idx) { let ret = '' str += '' ...
String.prototype.charCodeAt() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...see examples 2 and 3 (below).
... examples using charcodeat() the following example returns 65, the unicode value for a.
String.prototype.includes() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...for example, the following expression returns false: 'blue whale'.includes('blue') // returns false polyfill this method has been added to the ecmascript 2015 specification and may not be available in all javascript implementations yet.
... 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 specification ec...
String.prototype.match() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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.
... using global and ignore case flags with match() the following example demonstrates the use of the global and ignore case flags with match().
String.prototype.toUpperCase() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... exceptions typeerror when called on null or undefined, for example, string.prototype.touppercase.call(undefined).
... 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); // prints out 'abcdef true'.
Symbol() constructor - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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.
...bol each time: symbol('foo') === symbol('foo') // false new symbol(...) the following syntax with the new operator will throw a typeerror: let sym = new symbol() // typeerror this prevents authors from creating an explicit symbol wrapper object instead of a new symbol value and might be surprising as creating explicit wrapper objects around primitive data types is generally possible (for example, new boolean, new string and new number).
Symbol.prototype.description - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...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.isConcatSpreadable - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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] numer...
...in the above example, length:2 indicates two properties has to be added.
Symbol.match - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...for example, the methods string.prototype.startswith(), string.prototype.endswith() and string.prototype.includes(), check if their first argument is a regular expression and will throw a typeerror if they are.
... 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.matchAll - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...the 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.
Symbol.species - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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.
... for example, when using methods such as map() that return the default constructor, you want these methods to return a parent array object, instead of the myarray object.
Symbol.toStringTag - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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]" // ...
...for example, to acccess the symbol.tostringtag property on htmlbuttonelement: let test = document.createelement('button'); test.tostring(); // returns [object htmlbuttonelement] test[symbol.tostringtag]; // returns htmlbuttonelement specifications specification ecmascript (ecma-262)the definition of 'symbol.tostringtag' in that specification.
TypedArray.prototype.slice() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... for example, slice(1,4) extracts the second element through the fourth element (elements indexed 1, 2, and 3).
... 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.toString() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... examples the typedarray objects override the tostring method of object.
...for example, the following code creates a typed array and uses tostring to convert the array to a string.
WebAssembly.instantiate() - JavaScript
examples note: you'll probably want to use webassembly.instantiatestreaming() in most cases, as it is more efficient than instantiate().
... first overload example after fetching some webassembly bytecode using fetch, we compile and instantiate the module using the webassembly.instantiate() function, importing a javascript function into the webassembly module in the process.
... var importobject = { imports: { imported_func: function(arg) { console.log(arg); } } }; fetch('simple.wasm').then(response => response.arraybuffer() ).then(bytes => webassembly.instantiate(bytes, importobject) ).then(result => result.instance.exports.exported_func() ); note: you can also find this example at index.html on github (view it live also).
... second overload example the following example (see our index-compile.html demo on github, and view it live also) compiles the loaded simple.wasm byte code using the webassembly.compilestreaming() method and then sends it to a worker using postmessage().
encodeURIComponent() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... for example, if a user writes "jack & jill", the text may get encoded as "jack &amp; jill".
... 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 "con...
globalThis - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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')().
... however, this causes csp violations in some settings, so es6-shim uses a check like this, for example: var getglobal = function () { if (typeof self !== 'undefined') { return self; } if (typeof window !== 'undefined') { return window; } if (typeof global !== 'undefined') { return global; } throw new error('unable to locate global object'); }; var globals = getglobal(); if (typeof globals.settimeout !== 'function') { // no settimeout in this environment!
isNaN() - JavaScript
for example, dividing zero by zero results in a nan — but dividing other numbers by zero does not.
...thus for non-numbers that when coerced to numeric type result in a valid non-nan numeric value (notably the empty string and boolean primitives, which when coerced give numeric values zero or one), the "false" returned value may be unexpected; the empty string, for example, is surely "not a number." the confusion stems from the fact that the term, "not a number", has a specific meaning for numbers represented as ieee-754 floating-point values.
... 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: parse...
... you can use this, for example, to test whether an argument to a function is arithmetically processable (usable "like" a number), or if it's not and you have to provide a default value or something else.
parseFloat() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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 fol...
...lowing 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.
Lexical grammar - JavaScript
only the following unicode code points are treated as line terminators in ecmascript, other line breaking characters are treated as white space (for example, next line, nel, u+0085 is considered as white space).
...for example: function comment() { // this is a one line javascript comment console.log('hello world!'); } comment(); the second way is the /* */ style, which is much more flexible.
... for example, you can use it on a single line: function comment() { /* this is a one line javascript comment */ console.log('hello world!'); } comment(); you can also make multiple-line comments, like this: function comment() { /* this comment spans multiple lines.
...an example is as follows: #!/usr/bin/env node console.log("hello world"); note: hashbang comments in javascript mimic shebangs in unix used to run files with proper interpreter.
Bitwise AND (&) - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...for example, the following integer with more than 32 bits will be converted to a 32 bit integer: before: 11100110111110100000000000000110000000000001 after: 10100000000000000110000000000001 each bit in the first operand is paired with the corresponding bit in the second operand: first bit to first bit, second bit to second bit, and so on.
... 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 OR (|) - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...for example, the following integer with more than 32 bits will be converted to a 32 bit integer: before: 11100110111110100000000000000110000000000001 after: 10100000000000000110000000000001 each bit in the first operand is paired with the corresponding bit in the second operand: first bit to first bit, second bit to second bit, and so on.
... 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 XOR (^) - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...for example, the following integer with more than 32 bits will be converted to a 32 bit integer: before: 11100110111110100000000000000110000000000001 after: 10100000000000000110000000000001 each bit in the first operand is paired with the corresponding bit in the second operand: first bit to first bit, second bit to second bit, and so on.
... 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.
Equality (==) - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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 operat...
...ello"); const string3 = new string("hello"); const string4 = new string("hello"); console.log(string1 == string2); // true console.log(string1 == string3); // true console.log(string2 == string3); // true console.log(string3 == string4); // false console.log(string4 == string4); // true comparing dates and strings const d = new date('december 17, 1995 03:24:00'); const s = d.tostring(); // for example: "sun dec 17 1995 03:24:00 gmt-0800 (pacific standard time)" console.log(d == s); //true specifications specification ecmascript (ecma-262)the definition of 'equality operators' in that specification.
Exponentiation (**) - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...for example, in bash, the ** operator is defined to have a lower precedence than unary operators.
... 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 ...
Left shift (<<) - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... for example, 9 << 2 yields 36: .
... 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.
Logical NOT (!) - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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 !
Object initializer - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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.
Right shift (>>) - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... for example, 9 >> 2 yields 2: .
... -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.
in operator - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... examples basic usage the following examples show some uses of the in operator.
...for example, you can specify a string created with the string constructor, but you cannot specify a string literal.
instanceof - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...for instance, you can securely check if a given object is, in fact, an array using array.isarray(myobj) for example, checking if a nodes is a svgelement in a different context, you can use mynode instanceof mynode.ownerdocument.defaultview.svgelement.
... 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.
...for example, the statement car1.color = "black" adds a property color to car1, and assigns it a value of "black".
... examples object type and object instance suppose you want to create an object type for cars.
...for example: var kenscar = new car('nissan', '300zx', 1992); object property that is itself another object suppose you define an object called person as follows: function person(name, age, sex) { this.name = name; this.age = age; this.sex = sex; } and then instantiate two new person objects as follows: var rand = new person('rand mcnally', 33, 'm'); var ken = new person('ken jones', 39, 'm'); ...
block - JavaScript
the block is delimited by a pair of braces ("curly brackets") and may optionally be labelled: the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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.
...for example: var x = 1; { var x = 2; } console.log(x); // logs 2 this logs 2 because the var x statement within the block is in the same scope as the var x statement before the block.
break - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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.
continue - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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.
... var i = 0; var n = 0; while (i < 5) { i++; if (i === 3) { continue; } n += i; } using continue with a label in the following example, a statement labeled checkiandj contains a statement labeled checkj.
return - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...for example, the following function returns the square of its argument, x, where x is a number.
... 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.
var - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...the 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.
... the same example as above but with a strict mode: 'use strict'; var x = 0; function f() { var x = y = 1; // throws a referenceerror in strict mode.
with - JavaScript
so given this example: function f(x, o) { with (o) { console.log(x); } } only when f is called is x either found or not, and if found, either in o or (if no such property exists) in f's activation object, where x names the first formal argument.
...consider this example: function f(foo, values) { with (foo) { console.log(values); } } if you call f([1,2,3], obj) in an ecmascript 5 environment, then the values reference inside the with statement will resolve to obj.
...however, in this particular example, array.prototype has been defined with values in its symbol.unscopables object.
... examples using with the following with statement specifies that the math object is the default object.
Template literals (Template strings) - JavaScript
(alternatively, it can return something completely different, as described in one of the following examples.) the name of the function used for the tag can be whatever you want.
... let person = 'mike'; let age = 28; function mytag(strings, personexp, ageexp) { let str0 = strings[0]; // "that " let str1 = strings[1]; // " is a " // there is technically a string after // the final expression (in our example), // but it is empty (""), so disregard.
... let str = string.raw`hi\n${2+3}!`; // "hi\n5!" str.length; // 6 array.from(str).join(','); // "h,i,\,n,5,!" tagged templates and escape sequences es2016 behavior as of ecmascript 2016, tagged templates conform to the rules of the following escape sequences: unicode escapes started by "\u", for example \u00a9 unicode code point escapes indicated by "\u{}", for example \u{2f804} hexadecimal escapes started by "\x", for example \xa9 octal literal escapes started by "\0o" and followed by one or more digits, for example \0o251 this means that a tagged template like the following is problematic, because, per ecmascript grammar, a parser looks for valid unicode escape sequences, but finds malfor...
...med syntax: latex`\unicode` // throws in older ecmascript versions (es2016 and earlier) // syntaxerror: malformed unicode character escape sequence es2018 revision of illegal escape sequences tagged templates should allow the embedding of languages (for example dsls, or latex), where other escapes sequences are common.
Digital video concepts - Web media technologies
in bt.709 (used for hdtv), for example, the luma value is the weighted sum of the gamma-corrected red, green, and blue components of the pixel, using the formula y' = 0.2126r' + 0.7152g' + 0.0722b'.
... the table below shows examples of three chroma subsampling models.
... the final example demonstrates 4:4:4 subsampling.
...for example, in the av1 codec, a record stores the encoded luma for a tile, and a second record contains the chroma data in the form of the u and v values.
Optimizing startup performance - Web Performance
instead, you should write your code so that your app creates a web worker that does as much as possible in a background thread (for example, fetching and processing data.) then, anything that must be done on the main thread (such as user events and rendering ui) should be broken up into small pieces so that the app's event loop continues to cycle while it starts up.
... if you need to decode asset files (for example, decoding jpeg files and turning them into raw texture data for later use by webgl), that's great to do in workers.
... when dealing with data supported by the browser (for example, decoding image data), use the decoders built into the browser or device rather than rolling your own or using one from the original codebase.
... emscripten provides an api to help with this refactoring; for example, you can use emscripten_push_main_loop_blocker() to establish a function to be executed before the main thread is allowed to continue.
end - SVG: Scalable Vector Graphics
WebSVGAttributeend
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" widt...
...6s</text> <line x1="85" y1="25" x2="85" y2="105" stroke="grey" stroke-width=".5" /> <text x="110" y="20" text-anchor="middle">8s</text> <line x1="110" y1="25" x2="110" y2="105" stroke="grey" stroke-width=".5" /> <line x1="10" y1="30" x2="110" y2="30" stroke="grey" stroke-width=".5" /> <line x1="10" y1="105" x2="110" y2="105" stroke="grey" stroke-width=".5" /> </svg> event example <svg width="120" height="120" viewbox="0 0 120 120" xmlns="http://www.w3.org/2000/svg" version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink"> <!-- animated rectangle --> <rect x="10" y="35" height="15" width="0"> <animate attributetype="xml" attributename="width" from="0" to="100" begin="0s" end="endbutton.click" dur="8s" repeatcou...
...6s</text> <line x1="85" y1="25" x2="85" y2="55" stroke="grey" stroke-width=".5" /> <text x="110" y="20" text-anchor="middle">8s</text> <line x1="110" y1="25" x2="110" y2="55" stroke="grey" stroke-width=".5" /> <line x1="10" y1="30" x2="110" y2="30" stroke="grey" stroke-width=".5" /> <line x1="10" y1="55" x2="110" y2="55" stroke="grey" stroke-width=".5" /> </svg> accesskey example <svg width="120" height="120" viewbox="0 0 120 120" xmlns="http://www.w3.org/2000/svg" version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink"> <!-- animated rectangles --> <rect x="10" y="35" height="15" width="0"> <animate attributetype="xml" attributename="width" from="0" to="100" begin="0s" end="accesskey(e)" dur="8s" repeatcount...
...dle">6s</text> <line x1="85" y1="25" x2="85" y2="55" stroke="grey" stroke-width=".5" /> <text x="110" y="20" text-anchor="middle">8s</text> <line x1="110" y1="25" x2="110" y2="55" stroke="grey" stroke-width=".5" /> <line x1="10" y1="30" x2="110" y2="30" stroke="grey" stroke-width=".5" /> <line x1="10" y1="55" x2="110" y2="55" stroke="grey" stroke-width=".5" /> </svg> this example is embed in an iframe.
Mixed content - Web security
for example, an attacker could replace an image served over http with an inappropriate image or message to the user.
...malicious active content can steal the user's credentials, acquire sensitive data about the user, or attempt to install malware on the user's system (by leveraging vulnerabilities in the browser or its plugins, for example).
... 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.
Subdomain takeovers - Web security
suppose you control the domain example.com.
... you want to add a blog at blog.example.com, and you decide to use a hosting provider who maintains a blogging platform.
... (for "blog", you can substitute "e-commerce platform", "customer service platform", or any other "cloud-based" virtual hosting scenario.) the process you go through might look like this: you register the name "blog.example.com" with a domain registrar.
... you set up dns records to direct browsers that want to access blog.example.com so that they go to the virtual host.
An Overview - XSLT: Extensible Stylesheet Language Transformations
thus a full example of the opening stylesheet element might look like this.
...the examples in this article all assume the use of the xsl prefix.
...there are certain constraints on which type of nodes can occur where: for example, text nodes can have no children.
...for example, if the stylesheet is called inventory.xsl and resides in the same directory as the xml document, the processing instruction in the xml document would look like this: <?xml-stylesheet type="text/xml" href="inventory.xsl"?> this must be placed in the prolog section of the xml document.
Exported WebAssembly functions - WebAssembly
when you call them, you get some activity in the background to convert the arguments into types that wasm can work with (for example converting javascript numbers to int32), the arguments are passed to the function inside your wasm module, the function is invoked, and the result is converted and passed back to javascript.
... an example let's look at an example to clear things up (you can find this on github as table-set.html; see it running live also, and check out the wasm text representation): var othertable = new webassembly.table({ element: "anyfunc", initial: 2 }); webassembly.instantiatestreaming(fetch('table.wasm')) .then(obj => { var tbl = obj.instance.exports.tbl; console.log(tbl.get(0)()); // 13 console.log(...
... they are real functions in the previous example, the return value of each table.prototype.get() call is an exported webassembly function — exactly what we have been talking about.
...if you load the above example in a webassembly-supporting browser, and run the following lines in your console: var testfunc = othertable.get(0); typeof testfunc; you'll get the result function returned.
port - Archive of obsolete content
this example rewrites the content script in the port.removelistener() example so that it uses once(): // content-script.js function getfirstparagraph() { var paras = document.getelementsbytagname('p'); console.log(paras[0].textcontent); } self.port.once("get-first-para", getfirstparagraph); removelistener() you can use port.on() to listen for messages.
... for example, here's an add-on that creates a page-worker and a button.
... for example, to include an array of strings in the payload: // main.js var pagemods = require("sdk/page-mod"); var self = require("sdk/self"); var pagemod = pagemods.pagemod({ include: ['*'], contentscriptfile: self.data.url("content-script.js"), onattach: setuplistener }); function setuplistener(worker) { worker.port.on('loaded', function(pageinfo) { console.log(pageinfo[0]); console.log...
Testing the Add-on SDK - Archive of obsolete content
cfx testex --filter <addon_example_folder_name>: a suite of tests which run test code for some example add-ons.
... this suite builds the example code, then runs these example add-on's test code.
... 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.
request - Archive of obsolete content
examples outlined in this document are no longer relevent in regards to the twitter api calls and need to be updated make simple network requests.
... for example, if you're retrieving text content which was encoded as iso-8859-1 (latin 1), it will be given a content type of "utf-8" and certain characters will not display correctly.
... the example below shows how to use request to get the most recent tweet from the @mozhacks account: var request = require("sdk/request").request; var latesttweetrequest = request({ url: "https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=mozhacks&count=1", oncomplete: function (response) { var tweet = response.json[0]; console.log("user: " + tweet.user.screen_name); console.
simple-storage - Archive of obsolete content
for example, this add-on tries to store the urls of pages the user visits: var ss = require("sdk/simple-storage"); ss.storage.pages = []; require("sdk/tabs").on("ready", function(tab) { ss.storage.pages.push(tab.url); }); require("sdk/ui/button/action").actionbutton({ id: "read", label: "read", icon: "./read.png", onclick: function() { console.log(ss.storage.pages); } }); but this isn't g...
...oing to work, because it empties the array each time the add-on runs (for example, each time firefox is started).
...for example: ss.storage.mylist = [ /* some long array */ ]; ss.on("overquota", function () { while (ss.quotausage > 1) ss.storage.mylist.pop(); }); private browsing if your storage is related to your users' web history, personal information, or other sensitive data, your add-on should respect private browsing.
content/mod - Archive of obsolete content
for example, the following code applies a style to a content window, adding a border to all divs in page: var attachto = require("sdk/content/mod").attachto; var style = require("sdk/stylesheet/style").style; var style = style({ source: "div { border: 4px solid gray }" }); // assuming window points to the content page we want to modify attachto(style, window); parameters modification : object the modification we want to apply to the target.
... for example, the following code applies and removes a style to a content window, adding a border to all divs in page: var { attachto, detachfrom } = require("sdk/content/mod"); var style = require("sdk/stylesheet/style").style; var style = style({ source: "div { border: 4px solid gray }" }); // assuming window points to the content page we want to modify attachto(style, window); // ...
...for example target can be a content window itself in which case it's will be returned back.
lang/type - Archive of obsolete content
uses typeof operator to check type, and will only properly detect string primitives: for example, a string created with new string() will always return false.
...uses typeof operator to check type, and will only properly detect number primitives: for example, a number created with new number() will always return false.
...the difference is that the type constructor can be from a scope that has a different top level object: for example, it could be from a different iframe, module or sandbox.
ui/sidebar - Archive of obsolete content
so you can rewrite the above code like this: var sidebar = require("sdk/ui/sidebar").sidebar({ id: 'my-sidebar', title: 'my sidebar', url: "./sidebar.html" }); you can include javascript and css from the html as you would with any web page, for example using <script> and <link> tags containing a path relative to the html file itself.
... see using attach for an example.
... see using ready for an example.
Getting started (cfx) - Archive of obsolete content
for example, we could change the page that gets loaded: var buttons = require('sdk/ui/button/action'); var tabs = require("sdk/tabs"); var button = buttons.actionbutton({ id: "mozilla-link", label: "visit mozilla", icon: { "16": "./icon-16.png", "32": "./icon-32.png", "64": "./icon-64.png" }, onclick: handleclick }); function handleclick(state) { tabs.open("https://developer.mozill...
...for example: while true ; do cfx xpi ; wget --post-file=codesy.xpi http://localhost:8888/ ; sleep 5 ; done note that the logging level defined for the console is different when you use this method, compared to the logging level used when an add-on is run using cfx run.
... another example using grunt and grunt-shell: module.exports = function(grunt) { 'use strict'; require('matchdep').filterdev('grunt-!(cli)').foreach(grunt.loadnpmtasks); grunt.initconfig({ shell: { xpi: { command: [ 'cd pluginpath', 'cfx xpi', 'wget --post-file=pluginname.xpi http://localhost:8888/ || echo>/dev/null' ].join('&&') } }, watch: { xpi: { files: ['pluginpath/**'], tasks: ['shell:xpi'] } } }); grunt.loadnpmtasks('grunt-contrib-watch'); grunt.loadnpmtasks('grunt-shell'); grunt.registertask('default', ['wa...
Open a Web Page - Archive of obsolete content
to open a new web page, you can use the tabs module: var tabs = require("sdk/tabs"); tabs.open("http://www.example.com"); this function is asynchronous, so you don't immediately get back a tab object which you can examine.
...the callback is assigned to the onready property, and will be passed the tab as an argument: var tabs = require("sdk/tabs"); tabs.open({ url: "http://www.example.com", onready: function onready(tab) { console.log(tab.title); } }); even then, you don't get direct access to any content hosted in the tab.
...this add-on loads a page, then attaches a script to the page which adds a red border to it: var tabs = require("sdk/tabs"); tabs.open({ url: "http://www.example.com", onready: runscript }); function runscript(tab) { tab.attach({ contentscript: "document.body.style.border = '5px solid red';" }); } learning more to learn more about working with tabs in the sdk, see the tabs api reference.
Using XPCOM without chrome - Archive of obsolete content
below is an example for the xpcom bookmark observer.
... examples bookmarks observer normally, a bookmark observer would require chrome components and xpcomutils as described in the following links: (observing changes to bookmarks and tags) , (creating event targets).
... below is an example, where we extend the xpcom module's unknown class with an nsinavbookmarkobserverinterface and one of its optional interface methods (onitemchanged).
Embedding SVG - Archive of obsolete content
notice the template and example use xhtml to handle the namespacing.
... <?xml version="1.0" encoding="utf-8"?> <!doctype html public "-//w3c//dtd xhtml 1.0 strict//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:svg="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> <body> <!-- html and svg go here --> </body> </html> example: <?xml version="1.0" encoding="utf-8"?> <!doctype html public "-//w3c//dtd xhtml 1.0 strict//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:svg="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> <body> <p>hello</p> <svg:svg version="1.1" baseprofile="full" width="150" height="150"> <svg:rect x="10" y="10" width="100" height="100" fil...
...</body> </html> embedding into xul make sure you use the right namespace when embedding <?xml version="1.0"?> <?xml-stylesheet href="chrome://global/skin/" type="text/css"?> <window xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" xmlns:svg="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> <!-- xul and svg go here --> </window> example: <?xml version="1.0"?> <?xml-stylesheet href="chrome://global/skin/" type="text/css"?> <window xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" xmlns:svg="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> <vbox> <label value="hello"/> <svg:svg version="1.1" baseprofile="full" width="150" height="150"> <svg:rect x="10" y="...
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.
...here is an example: var datastring = "name1=data1&name2=data2"; // post method requests must wrap the encoded text in a mime // stream const cc = components.classes; const ci = components.interfaces; var stringstream = cc["@mozilla.org/io/string-input-stream;1"].
QuerySelector - Archive of obsolete content
xul and even xml can be easily made supportable (an alternative approach to the following would be to add chromewindow.prototype or window.prototype, accessing this.document.queryselector, or following the jquery style of chaining by returning 'this' within each prototype method of $()): htmldocument.prototype.$ = function (selector) { // only for html return this.queryselector(selector); }; example: <h1>test!</h1> <script> htmldocument.prototype.$ = function (selector) { return this.queryselector(selector); }; alert(document.$('h1')); // [object htmlheadingelement] </script> xuldocument.prototype.$ = function (selector) { // only for xul return this.queryselector(selector); }; example: <label value="test!"/> <script type="text/javascript"><![cdata[ xuldocument.prototype.$ = func...
...ment.implementation.createdocument('somens', 'foo', null); // create an xml document <foo xmlns="somens"/> var bar = foo.createelementns('somens', 'bar'); // add <bar xmlns="somens"/> foo.documentelement.appendchild(bar); alert(foo.$('bar').nodename); // gives 'bar' element.prototype.$ = function (selector) { // works for html, xul, and plain xml return this.queryselector(selector); }; html example: <h1><a>test!<a/></h1> <script> element.prototype.$ = function (selector) { return this.queryselector(selector); }; alert(document.getelementsbytagname('h1')[0].$('a').nodename); // 'a' xul example: <hbox><vbox/></hbox> <script type="text/javascript"><![cdata[ element.prototype.$ = function (selector) { return this.queryselector(selector); }; var xulns = 'http://www.mozilla.org/keymaster...
.../gatekeeper/there.is.only.xul'; alert(document.getelementsbytagnamens(xulns, 'hbox')[0].$('vbox').nodename); // vbox ]]></script> xml example: <foo xmlns="somens"><bar/></foo> in document earlier var foo = document.getelementsbytagnamens('somens', 'foo')[0]; alert(foo.$('bar')); note that for plain xml, the # 'id' selector will not work with an 'id' attribute (since a such-named attribute need not necessarily be of type id in xml, though it is in html and xul), nor will it work with xml:id.
Scrollbar - Archive of obsolete content
this example shows how to style the scrollbars in your xul application.
... example assumes a structure like this: app/chrome/chrome.manifest app/chrome/skin/global/ copy the scrollbars.css from xulrunner/chrome/classic.jar/skin/classic/global to app/chrome/skin/global/scrollbars.css open the app/chrome/chrome.manifest and add: skin app-global standard/1.0 skin/global/ override chrome://global/skin/xulscrollbars.css chrome://app-global/skin/scrollbars.css xulscrollbars.css are used for windows xp, and nativescrollbars.css on osx.
... example xul window: <?xml version="1.0"?> <?xml-stylesheet href="chrome://global/skin/" type="text/css"?> <window id="samplewindow" width="320" height="240" xmlns="http://www.mozilla.org/keymaster/gat...re.is.only.xul"> <hbox flex="1"> <browser type="content" src="http://mozilla.org" flex="1"/> <scrollbar orient="vertical"/> </hbox> </window> ...
Sidebar - Archive of obsolete content
for example the code below calls a function defined in the sidebar's context: var sidebarwindow = document.getelementbyid("sidebar").contentwindow; // verify that our sidebar is open at this moment: if (sidebarwindow.location.href == "chrome://yourextension/content/whatever.xul") { // call "yournotificationfunction" in the sidebar's context: sidebarwindow.yournotificationfunction(anyarguments); } ...
...the good practice to determine which sidebar is open at a time is by testing in location property, which is a chrome url: var sidebarwindow = document.getelementbyid("sidebar").contentwindow; if (sidebarwindow.location.href == "chrome://yourextension/content/whatever.xul") { // act on the sidebar content } for example to test if the web panel from firefox is open: var sidebarwindow = document.getelementbyid("sidebar").contentwindow; if (sidebarwindow.location.href == "chrome://browser/content/web-panels.xul") { // act on the sidebar content only if it is the web panels } accessing the browser.xul window from a sidebar script see accessing the elements of the top-level document from a child window sectio...
...for example, use this in your sidebar's unload event handler: mainwindow.document.getelementbyid("sidebar-splitter").hidden = mainwindow.document.getelementbyid("sidebar-box").hidden; see also bootstrap demo addon that creates a sidebar with html content: https://gist.github.com/noitidart/8728393 ...
Windows - Archive of obsolete content
example window.open(); //this open a pop-up window that could be "blocked" client-side //the following code generate an error as describe in the following warning box var wm = components.classes["@mozilla.org/appshell/window-mediator;1"] .getservice(components.interfaces.nsiwindowmediator); var newwindow = wm.getmostrecentwindow("navigator:browser"); var b = newwindow.gbrowser; the code generate a typee...
... example var startpos = null; function mousedown(event) { startpos = [event.clientx, event.clienty]; } function mousemove(event) { if (startpos) { var newx = event.screenx - startpos[0]; var newy = event.screeny - startpos[1]; window.moveto(newx, newy); } } function mouseup(event) { startpos = null; } window.addeventlistener("mousedown", mousedown, false); window.addeventlistener("...
...for example, the following code will add a horizontal rule.
Intercepting Page Loads - Archive of obsolete content
asubject.setrequestheader("referer", "http://example.com", false); } else if (re_url_to_cancel.test(url)) { // re_url_to_cancel is a regular expression.
... asubject.cancel(components.results.ns_binding_aborted); } } } this example shows how you can obtain the url for the request, analyze it using regular expressions, and perform actions on it such as modifying http headers, or even canceling the request.
...in the previous example, one of the first things we do is check if the url is of interest to us, otherwise we let it go.
Observer Notifications - Archive of obsolete content
for example, you might want to notify that a task is completed, and then several different actions must be performed.
... this example code shows you what an implementation of the nsiobserver interface looks like: let testobserver = { observe : function(asubject, atopic, adata) { if (atopic == "xulschoolhello-test-topic") { window.alert("data received: " + adata); } } } in order for this observer to work, you need to use the observer service that provides methods for you to add, remove, notify and enumera...
... let's see the following example code on how to send out a notification from non-chrome code.
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.
...~/.bash_login; make" an example project with xpcom components is included in the xpcom section.
The Box Model - Archive of obsolete content
most of the examples shown in the rest of this section were generated using the xul box alignment example.
... here's a very simple example of an hbox with 3 child buttons: <hbox> <button label="cat" /> <button label="parrot" /> <button label="porcupine" /> </hbox> this is how it looks on mac os (the black border was added for illustrative purposes, boxes don't have borders by default): if you use a vbox instead, it looks like this: the orientation of boxes (and most xul elements) can be controlled using the orient att...
...if we add flexibility to the hbox in our first example, we get the following result: the box flexes to cover the available horizontal space.
Performance best practices in extensions - Archive of obsolete content
for example, bug 719601 featured a "system principal" javascript compartment containing 100s of mbs of memory, which is much larger than usual.
...see examples.
...look through the source for examples.
Case Sensitivity in class and id Names - Archive of obsolete content
for example, there might be this css: p.warning {color: red; background: yellow;} ...coupled with this html: <p class="warning">warning!</p> in netscape 6, the paragraph in question will have neither red text nor a yellow background.
...for example, you would not want to do something like: .urgent {color: purple;} .urgent {color: yellow;} even though these are technically two distinct class names, browsers other than netscape 6 will treat them as though they are the same thing.
...an "illegal" example is given in the specification, preceded by the text: "the following example is illegal with respect to uniqueness since the two names are the same except for case." <p><a name="xxx">...</a> <p><a name="xxx">...</a> we could freely substitute id for name and the point would be the same, since name and id share the same name space (see section 12.2.3).
Source code directories overview - Archive of obsolete content
for example, if the javascript script adds a user-defined attribute to the document (e.g.
...for example, if this code determines that the content is a mail message, it looks up the appropriate listener (probably netscape messenger) and passes the mail message to it for display.
...for example, a scrolling view will find out the scroll bar positions and tell its content where to draw according the scroll bar thumbs.
Creating a Microsummary - Archive of obsolete content
in this tutorial we're going to create a microsummary generator for the spread firefox home page that displays the current firefox download count along with the label fx downloads; for example: 174475447 fx downloads.
... for example, if you use php scripts to generate pages on your site, you could write php code to output a microsummary when the view=microsummary url parameter is present.
... for example, if we put the generator file on the web at http://people.mozilla.com/~myk/micro...-generator.xml, and we wanted users to be able to install it from http://people.mozilla.com/~myk/micro...ial/index.html, we might add the following code to the index.html page: <button onclick="window.sidebar.addmicrosummarygenerator('http://people.mozilla.com/~myk/microsummaries/tutorial/sfx-generator.xml')">inst...
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.
...you can find a better quality answer repeated and with an example in this newsgroup thread.
Layout System Overview - Archive of obsolete content
consider for example a large paragraph of text sitting in paragraph: <p> we need documentation for users, web developers, and developers working on mozilla.
...as the width of the block changes (due to the window being resized, for example) the length of the lines within it changes, and thus more or less text appears on each line.
...for example, the presentation shell receives notifications of document load events, which are used to trigger updates to the formatting of the frames in some cases.
Hidden prefs - Archive of obsolete content
mail composition "other header" pref ("mail.compose.other.header") the format for this a comma delimited list of mail headers, like "approved,x-no-archive" an example for your prefs.js would be: user_pref("mail.compose.other.header", "approved"); this will cause "approved" to show up in the compose window address picker, under to:, cc:, bcc:, newsgroup:, etc.
... for example: when that mail gets sent, approved: test@test.com will be in the message in the headers.
...| mail & newsgroups | addressing" "other compose header" pref from mailnews.js: // you can specify a comma delimited list of optional headers // this will show up in the address picker in the compose window // examples: "x-face" or "approved" pref("mail.compose.other.header", "approved,x-no-archive"); ...
Clipboard - Archive of obsolete content
the api is fairly straightforward; examples can be found here.
...the only flavors currently implemented are 'plain' (text/unicode) and 'html' (which is html).string"text" here's an example of how to use the method to set the clipboard.
...string here's an example of how to use the method to get the data on the clipboard.
Clipboard Test - Archive of obsolete content
the api is fairly straightforward; examples can be found here.
...the only flavors currently implemented are 'plain' (text/unicode) and 'html' (which is html).string"text" here's an example of how to use the method to set the clipboard.
...string here's an example of how to use the method to get the data on the clipboard.
Clipboard - Archive of obsolete content
the api is fairly straightforward; examples can be found here.
...the only flavors currently implemented are 'plain' (text/unicode) and 'html' (which is html).string"text" here's an example of how to use the method to set the clipboard.
...string here's an example of how to use the method to get the data on the clipboard.
Selection - Archive of obsolete content
this api currently lives in the future and must be imported for use: jetpack.future.import("selection"); getting and setting the selection the current version of jetpack.selection includes these formats: .text and .html getting the selection the following is an example of getting the selection from the user.
... jetpack.import.future("selection");var textofsel = jetpack.selection.text;var htmlofsel = jetpack.selection.html; setting the selection the following is an example of getting the selection from the user.
...function adding a selection event jetpack.selection.onselection( fn ); removal of a selection event jetpack.selection.onselection.unbind( fn ); verbose example the following example will bold the html that you select.
Selection - Archive of obsolete content
this api currently lives in the future and must be imported for use: jetpack.future.import("selection"); getting and setting the selection the current version of jetpack.selection includes these formats: .text and .html getting the selection the following is an example of getting the selection from the user.
... jetpack.import.future("selection"); var textofsel = jetpack.selection.text; var htmlofsel = jetpack.selection.html; setting the selection the following is an example of getting the selection from the user.
...function adding a selection event jetpack.selection.onselection( fn ); removal of a selection event jetpack.selection.onselection.unbind( fn ); verbose example the following example will bold the html that you select.
Clipboard - Archive of obsolete content
the api is fairly straightforward; examples can be found here.
...the only flavors currently implemented are 'plain' (text/unicode) and 'html' (which is html).string"text" here's an example of how to use the method to set the clipboard.
...string here's an example of how to use the method to get the data on the clipboard.
Selection - Archive of obsolete content
ArchiveMozillaJetpackdocsUISelection
this api currently lives in the future and must be imported for use: jetpack.future.import("selection"); getting and setting the selection the current version of jetpack.selection includes these formats: .text and .html getting the selection the following is an example of getting the selection from the user.
... jetpack.import.future("selection"); var textofsel = jetpack.selection.text; var htmlofsel = jetpack.selection.html; setting the selection the following is an example of getting the selection from the user.
...function adding a selection event jetpack.selection.onselection( fn ); removal of a selection event jetpack.selection.onselection.unbind( fn ); verbose example the following example will bold the html that you select.
Microsummary XML grammar reference - Archive of obsolete content
example the microsummary generator created in the creating a microsummary tutorial: <?xml version="1.0" encoding="utf-8"?> <generator xmlns="http://www.mozilla.org/microsummaries/0.1" name="firefox download count"> <template> <transform xmlns="http://www.w3.org/1999/xsl/transform" version="1.0"> <output method="text"/> <template match="/"> <value-of select="id('download-count')"...
...the following example identifies a generator as being able to summarize all pages on the www.example.com web site except pages named about.html: <pages> <include> ^http://www\.example\.com/ </include> <exclude>/about\.html</exclude> </pages> note: regular expressions intended to match the beginnings of page urls should start with the caret (^) to ensure they do not inadvertently match urls which merely c...
...for example, the regular expression http://www\.example\.com/ matches both the url http://www.example.com/ and the url http://www.evil.com/http://www.example.com/, but the regular expression ^http://www\.example\.com/ matches only the first of those two urls.
Mozilla Application Framework in Detail - Archive of obsolete content
the networking library, for example, is a set of xpcom components that can be accessed and used by any mozilla application.
...the mozblog application hosted at mozdev.org, for example, uses xpinstall to make several different versions available simultaneously as updates are made and the browser itself advances versions.
...es the following functionality available as high-level javascript objects: an install trigger that initiates installations windows registry access mozilla registration interfaces for registering new mozilla software facilities for detecting and maintaining application versions high-level objects for manipulating local directories and files complete reference documentation, including useful example installations the following snippet from an xpinstall installation gives you some idea about how easy it is to write cross-platform installations that use the mozilla browser: // register chrome registerchrome(package | delayed_chrome, getfolder("chrome","xmlterm.jar"), "content/xmlterm/"); registerchrome(skin | delayed_chrome, getfolder("chrome","xmlterm.jar"), "skin/modern/xmlterm/"); registe...
PyDOM - Archive of obsolete content
for example, when a top-level window has something like: <window ...
...for example, let's say you have xul similar to pyxultest: top-level script code says something like: button = document.getelementbyid("some-button") button.foo = 0 and the button itself might look like: <button id="some-button" label="click here" onclick="event.target.foo += 1; print 'foo is now', event.target.foo"/> note that (a) we have stuck an arbitrary attribute on a dom element and (b) in all cases (e.g., event handler and top-level script), the dom node needs to be explicitly specified - the globals are the window itself.
...for example, <window script-type="application/x-python" .../> html <meta http-equiv="content-script-type" content="application/x-python" /> should work (but possibly doesn't - see bug 100924).
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 ...
Frequently Asked Questions - Archive of obsolete content
for example, webpages that embed svg using the <object> or <embed> tags must have a 'type' attribute assigned with the correct svg mime type of "image/svg+xml".
... if the mime type specified is wrong (for example image/svg-xml) mozilla won't recognise it.
...for example we support svg exceptions and svgtransform objects.
Actionscript Acceptance Tests - Archive of obsolete content
this example passes in another .abc file as an argument to the file being run: -- $dir/file.abc another use would be to pass a specific argument to the shell: -dtimeout this file can have multiple lines with different arguments.
... here is a more complicated example that passes both avm args, multiple abcs and test args: -ojit |multiabc| $dir/testname_support/a.abc -- test_args a dir.avm_args file can also be created with the same contents that will apply to the entire directory.
... in this example the .as test runs out of memory and so the expected exitcode is: 128 testname.out file that specifies expected output.
Running Tamarin performance tests - Archive of obsolete content
for example you may download or build the latest checked in avmshell to compare against a local change.
...the /android-public/android-vars.sh script has commented-out examples of the environment settings for running tests on the android avm shell.
...testsuite setup example commands: root the phone $ adb root copy avmshell to /data/app.
Tamarin build documentation - Archive of obsolete content
example call to build on an x86_64 machine with the 10.5 sdk: $ ../configure.py --mac-sdk=105 --target=x86_64-darwin if asc is not set, you will need to add asc.jar to the utils directory in tamarin-redux (bug 631641).
...e following variables into the environment $ export android_toolchain=<full path to your android sdk/ndk top folder> $ export android_ndk=$android_toolchain/android-ndk $ export android_ndk_bin=$android_ndk/toolchains/arm-linux-androideabi-4.4.3/prebuilt/darwin-x86/bin $ export android_sdk=$android_toolchain/android-sdk-mac_86 $ export path=$path:$android_sdk/platform-tools:$android_ndk_bin - example commands to build tamarin: $ hg clone http://hg.mozilla.org/tamarin-redux $ cd tamarin-redux $ mkdir objdir-release $ cd objdir-release $ ../configure.py --arm-arch=armv7-a --target=arm-android $ make to make a debug shell use this command: ../configure.py --enable-debug --arm-arch=armv7-a --target=arm-android using cross-platform scripts in cygwin on windows: prerequisites: you need pyth...
...for example, if you chose the win32 debug_debugger configuration your build will be under \tamarin-redux\platform\win32\obj_9\shell\debug_debugger by default.
Binding Attachment and Detachment - Archive of obsolete content
in the following example, a binding is referenced that will be attached to all html checkbox elements.
... for example, given a binding d1, with an explicit inheritance chain of d1 -> d2 -> d3 if this element is attached to an element using element.style.mozbinding that already has a binding chain of s1 -> s2 -> s3 the resulting binding chain following the addition of the binding is d1 -> d2 -> d3 -> s1 -> s2 -> s3 the inheritance between d3 and s1 is implicit, meaning that there is no connection in the xbl...
... for example, given a bound element with a binding chain of d1->d2 ->d3 ->s1 ->s2 ->s3 withs1 representing the binding attached via css.
XBL 1.0 Reference - Archive of obsolete content
e forwarding insertion points <children> handling dom changes event flow and targeting flow and targeting across scopes focus and blur events mouseover and mouseout events anonymous content and css selectors and scopes binding stylesheets binding implementations introduction methods properties inheritance of implementations event handlers example - sticky notes updated and adjusted for the current firefox implementation.
... this example is targeted to demonstrate the xbl usage rather than to be a practically useful application.
... notes.html notes.xml notes.css view this example download all files (.zip archive) need to ask to adjust the server - it gives "access denied" for zip files (?) references initial xbl 1.0 proposal submitted as a note to w3c (does not reflect mozilla implementation, nor future plans) xbl 2.0 project original document information last updated date: april 24, 2006 ...
registerChrome - Archive of obsolete content
note that you can combine switches as in the example below.
...for example, "locale/mylocale/aim," points to the locale/mylocale/aim subdirectory of the same xpi file in which the installation script is located.
...example example assumes your xpi file is in plugins folder and rdf file is in resources subfolder of xpi.
Accessing Files - Archive of obsolete content
the following example will retrieve a reference to a file named sample.txt located in the profile directory.
...in the example above the word 'profile' is used, which means start from within the user's profile directory.
...starting directories the examples above use the profile directory 'profile' as the starting directory for locating a file.
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.
... for example, the standard findbar in firefox 3.5 looks like this on the mac: you may attach a findbar to a particular browser element by either setting the findbar's browserid attribute to the id of the browser element before the findbar element is bound, or by setting the findbar's browser property to the browser element itself.
... attributes browserid, findnextaccesskey, findpreviousaccesskey, highlightaccesskey, matchcaseaccesskey properties browser, findmode methods close, onfindagaincommand, open, startfind, togglehighlight example <browser type="content-primary" flex="1" id="content" src="about:blank"/> <findbar id="findtoolbar" browserid="content"/> attributes browserid type: string the id of the browser element to which the findbar is attached.
International characters in XUL JavaScript - Archive of obsolete content
for example, they can contain a line: var text = "ein schönes beispiel eines mehrsprachigen textes: 日本語"; this mixes german and japanese characters.
... if the script file is loaded via http, the http header can contain a character encoding declaration as part of the content-type header, for example: content-type: application/javascript; charset=utf-8 if no charset parameter is specified, the same rules as above apply.
...however, you can use unicode escapes – the earlier example rewritten using them would be: var text = "ein sch\u00f6nes beispiel eines mehrsprachigen textes: \u65e5\u672c\u8a9e"; an alternative might be to use property files via nsistringbundle or the xul <stringbundle> element; this would allow for localization of the xul.
Namespaces - Archive of obsolete content
for example, <xul:textbox/> uses a namespace named "xul" and a local name "textbox".
... this distinguishes it from, for example, <foobar:textbox/> which might occur in the same document.
... <foo/> the answer is that it's in no namespace, or alternately, it's in the namespace denoted by the empty string: <foo xmlns=""/> this second example is semantically equivalent to the first.
Providing Command-Line Options - Archive of obsolete content
see also: xulrunner:commandline overview the code below is an example of writing a javascript xpcom component to handle command line parameters.
... example the below example component implements two command line parameters: firefox.exe -myapp opens a chrome window for my application.
... using the example to use this sample code, save the commandline.js file into the components directory and add the following lines to your chrome.manifest file: component {2991c315-b871-42cd-b33f-bfee4fcbf682} components/commandline.js contract @mozilla.org/commandlinehandler/general-startup;1?type=myapp {2991c315-b871-42cd-b33f-bfee4fcbf682} category command-line-handler m-myapp @mozilla.org/commandlinehandler/general-startup;1?type=myapp the javascript code const cc = components.classes; const ci = components.interfaces; components.utils.import("resource://gre/modules/xpcomutils.jsm"); components.utils.import("resource://gre/modules/services.jsm"); // changeme: to the chrome uri of you...
Sorting and filtering a custom tree view - Archive of obsolete content
this is example code for sorting and filtering a custom tree view, that is, a tree whose values are loaded via javascript.
... this will not work for other types of trees, for example rdf-backed or ones created with dom methods.
...sort.xul <?xml version="1.0"?> <?xml-stylesheet href="chrome://global/skin/" type="text/css"?> <!doctype window> <window title="sorting a custom tree view example" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" onload="init()"> <script type="application/javascript" src="sort.js"/> <hbox align="center" id="search-box"> <label accesskey="f" control="filter">filter</label> <textbox id="filter" oninput="inputfilter(event)" flex="1"/> <button id="clearfilter" oncommand="clearfilter()" label="clear" accesskey="c" disabled="true"/> </hbox> <tree id="tree" flex="1" persist="sortdirection sortresource" so...
Attribute Substitution - Archive of obsolete content
it can also be used to separate a variable with normal text: <label value="?name" class="?gender^german"/> these last two examples have been setting the class attribute on a label.
...my name is ?name"/> in this example, the label might be 'what is my name?
...another possibilty is to rearrange the rdf such that the values, in this example, the descriptions, are specified before the containers.
Introduction - Archive of obsolete content
for example, for an xml datasource, the url of an xml file is specified.
...here is an example: <vbox datasources="http://www.xulplanet.com/ds/sample.rdf" querytype="rdf"> this example specifies the datasource 'http://www.xulplanet.com/ds/sample.rdf', using the datasource type rdf as indicated by the querytype attribute'.
...for example: <listbox datasources="http://www.xulplanet.com/ds/sample.xml" querytype="xml"> <template> <listitem label="?name"/> </template> </listbox> this template uses an xml datasource to generate a listbox.
Rule Compilation - Archive of obsolete content
for example, the first rule might apply to results that represent books, while the second rule might apply only to results that are magazines.
...for instance, consider the example below: <vbox datasources="http://www.xulplanet.com/ds/sample.rdf" ref="http://www.xulplanet.com/rdf/a" hidden="true"> <template> ...
...for example, just calling the code like the following on the hidden vbox above will start off the template builder.
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 is an example: <vbox datasources="people.xml" ref="*" querytype="xml"> <template> <query expr="person"> <assign var="?namelength" expr="string-length(@name)"/> <assign var="?siblings" expr="count(../*) - 1"/> </query> <action> <hbox uri="?" align="center"> <button label="?name"/> <label value="?gender"/> <label value="?namelength"/> <label value="?siblings"/> </hbox> </action> </template> </vbox> two assign elements are placed as children of the query element.
...here, the two attributes 'name' and 'gender' will be taken from the xml data, as in previous examples.
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.
...window, document, or any of the functions/objects/variables bound to the window object event object example <?xml version="1.0"?> <?xml-stylesheet href="chrome://global/skin/" type="text/css"?> <window id="findfile-window" title="find files" orient="horizontal" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <script type="text/javascript"> function myfunction(e){ /* do something cool here or just say the below */ alert(e.target.nodename); ...
Tree Widget Changes - Archive of obsolete content
for example, nsitreeview.getcellvalue() takes a row index and a nsitreecolumn as arguments, whereas before it took a row index and a column id.
...this is shown in the example above.
...example: treechildren::-moz-tree-separator { margin-top: 1px; border-top: 1px solid threedshadow; border-left: 1px solid threedshadow; border-right: 1px solid threedhighlight; border-bottom: 1px solid threedhighlight; height: 2px; } original document information author: neil deakin source: here ...
Adding more elements - Archive of obsolete content
adding elements to our find files example we will add some more elements to the find files dialog now.
...we will see more examples of the box model and some of its features as we continue to add elements throughout the tutorial.
... find files example so far source view next, we will look at how to create stacks.
Additional Install Features - Archive of obsolete content
for example, you may want to install a package only when certain conditions are met, such as having a particular library installed.
...for example, you might want to make a backup of some files first.
...for example, you might put the following as the last section of your script: if (getlasterror() == success) { performinstall(); } else { cancelinstall(); } error codes that could be returned by getlasterror() are listed in the mozilla source file nsinstall.h.
Features of a Window - Archive of obsolete content
for example: var mywin = window.open("chrome://findfile/content/findfile.xul", "findfile", "chrome"); specifying the width and height you should have noticed that whenever elements were added to a window, the window's width expanded to fit the new elements.
... <window id="findfile-window" title="find files" width="400" height="450" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> in this example, the window will open with a width of 400 pixels and a height of 450 pixels.
...you may disable a feature by setting it to 'no', for example 'dialog=no'.
Modifying the Default Skin - Archive of obsolete content
this directory should be created when you create a profile and some examples placed there.
... for example, by adding the following to the end of the file, you can change all menubar elements to have a red background.
...for example, to add a red border around the menu commands in the bookmarks manager window, add the following to bookmarksmanager.css in the classic.jar or your favorite skin archive.
More Tree Features - Archive of obsolete content
example hierarchical tree the following is a simple example: example 1 : source view <tree rows="6"> <treecols> <treecol id="firstname" label="first name" primary="true" flex="3" /> <treecol id="lastname" label="last name" flex="7" /> </treecols> <treechildren> <treeitem container="true" open="true"> <treerow> <treecell label="guys" /> </treerow> <tre...
...for example, a directory with no files in it should still be treated like a container whereas a file should not.
...you will need to save a number of attributes as indicated in the example below: example 2 : source view <tree enablecolumndrag="true" flex="1"> <treecols> <treecol id="runner" label="runner" flex="2" persist="width ordinal hidden" /> <splitter class="tree-splitter" /> <treecol id="city" label="home city" flex="2" persist="width ordinal hidden" /> <splitter class="tree-splitter" /> <treecol id="starttime" label="start time" flex="1" persist="width...
More Wizards - Archive of obsolete content
for example, here are a set of wizard pages (the inner content has been omitted): <wizardpage pageid="type" next="font"> <wizardpage pageid="font" next="done"> <wizardpage pageid="color" next="done"> <wizardpage pageid="done"> the wizard always starts at the first page, which in this case has the page id type.
...in the following example, the user must enter a secret code into a textbox on the first page of the wizard.
... wizard example source <?xml version="1.0"?> <?xml-stylesheet href="chrome://global/skin/" type="text/css"?> <wizard id="thewizard" title="secret code wizard" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <script> function checkcode(){ document.getelementbyid('thewizard').canadvance = (document.getelementbyid('secretcode').value == "cabbage"); } </script> <wizardpage onpageshow="checkcode(); return true;"> <label value="enter the secret code:"/> <textbox id="secretcode" onkeyup="checkcode();"/> </wizardpage> <wizar...
Open and Save Dialogs - Archive of obsolete content
this would be used, for example, to hide all but .html files.
... fp.appendfilters(nsifilepicker.filterhtml | nsifilepicker.filterimages); fp.appendfilters(nsifilepicker.filtertext | nsifilepicker.filterall); the first example will add filters for html and for image files.
... the second example will add filters for text files and for all files.
Stack Positioning - Archive of obsolete content
for example, if a stack has two buttons as children, one may be placed 20 pixels from the left edge and 50 pixels from the top edge.
... example 1 : source view <stack> <button label="goblins" left="5" top="5"/> <button label="trolls" left="60" top="20"/> <button label="vampires" left="10" top="60"/> </stack> the stack here contains three elements, each positioned at the coordinates given by the left and top attributes.
... in this example, the resulting width of the top-most hbox will be 400px: <stack width="600"> <hbox flex="1"> <!-- content --> </hbox> <hbox left="0" right="200" > <!-- some content here.
Tabboxes - Archive of obsolete content
tabbox example example 1 : source view <tabbox> <tabs> <tab label="mail"/> <tab label="news"/> </tabs> <tabpanels> <tabpanel id="mailtab"> <checkbox label="automatically check for mail"/> </tabpanel> <tabpanel id="newstab"> <button label="clear news buffer"/> </tabpanel> </tabpanels> </tabbox> here, two tabs have been added, the first labeled 'mail' and the othe...
... for example, to place the tabs along the left side, change the orientation of the tabs element to vertical to make the tabs appear vertically stacked.
... find files example so far : source view next, we'll look at how to create grids of content.
XML - Archive of obsolete content
there are many times, for example, when you may use javascript tricks to add extra behavior.
...for example, <html:img src="box.gif" /> is valid, but <html:img src="box.gif"> is not.
...so the example here is valid memo according to our dtd; it's a memo that's been writtten in memoml.
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.
...for example, for a menuitem in a menu you can add the following css rule when you want to use the value none: menupopup > menuitem, menupopup > menu { max-width: none; } image type: uri the uri of the image to appear on the element.
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.
...for example, for a menuitem in a menu you can add the following css rule when you want to use the value none: menupopup > menuitem, menupopup > menu { max-width: none; } 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.
... for example, a clipboard paste operation can be invoked from the edit menu, a context menu and by pressing a keyboard shortcut.
...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 ...
commandset - Archive of obsolete content
« xul reference home [ examples | attributes | properties | methods | related ] this element is not displayed and serves as a container for command elements.
... attributes commandupdater, events, oncommandupdate, targets example <commandset> <command id="cmd_open" oncommand="alert('open!');"/> <command id="cmd_help" oncommand="alert('help!');"/> </commandset> attributes commandupdater type: boolean if true, the commandset is used for updating commands.
...for example, since the cut command is only valid when something is selected, a command updater might be used when the select event occurs.
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.
...for example, for a menuitem in a menu you can add the following css rule when you want to use the value none: menupopup > menuitem, menupopup > menu { max-width: none; } disabled type: boolean indicates whether the element is disabled or not.
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.
...for example, for a menuitem in a menu you can add the following css rule when you want to use the value none: menupopup > menuitem, menupopup > menu { max-width: none; } description type: string descriptive text to appear in addition to the dialog title.
editor - Archive of obsolete content
« xul reference home [ examples | attributes | properties | methods | related ] a frame which is expected to contain an editable document.
...to enable editing on an editor, do either of the following: set the src attribute on the editor after the outer window has loaded, for example, in the onload handler.
... 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" ty...
iframe - Archive of obsolete content
« xul reference home [ examples | attributes | properties | methods | related ] an inner frame that works much like the html <iframe> element.
...this can be a serious security vulnerability, for example if you use src="http://...".
... 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"/> </menupopup> </menulist> <iframe id="myframe" flex="1"/> <script> function donav(obj) { var url = obj.se...
label - Archive of obsolete content
ArchiveMozillaXULlabel
« 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.
...for example, for a menuitem in a menu you can add the following css rule when you want to use the value none: menupopup > menuitem, menupopup > menu { max-width: none; } disabled type: boolean indicates whether the element is disabled or not.
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"/> </listc...
...the item index is zero-based, thus this example will return the first selected item: getselecteditem(0).
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.
...for example, for a menuitem in a menu you can add the following css rule when you want to use the value none: menupopup > menuitem, menupopup > menu { max-width: none; } 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.
...for example, for a menuitem in a menu you can add the following css rule when you want to use the value none: menupopup > menuitem, menupopup > menu { max-width: none; } current type: boolean this attribute will be set to true if the listitem is the current item.
menu - Archive of obsolete content
ArchiveMozillaXULmenu
« xul reference home [ examples | attributes | properties | methods | related ] an element, much like a button, that is placed on a menubar.
...accesskey, allowevents, command, crop, disabled, image, label, menuactive, open, sizetopopup, tabindex, value properties accessibletype, accesskey, command, control, crop, disabled, image, itemcount, label, labelelement, menupopup, open, parentcontainer, selected, tabindex, value methods appenditem, getindexofitem, getitematindex, insertitemat, removeitemat style classes menu-iconic example <menubar id="sample-menubar"> <menu id="file-menu" label="file"> <menupopup id="file-popup"> <menuitem label="new"/> <menuitem label="open"/> <menuitem label="save"/> <menuseparator/> <menuitem label="exit"/> </menupopup> </menu> <menu id="edit-menu" label="edit"> <menupopup id="edit-popup"> <menuitem label="undo"/> <menuitem label="red...
...for example, for a menuitem in a menu you can add the following css rule when you want to use the value none: menupopup > menuitem, menupopup > menu { max-width: none; } disabled type: boolean indicates whether the element is disabled or not.
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 co...
...for example, for a menuitem in a menu you can add the following css rule when you want to use the value none: menupopup > menuitem, menupopup > menu { max-width: none; } description type: string descriptive text to appear in addition to the dialog title.
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.
...for example, for a menuitem in a menu you can add the following css rule when you want to use the value none: menupopup > menuitem, menupopup > menu { max-width: none; } disableautoselect type: boolean if this attribute is true or omitted, the selected item on the menu will update to match what the user entered in the textbox.
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.
...for example, for a menuitem in a menu you can add the following css rule when you want to use the value none: menupopup > menuitem, menupopup > menu { max-width: none; } disabled type: boolean indicates whether the element is disabled or not.
notificationbox - Archive of obsolete content
« xul reference home [ examples | attributes | properties | methods | related ] the notificationbox element is used to display notifications above an element.
...this element is used, for example, to implement the yellow information bar in various firefox windows.
... 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.
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 ...
radio - Archive of obsolete content
ArchiveMozillaXULradio
« 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.
...for example, for a menuitem in a menu you can add the following css rule when you want to use the value none: menupopup > menuitem, menupopup > menu { max-width: none; } disabled type: boolean indicates whether the element is disabled or not.
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.
...the item index is zero-based, thus this example will return the first selected item: getselecteditem(0).
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.
... note that this example doesn't use a scrollbox tag; you only need that tag if you want to programmatically scroll in addition to the automatic scroll bars.
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.
... the vbox is used to hold the .png image that a user clicks on to resize the search bar.--> <splitter tooltiptext="resize the search box" oncommand="alert('the splitter was dragged')"> <vbox id="example_vbox" /> </splitter> attributes collapse type: one of the values below determines which side of the splitter is collapsed when its grippy is clicked.
stack - Archive of obsolete content
ArchiveMozillaXULstack
« 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.
... --> </hbox> </stack> in this example, the resulting width of the top-most hbox will be 400px (600px - 200px - 0) : <stack width="600"> <hbox flex="1"> <!-- content --> </hbox> <hbox left="0" right="200" > <!-- some content here.
<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.
...for example, for a menuitem in a menu you can add the following css rule when you want to use the value none: menupopup > menuitem, menupopup > menu { max-width: none; } image type: uri the uri of the image to appear on the element.
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.
...for example, the following defines two properties: message.displayerror=an error occured trying to display this message message.namealreadyused=the name %s is already being used by another account.
... 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.
tab - Archive of obsolete content
ArchiveMozillaXULtab
« 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.
...for example, for a menuitem in a menu you can add the following css rule when you want to use the value none: menupopup > menuitem, menupopup > menu { max-width: none; } disabled type: boolean indicates whether the element is disabled or not.
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 press...
...for example, back-button,forward-button,print-button.
toolbaritem - Archive of obsolete content
« xul reference home [ examples | attributes | properties | methods | related ] firefox only an item that appears on a toolbar.
... the element is used, for example, to hold the location bar's textbox in firefox.
... 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" /> <toolbarbutton id="myext-button2" class="toolbarbutton-1" label="labe2l" /> </toolbaritem> attributes inherited from xul element align, allowevents, allownegativeassertions, class, coalesceduplicatearcs, collapsed, container, containment, context, c...
triple - Archive of obsolete content
« xul reference home [ examples | attributes | properties | methods | related ] a triple can be included inside a rule's conditions element.
...for example, for a bookmark resource, the name and url would be predicates.
... attributes object, predicate, subject examples (example needed) attributes object type: string the object of the element.
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!!
...this might be used, for example, to distinguish between a browser window and an editor window.
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 onpage...
...this might be used, for example, to distinguish between a browser window and an editor window.
Custom app bundles for Mac OS X - Archive of obsolete content
a xul application for mac os x should follow something similar to this basic directory structure: example.app/ contents/ info.plist (application bundle properties are specified in this xml file.) pkginfo (this is a simple text file and is created along with the info.plist file) macos/ (the macos folder will contain your xulrunner executable) xulrunner (this is the xulrunner stub) resources/ (this is where you place your xul applica...
...tion code and support files) application.ini (xulrunner-related application settings) example.icns (this is the icon which will be used by your application bundle) chrome/ content/ example.xul (this directory contains your application's chrome) example.manifest defaults/ preferences/ app-prefs.js (this provides some default values for preferences) application bundle contents in addition to the standard directory hierarchy that's required of all mac os x applications, as shown above in application bundle layout, there are some specific rules for what content goes ...
... examples these example files are taken from a port of webrunner which was created to illustrate one method of mac os x application packaging.
XULRunner Hall of Fame - Archive of obsolete content
one example of this tight integration is that the form in a web site can collect payment and set up a login for a members only section.
...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.
How to enable locale switching in a XULRunner application - Archive of obsolete content
here is an example event handler which is fired when the user clicks on the button to change the locale.
...pstartup = components.classes["@mozilla.org/toolkit/app-startup;1"] .getservice(components.interfaces.nsiappstartup); appstartup.quit(components.interfaces.nsiappstartup.erestart | components.interfaces.nsiappstartup.eattemptquit); } catch(err) { alert("couldn't change locale: " + err); } } * * * here i include a complete xulrunner application example that demonstrates the locale switching.
...localeswitchexample.zip (7kb, tested with xulrunner 1.9.0 for linux) ...
Windows and menus in XULRunner - Archive of obsolete content
here is an example: <?xml version="1.0"?> <?xml-stylesheet href="chrome://basicapp/skin/main.css" type="text/css"?> <!doctype window system "chrome://basicapp/locale/main.dtd"> <window id="main" title="&title;" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <script src="main.js"/> ...
...the window title is done this way in the above example.
...xul has a way to centralize commands and event handlers for menus and toolbars that do the same thing, like open and save in the above example.
Archived Mozilla and build documentation - Archive of obsolete content
creating a mozilla extension a mozilla extension is an installable enhancement to the mozilla browser that provides additional functionality (for example linky, which adds an item to the context menu for opening multiple links in a document or selection).
... microsummary topics to programmatically install a microsummary generator -- for example, in an extension that helps users create custom generators for their favorite sites -- obtain a reference to the nsimicrosummaryservice interface implemented by the nsimicrosummaryservice component, then call its installgenerator() method, passing it an xml document containing the generator.
...as a result, mozilla is not fully backwards-compatible with netscape navigator 4.x and microsoft internet explorer legacy code; for example, mozilla does not support <layer> as i will discuss later.
NPAPI plugin developer guide - Archive of obsolete content
for example, the adobe flash plug-in is used to access flash content (including videos and certain interactive applications), and the quicktime and realplayer plugins are used to play special format videos in a web page.
...ug-ins scriptable building plug-ins building, platforms, and compilers building carbonized plug-ins for mac os x type libraries installing plug-ins native installers xpi plug-ins installations plug-in installation and the windows registry initialization and destruction initialization instance creation instance destruction shutdown initialize and shutdown example drawing and event handling the npwindow structure drawing plug-ins printing the plug-in setting the window getting information windowed plug-ins mac os windows unix event handling for windowed plug-ins windowless plug-ins specifying that a plug-in is windowless invalidating the drawing area forcing a paint message making a plug-in opaque...
...r windowless plug-ins streams receiving a stream telling the plug-in when a stream is created telling the plug-in when a stream is deleted finding out how much data the plug-in can accept writing the stream to the plug-in sending the stream in random-access mode sending the stream in file mode sending a stream creating a stream pushing data into the stream deleting the stream example of sending a stream urls getting urls getting the url and displaying the page posting urls posting data to an http server uploading files to an ftp server sending mail memory allocating and freeing memory mac os flushing memory (mac os only) version, ui, and status information displaying a status line message getting agent information ge...
NPN_Write - Archive of obsolete content
see "example of sending a stream" for an example that includes npn_write().
... example this example pushes a snippet of html over a newly created stream, then destroys the stream when it's done.
... note: you should actually handle errors, which this example doesn't do.
NP_GetMIMEDescription - Archive of obsolete content
one mime type // example inside http://mxr.mozilla.org/mozilla-central/source/modules/plugin/sdk/samples/basic/unix/plugin.cpp #define mime_type_description "application/basic-plugin:bsp:basic example plug-in for mozilla" const char* np_getmimedescription(void) { return(mime_types_description); } two mime types const char* np_getmimedescription(void) { return "application/basic-example-plugin:xmp1:example 1;application/basic-example2-plu...
...gin:xmp2, xm2p:example 2"; } gnome integration if you use gnome vfs (gnome-vfs-2.0), you can get the mime type description with a function.
... #include <gio/gio.h> const char* desc = g_content_type_get_description("audio/ogg"); javascript inside a web page, you can retrieve these informations with this code: var mimetype = navigator.mimetypes['application/basic-example-plugin']; if (mimetype) { alert(mimetype.type + ':' + mimetype.suffixes + ':' + mimetype.description); } ...
Why RSS Slash is Popular - Counting Your Comments - Archive of obsolete content
an example using the most popular element of the rss slash module is shown below: <?xml version="1.0"> <rss version="2.0" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" > <channel> <title>example</title> <description>an rss example with slash</description> <lastbuilddate>sun, 15 may 2005 13:02:08 -0500</lastbuilddate> <link>http://w...
...ww.example.com</link> <item> <title>review of sin city</title> <guid>d77d2e80-0487-4e8c-a35d-a93f12a0ff7d:2005/05/15/114</guid> <pubdate>sun, 15 may 2005 13:02:08 -0500</lastbuilddate></pubdate> <link>http://www.example.com/blog/2005/05/15/114</link> <slash:comments>43</slash:comments> </item> <item> <title>what is the 3571st prime number</title> <guid>d77d2e80-0487-4e8c-a35d-a93f12a0ff7d:2005/05/15/113</guid> <pubdate>sun, 15 may 2005 10:55:12 -0500</lastbuilddate></pubdate> <link>d77d2e80-0487-4e8c-a35d-a93f12a0ff7d:2005/05/15/113</link> <slash:comments>72</slash:comments> </item> <item> ...
... <title>first article!</title> <guid>d77d2e80-0487-4e8c-a35d-a93f12a0ff7d:2005/05/15/112</guid> <pubdate>sun, 15 may 2005 08:14:11 -0500</lastbuilddate></pubdate> <link>http://www.example.com/blog/2005/05/15/112</link> <slash:comments>118</slash:comments> </item> </channel> </rss> the <slash:comments> element is it reason that the rss slash module is popular.
Why Well-Formed Web RSS Module is Popular - Syndicating Your Comments - Archive of obsolete content
an example using the most popular element of the well-formed web rss module is shown below: <?xml version="1.0"> <rss version="2.0" xmlns:wfw="http://wellformedweb.org/commentapi/" > <channel> <title>example</title> <description>an rss example with wfw</description> <lastbuilddate>sun, 15 may 2005 13:02:08 -0500</lastbuilddate> <link>http://www.example.com</link> <item> <title>i li...
...ke root beer</title> <guid>d77d2e80-0487-4e8c-a35d-a93f12a0ff7d:article:54321</guid> <pubdate>sun, 15 may 2005 13:02:08 -0500</pubdate> <link>http://www.example.com/article/54321</link> <wfw:commentrss>http://www.example.com/feed/rss/54321/comments</wfw:commentrss> </item> <item> <title>rain is wet</title> <guid>d77d2e80-0487-4e8c-a35d-a93f12a0ff7d:article:54320</guid> <pubdate>sun, 15 may 2005 10:55:12 -0500</pubdate> <link>http://www.example.com/article/54320</link> <wfw:commentrss>http://www.example.com/feed/rss/54320/comments</wfw:commentrss> </item> <item> <title>huh?!</title> <guid>d77d2e80-0487-4e8c-a35d-a93f12a0ff7d:article:54319</guid> <pubdate>sun, 15 may 2005 08:14:11 -0500</pubdate> <link>http://www.example.com/article/54319</link> <...
...wfw:commentrss>http://www.example.com/feed/rss/54319/comments</wfw:commentrss> </item> </channel> </rss> the <wfw:commentrss> element is the reason that the well-formed web rss module is popular.
Making sure your theme works with RTL locales - Archive of obsolete content
example toolbar[iconsize="large"][mode="icons"] #back-button { -moz-image-region: rect(0px 396px 34px 360px); } toolbar[iconsize="large"][mode="icons"] #back-button:-moz-locale-dir(rtl) { -moz-image-region: rect(0px 516px 34px 480px); } this specifies the default, left-to-right version of the button, then offers an override if the user's interface is being rendered in right-to-left mode.
...that's how the default theme works, so you can use it as an example.
...for example: /* we want to apply a rtl rule to #c; neither it nor its * parent element #b has a chromedir attribute, but its * grandparent element #a does.
Scratchpad - Archive of obsolete content
for example, try typing d, then pressing ctrl + space.
...for example, if you type document.addeventlistener, then press ctrl + shift + space, you'll see a popup that shows a summary of the function's syntax and a short description: the "[docs]" link takes you to the mdn documentation for the symbol.
... for example, if you enter the code: window then choose inspect, the object inspector is shown that looks something like this: display the display option executes the selected code, then inserts the result directly into your scratchpad editor window as a comment, so you can use it as a repl.
Using the W3C DOM - Archive of obsolete content
instead, use the w3c dom properties and methods (examples in the next section).
...for example, the following short sample dynamically sets the left margin of a <div> element with an id of "inset" to half an inch: // in the html: <div id="inset">sample text</div> document.getelementbyid("inset").style.marginleft = ".5in"; note: internet explorer 5 through 7 have a flawed implementation of getelementbyid(), which returns the first element with a matching name or id (id versus name when using getelemen...
... the following examples show how to modify the text of a span element that already exists in the html file.
E4X for templating - Archive of obsolete content
createbundle('chrome://myeext/locale/myext.properties'); if (args){ args = array.prototype.slice.call(arguments, 1); return strs.formatstringfromname(msg,args,args.length); } return strs.getstringfromname(msg); } for example, <toolbarbutton label={$s('mytoolbar.label')}/> conditionals function _if (cond, h, _else) { if (cond && cond != undefined) { // we need undefined condition for e4x return h(cond); } else if (_else) { return _else(cond); } return ''; // empty string allows conditions in attribute as well as element content } for example: {_if(elems.length(), function () <...
...ams; otherwise define with more than one param (see below) ++it; } } else { for (k in arr) { if (it < min) { ++it; continue; } if (it > max) { break; } ret+=h(k, arr[k], it, lev); ++it; } } return ret; } the following real case example iterates over an array of the lines in an e4x child element to produce an xmllist of multiple vbox's representing each line: <vbox> {foreach(e(someel.somechild[0]).split('\n'), function (line) <description>{line}</description> )} </vbox> the following example shows iteration over an e4x object itself: {foreach(elems, function (k, elem, iter) <> <row>{k}: {elem}</row> <row><image s...
... arr.push(xmllist[k]); } } arr.sort(h).foreach(function (item) { if (typeof item === 'xml') { ret += item; } else if (typeof item === 'string') { ret += new xml(item); } else { var ser = (new xmlserializer()).serializetostring(item); ret += new xml(ser); } }); return ret; } example: var fruits = <fruits> <item>pear</item> <item>banana</item> <item>grapes</item> </fruits>; alert( // using a javascript 1.8 expression closure <output> {sort(fruits.*, function (a, b) a.text() > b.text() /* text() call may not be necessary */ )} </output>.toxmlstring() ); /* <output> <item>banana</item> <item>grapes</item> <item>pear</item> </output> */ the above utilit...
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 inheri...
...i][name].apply(this, args); } } // if we get here, the method hasn't been found throw new typeerror; } // used to add a parent for multiple inheritance function addparent(obj, parent) { // if the object isn't initialized, initialize it if (!obj.__parents_) { obj.__parents_ = []; obj.__nosuchmethod__ = nomethod; } // add the parent obj.__parents_.push(parent); } an example of using this idea is shown below.
... // example base class 1 function namedthing(name) { this.name = name; } namedthing.prototype = { getname: function() { return this.name; }, setname: function(newname) { this.name = newname; } } // example base class 2 function agedthing(age) { this.age = age; } agedthing.prototype = { getage: function() { return this.age; }, setage: function(age) { this.age = age; } } // child class.
Object.prototype.watch() - Archive of obsolete content
for example, window.watch('location', myhandler) will not call myhandler if the user clicks a link to an anchor within the current document.
... 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 object's properties you can use watch to test any assignment to an object's properties.
... this example ensures that every person always has a valid name and an age between 0 and 200.
JavaArray - Archive of obsolete content
for example: var javastring = new java.lang.string("hello world!"); var bytearray = javastring.getbytes(); bytearray[0] // returns 72 bytearray[1] // returns 101 any java data brought into javascript is converted to javascript data types.
... 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.
... var javastring = new java.lang.string("hello world!"); var bytearray = javastring.getbytes(); example: instantiating a javaarray in javascript with the newinstance method in javascript 1.4, you can use a javaclass object as the argument for the newinstance method which creates the array, as shown in the following code: var dogs = java.lang.reflect.array.newinstance(java.lang.string, 5); in javascript 1.1, use a class object returned by java.lang.class.forname as the argument for the newinstance method, as shown in the following code: var datatype = java.lang.class.forname("java.lang.string"); var dogs = java.lang.reflect.array.newinstance(datatype, 5); ...
JavaClass - Archive of obsolete content
examples example: using javaclass in the following example, x is a javaclass object referring to java.awt.font.
... x = java.awt.font; myfont = x("helv", x.bold, 10); // creates a font object the previous example omits the packages keyword and uses the java synonym because the font class is in the java package.
... example in the following example, the javaclass object java.lang.string is passed as an argument to the newinstance method which creates an array: var cars = java.lang.reflect.array.newinstance(java.lang.string, 15); see also javaarray, javaobject, javapackage, packages ...
JavaPackage - Archive of obsolete content
for example, the netscape package contains the package netscape.javascript; the netscape.javascript package contains the classes jsobject and jsexception.
...for example, a reference to netscape is a javapackage.
... examples suppose the redwood corporation uses the java redwood package to contain various java classes that it implements.
background-size - Archive of obsolete content
some example code?
...here's a slightly more complex example (screenshot), and the same page without the -moz-border-image image rule (screenshot).
... 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.
Writing JavaScript for XHTML - Archive of obsolete content
(note that xhtml documents which behave correctly in both application/xhtml+xml and text/html environments are sometimes known as 'polyglot' documents.) to test the following examples locally, use firefox's extension switch.
...for example: var string = '<div xmlns="http://www.w3.org/999/xhtml"><h1>hello world!</h1></div>'; var parser = new domparser(); var documentfragment = parser.parsefromstring(string, "text/xml"); body.appendchild(documentfragment); // assuming 'body' is the body element but be aware that if your string is not well-formed xml (e.g., you have an & where it should not be), then this method will crash, leaving...
... in php, for example, you would write something like this: if( strpos( $_server['http_accept'], "application/xhtml+xml" ) ) { header( "content-type: application/xhtml+xml" ); echo '<?xml version="1.0" ?>'."\n"; } else { header( "content-type: text/html" ); } this distinction also sends the xml declaration, which is strongly recommended, when the document is an xml file.
Mozilla XForms User Interface - Archive of obsolete content
for example, a xforms input control may appear as a text field or as a datepicker depending on whether it is bound to a xsd:string type or a xsd:date type.
...binding these elements to instance data is also a way to apply model item properties (for example, relevancy) to the elements.
...for example, if a repeat is bound to a nodeset that contains 5 nodes and the repeat contains an output element that echoes the current node, then the user will see 5 outputs in the form.
The Business Benefits of Web Standards - Archive of obsolete content
while some browsers have quirks that cause different behavior by platform, mozilla-based browsers are designed to behave identically on all supported platforms (mac, linux, unix, windows...) web content is increasingly being accessed by a growing number of user agents other than browsers, or by browsers on different platforms - for example mobile telephones.
...it does not follow for example that successful business users have wide monitors.
...they act as a very good example of real separation not only of style and content but the process by which those items - which are very different - are implemented.
Game promotion - Game development
and you can use your own game as an example, especially in a tutorial when you're showing how to do something you've implemented already.
... events if you've gone through all the options listed above you can still find new, creative ways to promote your game — events are another good example.
... conferences there are many conferences where you can give a talk explaining some technical difficulties you overcame, or how you implemented specific apis; again — use your games as examples for that.
2D collision detection - Game development
this.color("green"); } else { // no collision this.color("blue"); } }); note: another example without canvas or external libraries.
...} note: here is another example without canvas or external libraries.
...some examples of spacial data structures are quad trees, r-trees or a spacial hashmap.
Explaining basic 3D theory - Game development
you can build geometry using this information — here is an example of a cube: a face of the given shape is a plane between vertices.
... for example, a cube has 8 different vertices (points in space) and 6 different faces, each constructed out of 4 vertices.
... during output merging some processing is also applied to ignore information that is not needed — for example the parameters of objects that are outside of the screen or behind other objects, and thus not visible, are not calculated.
Building up a basic demo with Babylon.js - Game development
the first <script> element includes the babylon.js library in the page; we will write our example code in the second one.
...the good thing about objects is that we can move them on the scene however we want, for example rotating and scaling.
... conclusion here's the final code listing, along with a viewable live example: you can also see it on github and fork the repository if you want to play with it yourself locally.
Building up a basic demo with Three.js - Game development
the first <script> element includes the three.js library in the page, and we will write our example code inside the second.
...we could set a fixed ratio — for example 16 ⁄ 9, which is the aspect ratio of a widescreen tv.
...for example, rotating and scaling as we like.
Unconventional controls - Game development
if all else fails, there's also a gallery of working examples you can look at.
...the last value is grabstrength, which is a float between 0 and 1 — when reaching 1 (fist fully clenched), we show an alert for now (in a full game this could be replaced with the shooting logic.) that's it — everything you needed for a working leap motion example in javascript is here already.
... proximity api another interesting idea is to use the built-in proximity sensors of your hardware to detect how far an object, for example a hand, is from the given sensor.
Implementing controls using the Gamepad API - Game development
the index variable is useful if we're connecting more than one controller and want to identify them to act accordingly — for example when we have a two-player game requiring two devices to be connected.
...for example, the fridge tank will turn right only when the x value is bigger than 0.5: if(gamepadapi.axesstatus[0].x > 0.5) { this.player.angle += 3; this.turret.angle += 3; } even if we move it a little by mistake or the stick doesn't make it back to its original position, the tank won't turn unexpectedly.
... getting the gamepads the navigator.getgamepads() method has been updated with a longer explanation and an example piece of code.
Crisp pixel art look with image-rendering - Game development
if the canvas was created with a 128 pixel width, for example, we would set the css width to 512px if we wanted a 4x scale.
... an example let's have a look at an example.
...text var ctx = document.getelementbyid('game').getcontext('2d'); // load image var image = new image(); image.onload = function () { // draw the image into the canvas ctx.drawimage(image, 0, 0); } image.src = 'https://udn.realityripple.com/samples/11/a2954fe197.png'; this code used together produces the following result: note: you can check out the original code on github (and a live example.) ...
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-lo...
... see register and login example.
... create examples demos in minimum 20 gameplay variants (table games, actions, platformers, basic demo throw the api doc etc.).
Client hints - MDN Web Docs Glossary: Definitions of Web-related terms
for example, based on accept-ch example above, the client could append dpr, width, viewport-width, and downlink headers to all subsequent requests.
... in the second example, the server gives the browser the hints by setting the accept-ch meta tag.
... example varying response: vary: accept, dpr, width, viewport-width, downlink see also client hints headers vary http header ...
Grid Lines - MDN Web Docs Glossary: Definitions of Web-related terms
in the following example there is a grid with three column tracks and two row tracks.
...lines numbers respect the writing mode of the document and so in a right-to-left language for example, column line 1 will be on the right of the grid.
...in the following example the item is positioned from column line 1 to column line 3, and from row line 1 to row line 3.
Polyfill - MDN Web Docs Glossary: Definitions of Web-related terms
for example, a polyfill could be used to mimic the functionality of an html canvas element on microsoft internet explorer 7 using a silverlight plugin or mimic support for css rem units, or text-shadow, or whatever you want.
...for example, the object.create polyfill only contains the functionalities that are possible in a non-native implementation of object.create.
...the 1st version of jquery was an early example of a polyfill.
SLD - MDN Web Docs Glossary: Definitions of Web-related terms
for example, in mozilla.org, mozilla is the second-level domain of the .org tld.
...for example, www is a commonly used subdomain to indicate the domain points to a web server.
... as another example, in developer.mozilla.org, the developer subdomain is used to specify that the subdomain contains the developer section of the mozilla website.
Second-level Domain - MDN Web Docs Glossary: Definitions of Web-related terms
for example, in mozilla.org, mozilla is the second level domain of the .org tld.
...for example, www is a commonly used subdomain to indicate the domain points to a web server.
... as another example, in developer.mozilla.org, the developer subdomain is used to specify that the subdomain contains the developer section of the mozilla website.
Semantics - MDN Web Docs Glossary: Definitions of Web-related terms
in programming, semantics refers to the meaning of a piece of code — for example "what effect does running that line of javascript have?", or "what purpose or role does that html element have" (rather than "what does it look like?".) semantics in javascript in javascript, consider a function that takes a string parameter, and returns an <li> element with that string as its textcontent.
... semantics in html in html, for example, the <h1> element is a semantic element, which gives the text it wraps around the role (or meaning) of "a top level heading on your page." <h1>this is a top level heading</h1> by default, most browser's user agent stylesheet will style an <h1> with a large font size to make it look like a heading (although you could style it to look like anything you wanted).
...blocks of meaningful code is significantly easier than searching though endless divs with or without semantic or namespaced classes suggests to the developer the type of data that will be populated semantic naming mirrors proper custom element/component naming when approaching which markup to use, ask yourself, "what element(s) best describe/represent the data that i'm going to populate?" for example, is it a list of data?; ordered, unordered?; is it an article with sections and an aside of related information?; does it list out definitions?; is it a figure or image that needs a caption?; should it have a header and a footer in addition to the global site-wide header and footer?; etc.
Symbol - MDN Web Docs Glossary: Definitions of Web-related terms
for example: // here are two symbols with the same description: let sym1 = symbol("sym") let sym2 = symbol("sym") console.log(sym1 === sym2) // returns "false" // symbols are guaranteed to be unique.
... for example: let sym = symbol("sym") alert(sym) // typeerror: cannot convert a symbol value to a string that’s a "language guard" against messing up, because strings and symbols are fundamentally different, and should not occasionally convert one into another.
... examples of well-known symbols are: symbol.iterator for array-like objects, or symbol.search for string objects.
Test your skills: The Cascade - Learn web development
in the example below see if you can match the image above.
... assessment or further help you can practice these examples in the interactive editors mentioned above.
... a link to the example you want to be assessed or need help with, in an online shareable editor (as mentioned in step 1 above).
Fundamental CSS comprehension - Learn web development
this could affect the values you need, although in this simple example this is not an issue.) other things to think about: you'll get bonus marks if you write your css for maximum readability, with a separate declaration on each line.
... example the following screenshot shows an example of what the finished design should look like: assessment or further help if you would like your work assessed, or are stuck and want to ask for help: put your work into an online shareable editor such as codepen, jsfiddle, or glitch.
... a link to the example you want assessed or need help with, in an online shareable editor (as mentioned in step 1 above).
CSS first steps - Learn web development
css (cascading style sheets) is used to style and lay out web pages — for example, to alter the font, color, size, and spacing of your content, split it into multiple columns, or add animations and other decorative features.
... 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.
...this article explains what css is, with a simple syntax example, and also covers some key terms about the language.
Using CSS generated content - Learn web development
for example, you might have different language versions of your document that share a stylesheet.
... examples text content css can insert text content before or after an element.
...for example, "\265b" is the chess symbol for a black queen ♛.
How do you make sure your website works properly? - Learn web development
let's look at our personal website, http://demozilla.examplehostingprovider.net/.
... frequent errors the most frequent errors that we find are these: typos in the address we wanted to type http://demozilla.examplehostingprovider.net/ but typed too fast and forgot an “l”: the address cannot be found.
... open the console (tools ➤ web developer ➤ web console) and reload the page: in this example, we learn (quite clearly) what the error is, and we can go fix it (we will cover javascript in another series of articles).
How do I use GitHub Pages? - Learn web development
on this page, in the repository name box, enter a name for your code repository, for example my-repository.
... go to the github pages section again, and you should see a line of the form "your site is ready to be published at https://xxxxxx." if you click on this url, you should go to a live version of your example, provided the home page is called index.html — it goes to this entry point by default.
... if your site's entry point is called something else, for example mypage.html, you'll need to go to https://xxxxxx/mypage.html.
What are browser developer tools? - Learn web development
note: before you run through the examples below, open the beginner's example site that we built during the getting started with the web article series.
...in example.js, a breakpoint has been set on the statement listitems.push(inputnewitem.value); the final two sections only appear when the code is running.
...for example, in the image below, you can see the objects available to the code in the additemclick function.
What is a web server? - Learn web development
(for example, html documents, images, css stylesheets, and javascript files) a web server connects to the internet and supports physical data interchange with other devices connected to the web.
... for example, to produce the final webpages you see in the browser, the application server might fill an html template with content from a database.
...for example, relying on http alone, a server can't remember a password you typed or remember your progress on an incomplete transaction.
Test your skills: Form validation - Learn web development
form validation 3 in our final task for this set, we are providing you with a similar example to what you saw in the accompanying article — a simple email address entry input.
... assessment or further help you can practice these examples in the interactive editors above.
... a link to the example you want assessed or need help with, in an online shareable editor (as mentioned in step 1 above).
Getting started with the Web - Learn web development
for example, is my content a set of paragraphs or a list of bullet points?
...for example, do you want the text to be black or red?
...some examples could be games, things that happen when buttons are pressed or data is entered in forms, dynamic styling effects, animation, and much more.
Add a hitmap on top of an image - Learn web development
then assign that name (preceded by a hash) as the value for the usemap attribute: <img src="image-map.png" alt="" usemap="#example-map-1" /> step 2: activate your hotspots in this step, put all your code inside a <map> element.
... <map> only needs one attribute, the same map name as you used in your usemap attribute above: <map name="example-map-1"> </map> inside the <map> element, we need <area> elements.
... <map name="example-map-1"> <area shape="circle" coords="200,250,25" href="page-2.html" alt="circle example" /> <area shape="rect" coords="10, 5, 20, 15" href="page-3.html" alt="rectangle example" /> </map> step 3: make sure it works for everybody you aren’t done until you test image maps rigorously on many browsers and devices.
Structuring a page of content - Learn web development
create the example on your local computer, or alternatively use an online tool such as codepen, jsfiddle, or glitch to work on the tasks.
... example the following screenshot shows an example of what the homepage might look like after being marked up.
... a link to the example you want assessed or need help with, in an online shareable editor (as mentioned in step 1 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.
... a link to the example you want assessed or need help with, in an online shareable editor (as mentioned in step 1 above).
Solve common problems in your JavaScript code - Learn web development
for example: correct wrong elem.style.color = 'red'; elem.style.color = 'red;' functions there are a number of things that can go wrong with functions.
...for example: function myfunction() { alert('this is my function.'); }; this code won't do anything unless you call it with the following statement: myfunction(); function scope remember that functions have their own scope — you can't access a variable value set inside a function from outside the function, unless you declared the variable globally (i.e.
...for example: const myobject = { name: 'chris', age: 38 } basic definitions what is javascript?
Multimedia: Images - Learn web development
examples for these types of motifs are logos, illustrations, charts or icons (note: svgs are far better than icon fonts!).
...an example use case for priority hints on images are carousels where the first image is a higher priority than the subsequent images.
...for example, when text gets pushed down the page by images loading.
Getting started with Ember - Learn web development
for example, the router (which will be mentioned later in this tutorial) is a service.
... examples include: prember: static website rendering for blogs or marketing content.
... first, enter into your todomvc directory in the terminal, for example using cd todomvc in macos/linux.
Componentizing our Svelte app - Learn web development
easier two-way data binding with the bind directive in the previous example we realized that our filterbutton component wasn't working because our application state was flowing down from parent to child through the filter prop — but it wasn't going back up.
...so in the above example you could just write <filterbutton bind:filter />.
... when editing is true, for example, svelte will show the update form; when it's false, it will remove it from the dom and add in the checkbox.
Working with Svelte stores - Learn web development
for example, information about the logged in user, or whether the dark theme is selected or not.
... this is a perfect example of how svelte puts the compiler in charge of better developer ergonomics, not only saving us from typing boiler plate, but also generating less error-prone code.
...in the following example we create a counter store, which will only allow us to add one to the counter or reset its value: import { writable } from 'svelte/store'; function mystore() { const { subscribe, set, update } = writable(0); return { subscribe, addone: () => update(n => n + 1), reset: () => set(0) }; } if our to-do list app gets too complex, we could let our todos store handle every state mod...
Learn web development
random glossary entry semantics in programming, semantics refers to the meaning of a piece of code — for example "what effect does running that line of javascript have?", or "what purpose or role does that html element have" (rather than "what does it look like?".) topics covered the following is a list of all the topics we cover in the mdn learning area.
... getting our code examples the code examples you'll encounter in the learning area are all available on github.
...for example, if you were in the parent directory: cd learning-area update the repository using the following command: git pull contact us if you want to get in touch with us about anything, the best way is to drop us a message on our discourse forum.
CSUN Firefox Materials
for example, it is possible to navigate to the desired link by pressing 2 letter keys rather than tabbing through many links to get there.
...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.
...for example, ibm has delivered over 50,000 lines of code to enable accessibility in firefox on windows and especially for this new powerful world of "web applications".
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 allow...
...for example to make a capital letter, first press the shift key, release it, then press the letter to be capitalized.
...for example, one application might display the image of a light bulb to indicate that it is processing a task, while another might display it as an indicator that it has completed processing a task.
Adding a new event
make new event class ipc aware for example, new class is caused by native user input event and needed to be dispatch to content, the class should be able to cross process boundary.
...for example, keyboardevent which is defined in dom level 3 events should be implemented as mozilla::dom::keyboardevent.
...please refer existing dom event implementation for example.
Creating JavaScript callbacks in components
here is a very simple example of the observer pattern: [scriptable, uuid(...)] interface stringparserobserver { void onword(string word); }; [scriptable, uuid(...)] interface stringparser { void parse(string data); void addobserver(stringparserobserver observer); }; in this example, the stringparser will call the stringparserobserver.onword method whenever it finishes parsing a word found in the raw string data.
... 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.
...so we could convert the example above to accept javascript functions in place of the stringparserobserver by making the following changes: [scriptable, function, uuid(...)] interface stringparserobserver : nsisupports { void onword(string word); }; [scriptable, uuid(...)] interface stringparser { void parse(string data); void addobserver(stringparserobserver observer); }; note the only change was adding function to the...
Creating a Login Manager storage module
so for example, on kde is is desirable to fully employ the kde wallet manager, rather than any secondary replacements of kdewallet.
... const cc = components.classes; const ci = components.interfaces; components.utils.import("resource://gre/modules/xpcomutils.jsm"); function sampleloginmanagerstorage() {} sampleloginmanagerstorage.prototype = { classdescription: "sample nsiloginmanagerstorage implementation", contractid: "@example.com/login-manager/storage/sample;1", classid: components.id("{364a118c-747a-4f6d-ac63-2d2998e5a5c1}"), queryinterface: xpcomutils.generateqi([ci.nsiloginmanagerstorage]), // this registers the category for overriding the built-in nsiloginmanagerstorage _xpcom_categories: [ { category: "login-manager-storage", entry: "nsiloginmanagerstorage" } ], // console loggin...
...ts); }, findlogins: function slms_findlogins(count, hostname, formsubmiturl, httprealm) { this.stub(arguments); }, countlogins: function slms_countlogins(ahostname, aformsubmiturl, ahttprealm) { this.stub(arguments); } }; function nsgetmodule(compmgr, filespec) xpcomutils.generatemodule([sampleloginmanagerstorage]); sample c++ implementation bug 309807 contains a complete example.
HTTP logging
here is an example for the windows platform, on other platforms we accept the same form of the arguments: if firefox is already running, exit out of it.
... so we have added a 'rotate:size_in_mb' option to moz_log (we use it in the examples above).
...for example: def environment(...
Old Thunderbird build
for example, to create a debug build instead of a release build, that file would contain: ac_add_options --enable-debug for more on configuration options, see the page configuring build options.
...for example, a mac user may get an object directory name of obj-x86_64-apple-darwin10.7.3/.
...you should copy the header files to a windows sdk include directory so that the build process will find the files, for example to c:\program files (x86)\windows kits\8.1\include\shared and/or c:\program files (x86)\windows kits\10\include\10.0.nnnnn.0\shared respectively, where nnnnn is the highest number present on the system.
Simple Thunderbird build
for example, to create a debug build instead of a release build, that file would also contain the line: ac_add_options --enable-debug each of these ac_add_options entries needs to be on its own line.
...for example, a mac user may get an object directory name of obj-x86_64-apple-darwin10.7.3/.
...for example, to just rebuild the lightning calendar extension: ./mach build comm/calendar/lightning for all other changes run the full rebuild: ./mach build problems building?
Commenting IDL for better documentation
example this is an example of what the sample interface document idl would look like: /** * @brief a make-believe interface that eats and enjoys cookies.
... this is an * example of what an interface document should look like; however, it's not a * document about a real interface.
... * * @note the article's name should be simply "nsicookiemonster" but is not in * order to make it more obvious this is an example.
mach
here are some examples: # use an explicit mozconfig file.
... for example: $ cd devtools/client $ mach build webconsole # rebuild only the files in the devtools/client/webconsole directory $ mach mochitest webconsole/test # run mochitests in devtools/client/webconsole/test enable tab completion to enable tab completion in bash, run the following command.
...for example, bugs in the build command should be filed against firefox build system :: general.
Message manager overview
process scripts are most likely to be useful when an extension wants to run some code only once in the content process, to access some global service: for example, to register an observer or a content policy.
... you can mix and match: so for example, you could load a script into every tab using the global message manager, but then send a message to the script instance loaded into a specific tab by using the browser message manager.
...this is the recommended way to load a script that executes just once per child process, which is something you might want to do if you are interacting with some global service (for example, adding listeners to observer notifications or registering a content policy).
Message manager overview
process scripts are most likely to be useful when chrome code wants to run some code only once in the content process, to access some global service: for example, to register an observer or a content policy.
... you can mix and match: so for example, you could load a script into every <browser> using the global message manager, but then send a message to the script instance loaded into a specific <browser> using the browser message manager.
...this is the recommended way to load a script that executes just once per child process, which is something you might want to do if you are interacting with some global service (for example, adding listeners to observer notifications or registering components).
Firefox UI considerations for web developers
one example is the new tab page, which includes a "top sites" section showing sites you visit that firefox thinks you're likely to want to visit again, as well as potentially some sites that have been pinned to always appear in that space.
... 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).
... that image is then scaled down to be 96 pixels wide and is used in the user interface as seen in the example.
Using the Browser API
MozillaGeckoChromeAPIBrowser APIUsing
for example: function canmovebwd() { browser.getcangoback().then(function(result) { if (result) { back.disabled = false; console.log("it's possible to navigate the history backward."); } else { back.disabled = true; console.log("it's not possible to navigate the history backward."); } }); } implementing the url bar the url bar for our simple browser is a <form> cont...
...for example, 1.1 would mean "zoom in by 10%", and 0.9 would mean "zoom out by 10%".
...when the front page of https://developer.mozilla.org is loaded, for example, the e.detail.backgroundcolor value reported is rgb(0, 83, 159).
HTMLIFrameElement.executeScript()
http://example.com url: a url, e.g.
... http://example.com/index.html note: the options parameter does not currently seem to have much effect.
... 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.log(request2.result); // 6 } if the script value is a not a promise, it is simply returned as the request value.
mozbrowserloadend
can be used to make the theme of the surrounding ui complement the theme of the currently loaded content, for example.
... example in this example the mozbrowserloadstart and mozbrowserloadend events are used to change the icon shown on the stop/reload button between stop (x) and reload (r), as appropriate.
...when the front page of https://developer.mozilla.org is loaded, for example, the e.detail.backgroundcolor value reported is rgb(0, 83, 159).
Browser API
mozbrowseropentab sent when a new tab is opened within a browser <iframe> as a result of the user issuing a command to open a link target in a new tab (for example ctrl/cmd + click.) mozbrowserresize sent when the browser <iframe>'s window size has changed.
...this can occur on resize and when the page size changes (while loading for example.) mozbrowserscrollviewchange sent when asynchronous scrolling (i.e.
... mozbrowservisibilitychange sent when the visibility state of the current browser iframe <iframe> changes, for example due to a call to setvisible().
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.
...uses winapi example.
Geckoview-Junit Tests
for example: <class1>#<test1> <class2> <class3>#<test2> <class3>#<test3> to run the tests specified in the file: mozilla-central$ mach geckoview-junit --test-filters-file <path-to-filter-file> disabling one failing test there is no manifest listing the geckoview junit tests.
...for example: import org.junit.ignore ...
...for example: import org.junit.assume.assumethat ...
How to add a build-time test
a simple example of adding a test is in .
...(example to run the testcookie program) in the test program: if the test fails, exit with a non-zero status and/or print the string "fail" to stdout if the test passes, exit with a zero status and don't print the string "fail" (bonus points for printing "pass" :) ) write the test so that you expect it to pass on all platforms, since if the test fails, the tree will go orange (once we've set this up - see bug 352240 f...
... for example, to add an xpcshell test to a module, do the following: copy tools/test-harness/xpcshell-simple/example to yourmoduledir/tests_type, wheretests_type is something that describes your tests.
IME handling guide
for example, if a user types "watasinonamaehanakanodesu", it's converted to hiragana characters, "わたしのなまえはなかのです", automatically (in the following screenshots, the composition string has a wavy underline and the only one clause is called "raw input clause").
...for example, if widgetkeyboardevent should be dispatched when there is a composition is managed by this class in xp level.
...for example, pressing the space key to attempt scrolling a page may be consumed and prevented by ime.
PBackground
pbackground is a mechanism available since gecko 30 (see bug 956218) that builds on top of ipdl to provide a solution to common problems that arise when handling multiple threads in the chrome process, for example communication between workers and multiple child processes and other parent-process worker threads.
... for example, when we are uploading textures from the content process we don't need to go through the main thread of the parent process.
... examples indexeddb was rebuilt on top of pbackground last year.
Internationalized Domain Names (IDN) Support in Mozilla Browsers
as an example, an output string to be sent to a dns server for a japanese domain name, "http://ジェーピーニック.jp", will look like the following in ace form: http://xn--hckqz9bzb1cyrb.jp domain name registration after the technical standards were established by ietf, the last remaining issue was for domain name registrars to agree on an international guideline on the use of idn characters.
... real world examples punycode there are real world examples of idn that you can test with netscape 7.1, which uses punycode as the default idn encoding.
... for example, most sample links on the following test pages can be used without any further setting: http://www.nunames.nu/eu-lang-test.htm (domain names with latin 1 accented characters) http://www.nunames.nu/lldemo/default.htm (domain names in other languages) on july 10, 2003 and thereafter, you can access a large number of japanese domain name sites under the .jp top domain with no further setting on netscape 7.1/mozilla 1.4: http://mitsuketa-nihongo.jp race (row-based ascii compatible encoding) almost all idn registration data are expected to change to punycode by the end of 2003.
AsyncShutdown.jsm
example at some point during shutdown, the add-on manager needs to ensure that all add-ons have safely written their data to disk, before writing its own data.
...// collect any information that may be useful for debugging shutdown issues with this blocker return status; } }); in this example, at some point during phase profilebeforechange, function condition will be called.
... 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() { // ...
DeferredTask.jsm
if a special operation or error logging is needed on completion, it can be better handled from within the task itself, for example using a try/catch/finally clause in the task.
... promise finalize(); example firefox 28 note this section describes about deferredtask.jsm in firefox 28.0 or higher.
... for example, during shutdown, you may want to ensure that any pending write is processed, using the latest version of the data if the timer is armed: asyncshutdown.profilebeforechange.addblocker( "example service: shutting down", () => savedeferredtask.finalize() ); instead, if you are going to delete the saved data from disk anyways, you might as well prevent any pending write from starting, while st...
FxAccountsOAuthClient.jsm
example: "https://oauth.accounts.firefox.com/v1" content_uri - the fxa content server uri.
... example: "https://accounts.firefox.com" [optional] scope - a colon-separated list of scopes that the user has authorized.
...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.la...
Http.jsm
for example: [["key1", "value1"], ["key2", "value2"]].
...for example, xhr might be configured to use any custom mime-type when processing a response regardless of what the server returns.
...another example of how this can be used can be found here.
Promise.jsm
a reference to an existing promise may be received by different means, for example as the return value of a call into an asynchronous api.
...for example, unhandled exceptions in the callbacks cause the new promise to be rejected, even if the original promise is fulfilled.
... examples see the examples page.
Index
for example, "1 page" vs "2 pages".
...an example of a cultural reference in english would be the phrase, "kick-off meeting." this is a reference that uses an american football term.
...all we ask is that you name this page according to this example, "mozilla content in spanish (es-mx)" and add your locale code tag at the bottom.
Localizing with Mercurial
see the screenshot for an example.
... your config file should have the following settings: [ui] username = your real name <user@example.com> merge = internal:merge [defaults] commit = -v [diff] git = 1 showfunc = 1 unified = 8 to configure hg, follow these steps: create a new file in your favorite text editor.
...for example, to clone your firefox nightly l10n repo, run the following command, replacing ab-cd with your locale code: hg clone https://hg.mozilla.org/l10n-central/ab-cd/ updating your local repos to update your working copy of mozilla-central, go to your local mozilla-central directory and run: hg pull -u this will both get new changesets from mozilla-central and apply those changes in your worki...
Localizing with Mozilla Translator
see the following example.
...see this example for browser.
... defining symbolic links for browser this is an example just for browser, without shared components, but it should suffice to get the idea.
Patching a Localization
i'll use firefox in the example below to help you understand the general steps to creating a l10n patch.
...for our example, i'll use gl (galician).
...for example, create a directory like localization-workdir (in this example it is located in your home directory): mkdir ~/localization-workdir navigate to the directory you just created.
Basics
the following example shows the i-th step of the multiplication of a matrix a by a vector x (notice how ai1 , ...
... mathml button html content <div style="text-align: center"> <button style="white-space: normal;"> <span style="color: brown;"> for example, <b>click</b> this mathml continued fraction<br/> inside this html button<br /> </span> <math> <mrow> <mfrac> <mi>&pi;</mi> <mn>4</mn> </mfrac> <mo>=</mo> <mfrac numalign="left"> <mstyle scriptlevel="0"> <mn>1</mn> </mstyle> <mstyle scriptlevel="0"> <mrow> <mn>2</mn> <mo>+</mo> <mfrac numalign="left"> <mstyle scriptlevel="0"> <msup><mn>1</mn><mn>2</mn></msup> </mstyle> <mstyle scriptl...
...these fonts are required to view other examples beyond the basic constructions illustrated here.
Refcount tracing and balancing
for example: env xpcom_mem_log_classes=nsdocshell xpcom_mem_refcnt_log=./refcounts.log ./mach run this will log the addref and release calls only for instances of nsdocshell while running the browser using mach, to a file refcounts.log.
...for example, env xpcom_mem_log_classes=nsdocshell xpcom_mem_log_objects=2 xpcom_mem_refcnt_log=./refcounts.log ./mach run will log stack traces to refcounts.log for the 2nd nsdocshell object that gets allocated, and nothing else.
...for example: perl -w tools/rb/make-tree.pl --object 0x00253ab0 < my-leak.log this will build an indented tree that looks something like this (except probably a lot larger and leafier): .root: bal=1 main: bal=1 dosomethingwithfooandreturnittoo: bal=2 ns_newfoo: bal=1 let's pretend in our toy example that ns_newfoo() is a factory method that makes a new foo and returns it.
Patches and pushes
here is an example search plugin file using french yahoo.
...json&amp;command={searchterms}" />*** <url type="text/html" method="get" template="http://search.yahoo.com/search"> <param name="p" value="{searchterms}"/> <param name="ei" value="utf-8"/> <mozparam name="fr" condition="pref" pref="yahoo-fr" /> </url> <searchform>http://search.yahoo.com/</searchform> </searchplugin> create xml files for each search plugin preference following the above example.
...for example: hg ci -m "bug 654321, copied the comment from the doc without reading, r=nobody" path-to-changed-files close the bug, copying the url to your change in the closing comment.
L20n HTML Bindings
<link rel="localization" href="../locales/manifest.json"> an example of the manifest file (all keys are required): { "locales": [ "en-us", "pl"], "default_locale": "en-us", "resources": [ "../locales/{{locale}}/strings.l20n", "/shared/{{locale}}/date.l20n"¨ ] } make html elements localizable use the data-l10n-id attribute on an html element to mark it as localizable.
...for instance, a string could use the information about the user's gender to provide two variants of the translation, like in the example below.
... see l20n by example to learn more about l20n's syntax.
L20n
what l20n looks like here is a simple, straightforward example showing an english string being provided: <brandname "firefox"> <about "about {{ brandname }}"> here is the same string being provided in slovenian: <brandname { nominative: "firefox", genitive: "firefoxa", dative: "firefoxu", accusative: "firefox", locative: "firefoxu", instrumental: "firefoxom" }> <about "o {{ brandname.locative }}"> for developers documentation for devel...
...complete with use cases and examples of l20n in action.
...complete with use cases and examples of l20n in action.
NSPR Contributor Guide
new features for purposes of this paper, a "new feature" is defined as some api addition that goes into the core nspr library, for example: libnspr4.dll nspr is mostly complete.
...see: prshm.h as an example of how your header file(s) should be documented.
...test cases should serve as an example of how to use the api items.
I/O Functions
nspr converts the slashes in a pathname to the directory separator of the native os--for example, backslash (\) on windows and colon (:) on mac os--before passing it to the native system calls.
...for example, ssl is a layer on top of a reliable bytestream layer such as tcp.
...for example, the following lines of code are equivalent: rv = pr_pushiolayer(stack, pr_top_io_layer, my_layer); rv = pr_pushiolayer(stack, pr_getlayersidentity(stack), my_layer); pr_getuniqueidentity pr_getnameforidentity pr_getlayersidentity pr_getidentitieslayer pr_getdefaultiomethods pr_createiolayerstub pr_pushiolayer pr_popiolayer ...
Introduction to NSPR
some operating systems cannot be made preemptable (for example, mac os and win 16).
... a trivial example might be as follows.
... for example, suppose the defined rule of a function is that it should wait until there is an object available and that it should return a reference to that object.
NSPR Types
a typical example is a function implemented in an application but called from a shared library.
... 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 32-bit integer types 64-bit integer types floating-point number type for convenience, nspr also provides type definitions with platform-dependent bit widths: native os integer types 8-, 16-, and 32-bit integer types signed integers print8 print16 print32 unsigned integers pruint8 pruint16 pruint32 64-bit integer types different platforms treat 64-...
...they are guaranteed to be at least 16 bits, though various architectures may define them to be wider (for example, 32 or even 64 bits).
PRIOMethods
for example, the write method in priomethods implements the pr_write function.
...if a layer provides no functionality, it should call the next lower (higher) function of the same name (for example, the "close" method would return fd->lower->method->close(fd->lower)).
...for example, the seek method is implemented for normal files but not for sockets.
PR_NormalizeTime
for example, if you have a ] object that represents the date 3 march 1998 and you want to say "forty days from 3 march 1998", you can simply add 40 to the tm_mday field and then call pr_normalizetime().
...for example, suppose you want to compute the day of week for 3 march 1998.
...for example, if the input argument time is in time zone a and the input argument params represents time zone b, when pr_normalizetime() returns, time will be in time zone b.
NSS Code Coverage
numbers in tested files example: 72.69% (165/227/731) 72.69% - ratio of tested blocks and total blocks in file (generated by tcov).
... numbers in not tested files example: not tested (0/?/878).
... numbers in total count example: total: 42% (574/1351).
HTTP delegation
to find an example implementation, you may look at bug 111384, which tracks the implementation in mozilla client applications.
...the http server session object is logically associated with host and port destination information, in our example this is "host ocsp.provider.com port 80".
...in our example the path is "/cgi-bin/ocsp-responder".
HTTP delegation
to find an example implementation, you may look at bug 111384, which tracks the implementation in mozilla client applications.
...the http server session object is logically associated with host and port destination information, in our example this is "host ocsp.provider.com port 80".
...in our example the path is "/cgi-bin/ocsp-responder".
nss tech note4
ess(certname *name); char *cert_getcountryname(certname *name); char *cert_getlocalityname(certname *name); char *cert_getstatename(certname *name); char *cert_getorgname(certname *name); char *cert_getorgunitname(certname *name); char *cert_getdomaincomponentname(certname *name); char *cert_getcertuid(certname *name); example code to illustrate access to the info is given below.
...examples: x500 rsa encryption, certificate basic constraints, pkcs#7 digested data, etc.
... } extensions++; } } an example custom cert extension struct _mycertextdata { secitem version; secitem streetaddress; secitem phonenum; secitem rfc822name; secitem id; secitem maxusers; }; typedef struct _mycertextdata mycertextdata; /* template used for decoding the extension */ const sec_asn1temp...
NSS PKCS11 Functions
for example, if you would normally specify tokens=<0x4=[configdir='./mybackup' tokendescription='backup']> to softoken if you at init time, then you could specify "configdir='./mybackup' tokendescription='backup'" as your module spec here to open the database ./mybackup on the fly.
...for example, mozilla uses the parameter to pass information about which window is associated with the modal dialog box requesting the password from the user.
...see also for examples of password callback functions, see the samples in the samples directory.
NSS tools : cmsutil
usage encrypt example cmsutil -c [-i infile] [-o outfile] [-d dbdir] [-p password] -r "recipient1,recipient2, .
...." -e envfile decode example cmsutil -d [-i infile] [-o outfile] [-d dbdir] [-p password] [-c content] [-n] [-h num] envelope example cmsutil -e [-i infile] [-o outfile] [-d dbdir] [-p password] -r "recipient1,recipient2, ..." certificate-only example cmsutil -o [-i infile] [-o outfile] [-d dbdir] [-p password] -r "cert1,cert2, .
...." sign message example cmsutil -s [-i infile] [-o outfile] [-d dbdir] [-p password] -n nickname[-tgp] [-y ekprefnick] see also certutil(1) see also additional resources nss is maintained in conjunction with pki and security-related projects through mozilla dn fedora.
NSS tools : cmsutil
MozillaProjectsNSStoolscmsutil
usage encrypt example cmsutil -c [-i infile] [-o outfile] [-d dbdir] [-p password] -r "recipient1,recipient2, .
...." -e envfile decode example cmsutil -d [-i infile] [-o outfile] [-d dbdir] [-p password] [-c content] [-n] [-h num] envelope example cmsutil -e [-i infile] [-o outfile] [-d dbdir] [-p password] -r "recipient1,recipient2, ..." certificate-only example cmsutil -o [-i infile] [-o outfile] [-d dbdir] [-p password] -r "cert1,cert2, .
...." sign message example cmsutil -s [-i infile] [-o outfile] [-d dbdir] [-p password] -n nickname[-tgp] [-y ekprefnick] see also certutil(1) see also additional resources nss is maintained in conjunction with pki and security-related projects through mozilla dn fedora.
NSS tools : signver
MozillaProjectsNSStoolssignver
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).
...for example: # signver -a -s signature -d sql:/home/my/sharednssdb to set the shared database type as the default type for the tools, set the nss_default_db_type environment variable to sql: export nss_default_db_type="sql" this line can be set added to the ~/.bashrc file to make the change permanent.
...for example, this how-to article covers how to configure firefox and thunderbird to use the new shared nss databases: o https://wiki.mozilla.org/nss_shared_db_howto for an engineering draft on the changes in the shared nss databases, see the nss project wiki: o https://wiki.mozilla.org/nss_shared_db see also signtool (1) the nss wiki has information on the new database design and how to configure applications to use it.
Multithreading in Necko
for example, the http protocol handler has code that runs on the socket transport thread to kick off pending requests well before the main thread would get around to doing so.
...the jar protocol handler, for rexample, passes a special nsiinputstream impl that does gzip decoding on the fly.
...for example, on xp_win an invisible window is created with a message pump on a background thread for processing wsa asynchronous dns events.
Performance Hints
for example, you could rewrite function sum(a) { result = 0; for (i=0; i < a.length; i++) result += a[i]; return result; } as function sum(a) { var result = 0; for (var i=0; i < a.length; i++) result += a[i]; return result; } this is not equivalent code because the second version does not modify global variables result and i.
...for example, the code var a = new array(); for (var i=0; i < n; i++) a[i] = i; could be sped up by changing the constructor call to new array(n).
...for example, the code function myobject(a) { this.s = a; this.tostring = new function("return this.s"); } could be written more efficiently as function myobject(a) { this.s = a; this.tostring = function () { return this.s } } beginning with rhino 1.4 release 2, code passed to eval and new function will be interpreted rather than compiled to class files.
The JavaScript Runtime
for example, evaluating the expression obj["3"] will invoke the get(int, scriptable) method even though the property name was presented in the script as a string.
...for example, in a browser environment, the window and document objects are host objects.
...several of the examples define host objects this way.
Rhino scopes and contexts
for a more concrete example, let's consider the following script: var g = 7; function f(a) { var v = 8; x = v + a; } f(6); we have a top-level variable g, and the call to f will create a new top-level variable x.
... an example scope chain for a simple script.
... the dynamicscopes example illustrates all the points discussed above.
Rhino serialization
simple serialization example the rhino shell has two new top-level functions, serialize and deserialize.
... 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.
...this isn't that interesting an example since compiling a function to a class and then loading it accomplishes the same as serializing an interpreted function, but it becomes more relevant if you wish to serialize javascript objects that have references to compiled functions.
Creating JavaScript jstest reftests
non262 tests the directory js/src/tests/non262/ should contain all tests of the following type: regressions of spidermonkey non-standard spidermonkey extensions to the javascript language test of "implementation-defined" details of the ecmascript standard for example, the exact definition of pi or some details of array sorting.
...for example, reportcompare sometimes considers numbers to be the same if they are "close enough" to each other, even if the == operator would return false.
...for example, to test the decompilation of a simple function you could write: var f = (function () { return 1; }); expect = 'function () { return 1; }'; actual = f + ''; comparesource(expect, actual, 'decompile simple function'); handling shell or browser specific features jstests run both in the browser and in the javascript shell.
Property cache
see bug 458271 and bug 507231 for example.
... there are probably similar bugs to do with, for example, xml objects' custom getproperty op.) dense arrays are shapeless.
...for example, when sealing an object, we must somehow preserve the extensibility guarantee.
Introduction to the JavaScript shell
for example, if you want to display a message when line 6 of a function, dosomething() is executed, you can enter the following: trap(dosomething, line2pc(dosomething, 6), "print('line 6!\n')"); note: when a trap is set, the corresponding bytecode in the program is replaced with a trap bytecode until you use untrap() to remove the trap.
...this may be useful for gaining access to syntax only available in certain versions of javascript (for example, see using javascript 1.7).
... for example, if you enter the javascript function below: function test() { var i = 3; print(i+2); } then run the command dis(test);, you get this output: main: 00000: uint16 3 00003: setvar 0 00006: pop 00007: name "print" 00010: pushobj 00011: getvar 0 00014: uint16 2 00017: add 00018: call 1 00021: pop 00022: stop source notes: 0: 0 [ 0] newline 1: 3 [ 3] decl offset 0 2: 7 [ 4] newline 3: 18 [ 11] xdelta 4: 18 [ 0] pcbase offset 11 dissrc([function]) disassembles the javascript bytecode for the entire program, or for the specified function, ...
JS_PreventExtensions
for example, if making the object requires an allocation, and that allocation fails, out-of-memory might be reported, and js_preventextensions would return false.
... for example, if the object is a revocable proxy that has been revoked, it makes no sense to say that an attempt to prevent extensions either succeeded or failed: it's a category error.
... for example, a proxy might refuse to be made non-extensible; this refusal would show up in the post-call value of *succeeded.
JSAPI reference
for example, js_valuetoobject(cx, s) where s is a string creates a new string wrapper object.
...for example, js_valuetostring(cx, obj) may call obj.tostring().
...(for example, these apis support very smooth integration between the js garbage collector and other garbage collectors.) struct jstracer added in spidermonkey 1.8 js_tracechildren added in spidermonkey 1.8 js_traceruntime added in spidermonkey 1.8 jsval_is_traceable added in spidermonkey 1.8 obsolete since jsapi 31 jsval_to_traceable added in spidermonkey 1.8 obsolete since jsapi 31 jsval_trace_kin...
TPS History Lists
for example, 0 is now, -24 is 24 hours in the past.
... for example: var history_initial = [ { uri: "http://www.google.com/", title: "google", visits: [ { type: 1, date: 0 }, { type: 2, date: -1 } ] }, { uri: "http://www.cnn.com/", title: "cnn", visits: [ { type: 1, date: -1 }, { type: 2, date: -36 } ] }, ]; the history list used for deletions looks different.
...e different types: to delete all references to a specific page from history, use an object with a uri property to delete all references to all pages from a specific host, use an object with a host property to delete all history in a certain time period, use an object with begin and end properties, which should have integer values that express time since the present in hours (see date above) for example: var history_to_delete = [ { uri: "http://www.cnn.com/" }, { begin: -24, end: -1 }, { host: "www.google.com" } ]; history lists and phase actions history lists cannot be modified, they can only be added, deleted, and verified, using the following functions: history.add history.delete history.verify history.verifynot ...
Gecko object attributes
for example, a datatype may be xsd:integer.
...for example, a heading, paragraph, or list item is typically formatted as a block, but there is no requirement to do so.
...an example of this is often horizontal navigation bars with list items that are formatted with css display: inline.
Retrieving part of the bookmarks tree
for more basic bookmarks examples, see manipulating bookmarks using places.
...this example will get the id of the bookmarks toolbar: var bookmarksservice = components.classes["@mozilla.org/browser/nav-bookmarks-service;1"] .getservice(components.interfaces.nsinavbookmarksservice); var toolbarfolder = bookmarksservice.toolbarfolder; the placesroot is the root folder in the whole places hierarchy.
...object: query.setfolders([toolbarfolder], 1); run the query the executequery and executequeries functions will return an nsinavhistoryresult object containing the results of your query: var result = historyservice.executequery(query, options); get the results when you are querying for exactly one folder grouped by folder with no fancy query parameters such as keywords or date ranges (as in this example), the root of the result will be an nsinavhistorycontainerresultnode corresponding to your folder.
Using the Places livemark service
var newlvmkid = livemarkservice.createlivemark(parentfolderid, "livemark name", uri("http://example.com/"), uri("http://example.com/rss.xml"), -1); the first parameter is the id of the folder in which to create the livemark.
... getservice(components.interfaces.nsinavbookmarksservice); var root = bmsvc.bookmarksmenufolder; // item id of the bookmarks menu var newlvmkid = livemarkservice.createlivemarkfolderonly(bmsvc, root, "livemark name", uri("http://example.com/"), uri("http://example.com/rss.xml"), -1); the parameters here are the same as for nsilivemarkservice.createlivemark(), except for the insertion of a new parameter at the beginning, which is the nsinavbookmarksservice to use when creating the livemark.
... livemarkservice.setfeeduri(newlvmkid, uri("http://foo.example.com/rss.xml")); //newlvmkid = see "create a new livemark" for more detail.
Using the Places tagging service
taggingsvc.taguri(uri("http://example.com/"), ["tag 1"]); //first argument = uri //second argument = array of tag(s) where uri() is probably similar to makeuri().
... tagginsvc.untaguri(uri("http://example.com/"), ["tag 1"]); //first argument = uri //second argument = array of tag(s) finding all urls with a given tag the nsitaggingservice.geturisfortag() method returns an array of all urls tagged with the given tag.
... var tags = taggingsvc.gettagsforuri(uri("http://example.com/", {})); //tags = an array of tags stored in http://example.com/ see also places nsitaggingservice ...
extIPreferenceBranch
for example, an extension's preferences has a root of "extensions.extensionid.", while the application-level preferences have an empty root.
... for example, null/undefined/an object.
... see bug 481044 void reset() parameters return value examples var myext = application.extensions.get('myapplicationid'); function myfunc (event) { application.console.log('change!'); }; myext.prefs.get("myprefname").events.addlistener("change", myfunc); see also fuel (firefox), steel (thunderbird) and smile (seamonkey) known issues bug 488587 - function registered as fuel preference listener not always called ...
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.
Bundling multiple binary components
if the component uses only "frozen" xpcom interfaces, there is a good chance the same binary component will work with different versions of gecko (version 1.8 and 1.9, for example).
...this can create a difficult situation for extension developers trying to support multiple gecko versions (firefox 2 and 3, for example).
...the gears project contains an example of a javascript-based stub loader.
Preface
for example, the introduction includes a discussion of components and what they are, and the first chapter - in which you compile the basic code and register it with mozilla - prompts a discussion of the relationship between components and modules, of xpcom interfaces, and of the registration process in general.
...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.
Creating XPCOM components
for example, the introduction includes a discussion of components and what they are, and the first chapter - in which you compile the basic code and register it with mozilla - prompts a discussion of the relationship between components and modules, of xpcom interfaces, and of the registration process in general.
... 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 co...
...mponents 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 coding for the re...
Interfacing with the XPCOM cycle collector
for example, your class may have multiple nsisupports base classes, which requires the use of some *_ambiguous macros that perform a disambiguating downcast.
...you can see an example of their use in some more complicated classes such as content/base/src/nsgenericelement.cpp.
... for example, suppose your class nsfoo has field msomeobj: private: ...
Components.isSuccessCode
for example, if you ask a component or service to asynchronously perform some task, you must usually pass in an object which will be notified when the task is completed.
... if the task is sufficiently complex that it can fail, the notification will include a status code indicating the success or failure of the operation (see, for example, nsirequestobserver.onstoprequest()).
... 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.import
for example, you can import xpcomutils.jsm to avoid copy/pasting long xpcom component registration boilerplate in your component files.
... example components.utils.import("resource://gre/modules/xpcomutils.jsm", this); difference from mozijssubscriptloader the differences from mozijssubscriptloader: the behavior when importing/loading the same code from different locations: the subscript loader evaluates the specified code each time it is invoked, with the caller's global object.
... for example: var scope1 = {}, scope2 = {}; components.utils.import("resource://gre/modules/json.jsm", scope1); components.utils.import("resource://gre/modules/json.jsm", scope2); assert(scope2.xpcomutils === scope1.xpcomutils); ...returns true, whereas: var someurl = "resource://gre/modules/json.jsm"; var obj1 = {}, obj2 = {}; var loader = components.classes["@mozilla.org/moz/jssubscript-loader;1"] .getservice(components.interfaces.mozijssubscriptloader); loader.loadsubscript(someurl, obj1); loader.loadsubscript(someurl, obj2); assert(obj2 === obj1); ...returns false.
Components.utils.importGlobalProperties
example components.utils.import("resource://gre/modules/devtools/console.jsm"); components.utils.importglobalproperties(["atob", "btoa"]); var encoded = btoa("hello"); console.log(encoded); // "sgvsbg8=" console.log(atob(encoded)); // "hello" alternative methods if importglobalproperties does not support the targeted firefox version, here are some alternative methods to import t...
... for example this is how to ues the file object.
... var domfile = services.appshell.hiddendomwindow.file('/path/to/file'); xpcom components some objects have an xpcom alternative, which typically allows more flexibility then the dom version here is an example of how to use the dom xmlhttprequest through xpcom interface of nsixmlhttprequest: var oreq = cc["@mozilla.org/xmlextras/xmlhttprequest;1"].createinstance(ci.nsixmlhttprequest); ...
Components.utils.waiveXrays
for example, privileged code using an xray to a dom object sees only the original, native version of the dom object.
...however, in some cases it can be too restrictive: for example, if you need to see an expando property on a dom object.
...example suppose a page script adds an expando to its global window: // page script foo = "i'm an expando"; by default, chrome code won't see foo, because it sees the content window with xray vision, but the chrome code can waive xray protection: // chrome code // contentwindow is an xray var isxray = components.utils.isxraywrapper(gbrowser.contentwindow); // true // expandos are not visible in xrays...
XPCShell Reference
for example, if you created anobject with a property named value and then called clear(anobject), the property value would no longer exist.
...for example, load("myscript.js") will execute the script myscript.js in the current directory.
...an example print(1, 2, 3) will print 1 2 3<newline>.
Observer Notifications
user-interaction-active nsidomwindow null sent once every 5000ms while this chrome document sees some kind of user activity (for example, keyboard or mouse events), and at the exact moment of the state transition from idle to active.
...the subject will be the download id wrapped in nsisupportspruint32, for one download removed, or null for multi download remove, for example when the download list is cleared.
... for example, suppose you've loaded a frame script into a tab using a browser message manager, and the user closes the tab.
mozIThirdPartyUtil
for example, if auri is "http://mail.google.com/", achannel has a uri of "http://google.com/", and its parent is the topmost content window with a uri of "http://mozilla.com", the result will be true.
...for example, the uri "http://mail.google.com/" is not third party with respect to "http://images.google.com/", but "http://mail.yahoo.com/" and "http://192.168.1.1/" are.
...(this means that nested iframes with different base domains, even though the bottommost and topmost uris might be equal, will be considered third party.) for example, if auri is "http://mail.google.com/", 'awindow' has a uri of "http://google.com/", and its parent is the topmost content window with a uri of "http://mozilla.com", the result will be true.
nsIAccessibleHyperLink
this anchor is, for example, the visible output of the html:a tag.
... selected boolean determines whether the element currently has the focus, for example after returning from the destination page.
... valid boolean determines whether the hyperlink is valid, for example points to a valid url.
nsIAccessibleRole
for example, a user clicks and drags a sizing grip in the lower-right corner of a window to resize it.
...an example of the use of this role is to represent an html:div.
...an example of the use of this role is to represent an html:form.
nsIAuthPrompt
for example, ldap://localhost/dc=test.
...for example, ldap://localhost/dc=test.
...for example, ldap://localhost/dc=test.
nsICategoryManager
examples print out a list of all categories this snippet shows how to print out a list of all categories in c++.
...orymanager.enumeratecategories(); var categories = []; while (enumerator.hasmoreelements()) { var item = enumerator.getnext(); var category = item.queryinterface(components.interfaces.nsisupportscstring) categories.push(category.tostring()); } categories.sort(); var categoriesstring = categories.join("\n"); dump(categoriesstring + "\n"); print out a list of app-startup entries this example prints out a list of entries of "app-startup" category.
...the second portion of this snippet disables plugins from loading in the future, it does not user the category manager but it is included for completness of the example.
nsIConsoleService
reset() to clear the message buffer (for example, for privacy reasons): void reset(); parameters none.
... 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 message array in gecko 19 or later: function getconsolemessag...
...in this example nsiscripterror, which implements nsiconsolemessage, is used to include information about the source file and line number of the error.
nsIExternalProtocolService
for example, "mms".
...-nickolay <pre> // first construct an nsiuri object using the ioservice var ioservice = components.classes["@mozilla.org/network/io-service;1"].getservice(components.interfaces.nsiioservice); var uritoopen = ioservice.newuri("http://www.example.com/", null, null); var extps = components.classes["@mozilla.org/uriloader/external-protocol-service;1"] .getservice(components.interfaces.nsiexternalprotocolservice); if (extps.externalprotocolhandlerexists("tlcxp")) { // handler for http:// urls exists } else { // suppress external-load warning for standard browser schemes pref("network.protocol-handler.external.tlcxp", true); pref("network.protocol-handler.app.tlcxp, "lzx"); } </pre> getprotocolhandlerinfo() retrieve the handler for...
...for example, a non-exposed protocol would not be loaded by the application in response to a link click or a x-remote openurl command.
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.
... var inifact = components.manager.getclassobjectbycontractid( "@mozilla.org/xpcom/ini-parser-factory;1", components.interfaces.nsiiniparserfactory ); var iniparser = inifact.createiniparser(inifile); try { return iniparser.getstring(section,prop); } catch(e) { return undefined; } } // usage: var lang = getinivalue(file,"setting","language"); enumerating sections this example gets a list of all the sections in the ini file.
... // get all sections in the ini file var sectenum = iniparser.getsections(); // save the sections in an array var sections = []; while (sectenum && sectenum.hasmore()) { var section = sectenum.getnext(); // add an array entry for each section sections.push(section); } enumerating keys this example shows how to fetch the values for all the keys in the section named "setting".
nsIINIParserFactory
1.0 66 introduced gecko 1.8 inherits from: nsisupports last changed in gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) see example for how to use this interface.
...example obtaining a parser object to obtain a parser for an ini file, you can use code that looks like this: to get an nsiiniparser instance for an ini file, you may use the following code: // create an nsilocalfile var cl = "@mozilla.org/file/local;1"; var interf = components.interfaces.nsilocalfile; var file = components.classes[cl].createinstance(interf); // init the file with the path to your ini fi...
...le var path = "c:\\temp\\example.ini"; file.initwithpath(path); // create the nsiiniparserfactory var cl = "@mozilla.org/xpcom/ini-parser-factory;1"; var interf = components.interfaces.nsiiniparserfactory; var inifact = components.manager.getclassobjectbycontractid(cl,interf); // get the iniparser for the ini file var iniparser = inifact.createiniparser(file); see also nsiiniparser nsilocalfile ...
nsIMemoryReporter
for example, the number of tabs currently open.
...for example, the number of times the user has opened a new tab.
...for example if the actual percentage is 12.34%, amount should be 1234.
nsIMessageBroadcaster
for example, broadcasting a message through a window message manager will broadcast the message to all frame message managers within its window.
... for example, we will throw ns_error_not_initialized if we try to send a message to a cross-process frame but the other process has not yet been set up.
... for example, we will throw ns_error_failure if we try to send a message to a cross-process frame whose process has crashed.
nsIMessageSender
for example, a child-process message manager will send messages that are only delivered to its one parent-process message manager.
... for example, we will throw ns_error_not_initialized if we try to send a message to a cross-process frame but the other process has not yet been set up.
... for example, we will throw ns_error_failure if we try to send a message to a cross-process frame whose process has crashed.
nsINavHistoryObserver
if an error occurs in between these two steps (for example, an out of memory error), then you may get a notification even though the page doesn't wind up getting deleted.
...if an error occurs in between these two steps (for example, an out of memory error), then you may get a notification even though the page doesn't wind up getting deleted.
...normally, transition types of transition_embed (corresponding to images in a page, for example) are not displayed in history results (unless includehidden is set).
nsINavHistoryQuery
uri nsiuri this is a uri to match, to, for example, find out every time you visited a given uri.
...for example http://bar.com/foo will match http://bar.com/foo as well as http://bar.com/foo/baz.gif.
...for example, a "past week" query would be (today-6 days -> today+1 day).
nsINavHistoryResultViewObserver
for example, when the delete key is pressed, this method is called with the string "delete".
...for example, when the delete key is pressed, this method is called with the string "delete".
...for example, when the delete key is pressed, this method is called with the string "delete".
nsIPrefBranch2
for example, if your observer is registered with addobserver("bar.", ...) on a branch with root "foo.", modifying the preference "foo.bar.baz" will trigger the observer, and adata parameter will be "bar.baz".
...for example holding the "root" prefbranch and calling addobserver("foo.bar.", ...) will observe changes to foo.bar.baz and foo.bar.bzip.
...this ensures that long lived objects (services for example) will be freed correctly.
nsIProcessScriptLoader
for example: let ppmm = services.ppmm.getchildat(1); ppmm.loadprocessscript('data:,dump("foo\n");', true); parameters name type description aurl string url for the script to load.
...for example data:,dump("foo\n"); aallowdelayedload boolean if this flag is false, the process script will only be loaded into child processes that are already running at the time of the call.
...if you used aallowdelayedload, you should call this as part of your cleanup (for example, when your add-on is disabled or uninstalled).
nsIScriptableIO
for example: io.getfile("profile", "cookies.txt"); from an xpcom component, however, you will need to get a reference as with other components: var scriptableio = components.classes["@mozilla.org/io/scriptable-io;1"] .getservice(); scriptableio.getfile("profile", "cookies.txt"); method overview nsifile getfile(in astring alocation, in astring afilename); ...
...for example, if the location key is specified as "desk" and the file name is specified as "foo.txt", the file reference generated will refer to a file named "foo.txt" on the user's desktop.
... example: writing to a file var json = "{ name: 'bob', age: 37}"; var file = io.getfile("profile", null); file.append("myobject.json"); if (!file.exists()) file.create(ci.nsifile.normal_file_type, 0600); var stream = io.newoutputstream(file, "text write create truncate"); stream.writestring(json); stream.close(); example: reading from a file var file = io.getfile("profile", null); file.append("localsto...
nsIScriptableInputStream
examples list contents of xpi and read file contents this example here uses the read function.
...full example using the zip interfaces is seen here: list contents of xpi and read file contents.
...inputstream = cc("@mozilla.org/scriptableinputstream;1", "nsiscriptableinputstream", "init"); let entry = this.getentry(name); let stream = new scriptableinputstream(this.getinputstream(name)); try { // use readbytes to get binary data, read to read a (null-terminated) string let contents = stream.readbytes(entry.realsize); } finally { stream.close(); } example usage in ondataavailable remember: the nsiscriptableinputstream has a contract where `init` should only be called once, and should always be closed.
nsISupports proxies
a good example of this is the old install.js scripts that were used in xpinstall in older mozilla versions.
...for example: myfoo->bar(&x) ...
... example usage nsresult rv = ns_ok; nscomptr<nsiproxyobjectmanager> piproxyobjectmanager(do_getservice("@mozilla.org/xpcomproxy;1", &rv)); if(ns_failed(rv)) return rv; nscomptr<ifoo> ptestobj(do_createinstance(foo_contractid, &rv)); if(ns_failed(rv)) return rv; nscomptr<ifoo> pproxy; rv = piproxyobjectmanager->getproxyforobject(ns_proxy_to_main_thread, ifoo::getiid(), ptestobj, ns_proxy_sync | ns_p...
nsISyncMessageSender
for example, a child-process message manager will send messages that are only delivered to its one parent-process message manager.
... for example, we will throw ns_error_not_initialized if we try to send a message to a cross-process frame but the other process has not yet been set up.
... for example, we will throw ns_error_failure if we try to send a message to a cross-process frame whose process has crashed.
nsIWindowWatcher
this attribute will be null if the active window is not an nsidomwindow; for example, if the active window is an alert.
... example for example, in a xul application or mozilla extension, if the window object is unavailable (for example, when opening a window from xpcom component code), you might want to use this interface for opening a new window: var ww = components.classes["@mozilla.org/embedcomp/window-watcher;1"] .getservice(components.interfaces.nsiwindowwatcher); var win = ww.openwindow(null, "c...
...for example the following code will block the system because it will open windows continuously: function mywindowobserver() { this.observe=function(asubject, atopic, adata) { alert("window event: " + atopic) //and this is where the bugs origins because opening this alert will cause a window-open //event and the call of this method again (forever) } } var ww = components.classes["@mozilla.org...
nsIXMLHttpRequest
when using the xpcom interface, as seen below in example 2, we can get access to this.
...for instance, as done in example 2, the flag of load_anonymous is added, this strips all user data (cookies, tokens, etc).
... example code this is a simple example code for opening a simple http request from a xul application (like a mozilla extension) without using observers: var req = components.classes["@mozilla.org/xmlextras/xmlhttprequest;1"].createinstance(); req.open('post', "http://www.foo.bar:8080/nietzsche.do", true); req.send('your=data&and=more&stuff=here'); example 2 var {cu: utils, cc: classes, ci: instanc...
NS_StringAppendData
remarks this function is defined inline as a wrapper around ns_stringsetdatarange note: gcc requires the -fshort-wchar option to compile this example since prunichar is an unsigned short.
... this example should compile by default under msvc.
... example code nsstringcontainer str; ns_stringcontainerinit(str); ns_stringsetdata(str, l"hello"); ns_stringappenddata(str, l" world"); const prunichar* data; ns_stringgetdata(str, &data); // data now points to the string: l"hello world" ns_stringcontainerfinish(str); history this function was frozen for mozilla 1.7.
NS_StringCutData
note: gcc requires the -fshort-wchar option to compile this example since prunichar is an unsigned short.
... this example should compile by default under msvc.
... example code nsstringcontainer str; ns_stringcontainerinit(str); ns_stringsetdata(str, l"hello world"); // remove " world" portion of string ns_stringcutdata(str, 5, pr_uint32_max); const prunichar* data; ns_stringgetdata(str, &data); // data now ponts to the string: l"hello" ns_stringcontainerfinish(str); history this function was frozen for mozilla 1.7.
NS_StringInsertData
note: gcc requires the -fshort-wchar option to compile this example since prunichar is an unsigned short.
... this example should compile by default under msvc.
... example code nsstringcontainer str; ns_stringcontainerinit(str); ns_stringsetdata(str, l"hello"); ns_stringinsertdata(str, 5, l" world"); const prunichar* data; ns_stringgetdata(str, &data); // data now points to the string: l"hello world" ns_stringcontainerfinish(str); history this function was frozen for mozilla 1.7.
Getting Started Guide
all good getters addref the interface pointers they produce, thus providing you with an owning reference; you will hold onto the reference longer than the scope of the function in which you acquired it, e.g., you got it as a parameter, but you're hanging onto it in a member variable (see, for example, comparison 1, below).
...in the example above, there is no reason to assume that the nsifoo* c++ pulls out of p would be the same one that p->queryinterface() would return.
...do this, for example, when you got the new value from a function which, like all good xpcom getters, already called addref on your behalf.
Reference Manual
for example, an nscomptr<nsifoo> will always hold the pointer that would be returned by queryinterface, when querying an xpcom object for its nsifoo interface.
... nsresult getfoo( nsifoo** ); // a standard getter nsresult getfoo2( nsifoo*& ); // a non-standard getter nsresult getsomething( void** ); // an "un-typed" getter // note: |queryinterface| is an example of a "un-typed" getter we must be able to pass nscomptrs by pointer or reference, into routines for use as "out" parameters.
...the case using the temporary, however, uses construction to put the value into the nscomptr, which (though slightly more complicated in source) is more efficient than default construction followed by assignment, the course of events followed by the simpler example.
Weak reference
here's an example.
... { // ...but to use my weak reference, i'll need a (short-lived) owning reference nscomptr<nsifoo> tempfooptr = do_queryreferent(weakptr); if ( tempfooptr ) tempfooptr->somefoomethod(...); // else, the `real' object has gone away } in a real world example, however, you are more likely to be holding a weak reference in a member variable.
... in the following example, an nsobservable must keep some kind of a reference to each observer, in order to report events.
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.
Building a Thunderbird extension 5: XUL
in this example you are adding a line to the indented statusbar.
... example xul overlay document create a new file called myhelloworld.xul within the content folder you created earlier with the following content: <?xml version="1.0"?> <overlay id="sample" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <script type="application/javascript" src="chrome://myfirstext/content/overlay.js"/><!-- a reference to your javascript file --> <statusbar id="status-bar"> <statusbarpanel id="my-panel" label="date"/> </statusbar> </overlay> the <statusbar> widget n...
...in the example above we have defined a new <statusbarpanel> item (that can be referred to as my-panel) which will create a new instance of this widget type and add it at the end of the statusbar.
Demo Addon
it shows how to achieve various goals in a working live example, such as working with gloda.
..." *" : "") + "\n"; if (folder.hassubfolders) for each (let folder in fixiterator(folder.subfolders, ci.nsimsgfolder)) print(indent + " ", folder); }; print(" ", folder); as in the previous example, we get the incomingserver of the account in question.
... the last line of this example executes the gloda query.
Finding the code for a feature
as an example, i received the following inquiry, and i decided to follow my usual path and document what i do: hello i would like to add colours and tags to specific emails...by using nsimsgtagservice, can this be done?
... 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 ...
Using tab-modal prompts
for example: var factory = components.classes["@mozilla.org/prompter;1"] .getservice(components.interfaces.nsipromptfactory); var prompt = factory.getprompt(gbrowser.contentwindow, components.interfaces.nsiprompt); var bag = prompt.queryinterface(components.interfaces.nsiwritablepropertybag2); bag.setpropertyasbool("allowtabmodal", true); var promptargs = ["devmo alert", "omg!
... an alert!"]; prompt.alert.apply(null, promptargs); nsiprompt will automatically fall back to window-modal prompts when necessary (such as in situations in which tab-modal prompts aren't supported, or for prompts displayed outside the context of a tab).le to use other forms of the prompts of nsipromptservice interface see the example code.
... then apply it, like in the example below, here we apply the prompt with a checkbox: var window = gbrowser.contentwindow; var promptfact = components.classes['@mozilla.org/prompter;1'].getservice(components.interfaces.nsipromptfactory); var prompt = promptfact.getprompt(window, components.interfaces.nsiprompt); var promptbag = prompt.queryinterface(components.interfaces.nsiwritablepropertybag2); promptbag.setpropertyasbool('allowtabmodal', true); var check = {value: false}; //initial state of checkbox, however if no text is supplied the checkbox is not shown var input = {value: 'pre filled value'}; var ok = prompt.prompt.apply(null, ['title - but not shown in tab modal', 'text goes here', input, 'check text, if no text, checkbox is not shown', check]); //this here is just an alert, showing th...
Declaring and Calling Functions
example: no input parameters in this example, we declare the libc clock() function, which returns the elapsed time since system startup, then fetch and output that value.
... example: multiple input parameters this example declares the libc asctime() function, which converts a time structure into a string.
... const asctime = lib.declare("asctime", ctypes.default_abi, ctypes.char.ptr, struct_tm.ptr); for a more complete version of this example (including the implementation of the struct_tm type), see the structures example.
Gecko Plugin API Reference - Plugins
ug-ins scriptable building plug-ins building, platforms, and compilers building carbonized plug-ins for mac os x type libraries installing plug-ins native installers xpi plug-ins installations plug-in installation and the windows registry initialization and destruction initialization instance creation instance destruction shutdown initialize and shutdown example drawing and event handling the npwindow structure drawing plug-ins printing the plug-in setting the window getting information windowed plug-ins mac os windows unix event handling for windowed plug-ins windowless plug-ins specifying that a plug-in is windowless invalidating the drawing area forcing a paint message making a plug-in opaque...
...r windowless plug-ins streams receiving a stream telling the plug-in when a stream is created telling the plug-in when a stream is deleted finding out how much data the plug-in can accept writing the stream to the plug-in sending the stream in random-access mode sending the stream in file mode sending a stream creating a stream pushing data into the stream deleting the stream example of sending a stream urls getting urls getting the url and displaying the page posting urls posting data to an http server uploading files to an ftp server sending mail memory allocating and freeing memory mac os flushing memory (mac os only) version, ui, and status information displaying a status line message getting agent information ge...
... npn_getvalueforurl provides information to a plug-in which is associated with a given url, for example the cookies or preferred proxy.
Tree map view - Firefox Developer Tools
here are some example snapshots, as they appear in the tree map view: this treemap is from the dom allocation example, which simply runs a script that creates a large number of dom nodes (200 htmldivelement objects and 4000 htmlspanelement objects).
... this treemap is from the monster allocation example, which creates three arrays, each containing 5000 monsters, each monster having a randomly-generated name.
... this treemap is from http://www.bbc.com/, and is probably more representative of real life than the examples.
Call Tree - Firefox Developer Tools
in this article, we'll use the output of a simple program as an example.
...for example, we can expand the entry for bubblesort(): so we can see the call graph is like this: sortall() -> sort() -> bubblesort() note also that self cost for sort() here is 1.45%, and note that this is the same as for the separate entry for sort() later in the list.
... in our example, there are 679 samples assigned to gecko - the second-largest group after bubblesort().
Web Console Helpers - Firefox Developer Tools
for example, if you type "2+2 <enter>", then "$_ <enter>", the console will print 4.
...actually, in a delightful example of recursion, it brings you to this page.
... examples looking at the contents of a dom node let's say you have a dom node with the id "title".
Web Console remoting - Firefox Developer Tools
for example: ["pageerror", "consoleapi", "networkactivity", "fileactivity"] the web console actor does not start any listeners by default.
...the request argument is the same as the request object in the above example request packet.
...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"...
AbstractWorker - Web APIs
example as an abstract interface, you won't directly use abstractworker in your code.
... you can find more examples on the mdn web docs github repository: basic dedicated worker example (run dedicated worker).
... basic shared worker example (run shared worker).
AnalyserNode.getByteFrequencyData() - Web APIs
for example, for 48000 sample rate, the last item of the array will represent the decibel value for 24000 hz.
... example the following example shows basic usage of an audiocontext to create an analysernode, then requestanimationframe and <canvas> to collect frequency data repeatedly and draw a "winamp bargraph style" output of the current audio input.
... for more examples/information, check out our voice-change-o-matic demo (see app.js lines 128–205 for relevant code).
AnalyserNode.getFloatFrequencyData() - Web APIs
for example, for 48000 sample rate, the last item of the array will represent the decibel value for 24000 hz.
... example const audioctx = new audiocontext(); const analyser = audioctx.createanalyser(); // float32array should be the same length as the frequencybincount const mydataarray = new float32array(analyser.frequencybincount); // fill the float32array with data returned from getfloatfrequencydata() analyser.getfloatfrequencydata(mydataarray); drawing a spectrum the following example shows basic usage of a...
... for more complete applied examples/information, check out our voice-change-o-matic-float-data demo (see the source code too).
AnalyserNode.smoothingTimeConstant - Web APIs
example the following example shows basic usage of an audiocontext to create an analysernode, then requestanimationframe and <canvas> to collect frequency data repeatedly and draw a "winamp bargraph style" output of the current audio input.
... for more complete applied examples/information, check out our voice-change-o-matic demo (see app.js lines 128–205 for relevant code).
... if you are curious about the effect the smoothingtimeconstant() has, try cloning the above example and setting analyser.smoothingtimeconstant = 0; instead.
AnalyserNode - Web APIs
examples note: see the guide visualizations with web audio api for more information on creating audio visualizations.
... basic usage the following example shows basic usage of an audiocontext to create an analysernode, then requestanimationframe and <canvas> to collect time domain data repeatedly and draw an "oscilloscope style" output of the current audio input.
... for more complete applied examples/information, check out our voice-change-o-matic demo (see app.js lines 128–205 for relevant code).
Animation.playbackRate - Web APIs
the value is a scaling factor, so for example a value of 2 would double the playback rate.
... 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.
...cake.addeventlistener("mousedown", growalice, false); cake.addeventlistener("touchstart", growalice, false); in another example, the red queen's race game, alice and the red queen are constantly slowing down: setinterval( function() { // make sure the playback rate never falls below .4 if (redqueen_alice.playbackrate > .4) { redqueen_alice.playbackrate *= .9; } }, 3000); but clicking or tapping on them causes them to speed up by multiplying their playbackrate: var gofaster = function() { redqueen_al...
AudioBufferSourceNode.loopEnd - Web APIs
example in this example, the audiocontext.decodeaudiodata() function is used to decode an audio track and put it into an audiobuffersourcenode.
...for example, if you set their values to 20 and 25, respectively, then begin playback, the sound will play normally until it reaches the 25 second mark.
... for a full working example, see this code running live, or view the source.
AudioBufferSourceNode.loopStart - Web APIs
example in this example, the audiocontext.decodeaudiodata() function is used to decode an audio track and put it into an audiobuffersourcenode.
...for example, if you set their values to 20 and 25, respectively, the audio will start to loop between 20 and 25 seconds in to the track.
... for a full working example, see this code running live, or view the source.
AudioBufferSourceNode.start() - Web APIs
for example, to start playback halfway through a 10-second audio clip, offset should be 5.
... 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.
... source.start(audioctx.currenttime + 1,3,10); for a more complete example showing start() in use, check out our audiocontext.decodeaudiodata() example, you can also run the code example live, or view the source.
AudioContext.createMediaStreamDestination() - Web APIs
this stream can be used in a similar way as a mediastream obtained via navigator.getusermedia — it can, for example, be sent to a remote peer using the rtcpeerconnection addstream() method.
... 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.
... var blob = new blob(chunks, { 'type' : 'audio/ogg; codecs=opus' }); document.queryselector("audio").src = url.createobjecturl(blob); }; </script> </body> </html> note: you can view this example live, or study the source code, on github.
AudioTrack.language - Web APIs
for example, if the primary language used in the track is united states english, this value would be "en-us".
... example this example locates all of a media element's primary language and translated audio tracks and returns a list of objects containing each of those tracks' id, kind, and language.
... this could then be used to build a user interface for selecting the language the user would like to listen to while watching a movie, for example.
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.
... var audiotracks = document.queryselector("video").audiotracks; monitoring track count changes in this example, we have an app that displays information about the number of channels available.
BaseAudioContext.createConvolver() - Web APIs
example the following example shows basic usage of an audiocontext to create a convolver node.
...the example below uses a short sample of a concert hall crowd, so the reverb effect applied is really deep and echoey.
... for applied examples/information, check out our voice-change-o-matic demo (see app.js for relevant code).
BaseAudioContext - Web APIs
baseaudiocontext.createanalyser() creates an analysernode, which can be used to expose audio time and frequency data and for example to create data visualisations.
... baseaudiocontext.createconvolver() creates a convolvernode, which can be used to apply convolution effects to your audio graph, for example a reverberation effect.
... 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 ...
Beacon API - Web APIs
requests are guaranteed to be initiated before a page is unloaded and they are run to completion, without requiring a blocking request (for example xmlhttprequest).
... example use cases of the beacon api are logging activity and sending analytics data to the server.
... example code of the interfaces described in this document is included in using the beacon api.
BeforeUnloadEvent - Web APIs
when a non-empty string is assigned to the returnvalue event property, a dialog box appears, asking the users for confirmation to leave the page (see example below).
...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.
... an almost-cross-browser working example would be close to the below example.
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.
...button">broadcast message</button> body { border: 1px solid black; padding: .5rem; height: 150px; font-family: "fira sans", sans-serif; } h1 { font: 1.6em "fira sans", sans-serif; margin-bottom: 1rem; } textarea { padding: .2rem; } label, br { margin: .5rem 0; } button { vertical-align: top; height: 1.5rem; } const channel = new broadcastchannel('example-channel'); const messagecontrol = document.queryselector('#message'); const broadcastmessagebutton = document.queryselector('#broadcast-message'); broadcastmessagebutton.addeventlistener('click', () => { channel.postmessage(messagecontrol.value); }) receiver 1 <h1>receiver 1</h1> <div id="received"></div> body { border: 1px solid black; padding: .5rem; height: 100px; fon...
...t-family: "fira sans", sans-serif; } h1 { font: 1.6em "fira sans", sans-serif; margin-bottom: 1rem; } const channel = new broadcastchannel('example-channel'); channel.addeventlistener('message', (event) => { received.textcontent = event.data; }); receiver 2 <h1>receiver 2</h1> <div id="received"></div> body { border: 1px solid black; padding: .5rem; height: 100px; font-family: "fira sans", sans-serif; } h1 { font: 1.6em "fira sans", sans-serif; margin-bottom: 1rem; } const channel = new broadcastchannel('example-channel'); channel.addeventlistener('message', (event) => { received.textcontent = event.data; }); result specifications specification status html living standard living standard ...
CSSImageValue - Web APIs
the cssimagevalue interface of the css typed object model api represents values for properties that take an image, for example background-image, list-style-image, or border-image-source.
... 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.
... we then get() the background-image from the stylemap and stringify it: // get the element const button = document.queryselector( 'button' ); // retrieve all computed styles with computedstylemap() const allcomputedstyles = button.computedstylemap(); // return the cssimagevalue example console.log( allcomputedstyles.get('background-image') ); console.log( allcomputedstyles.get('background-image').tostring() ); specifications specification status comment css typed om level 1the definition of 'cssimagevalue' in that specification.
Managing screen orientation - Web APIs
for example, perhaps you want a button bar to stretch along the longest dimension of the device's display.
... let's have an example with the following html code <ul id="toolbar"> <li>a</li> <li>b</li> <li>c</li> </ul> <p>lorem ipsum dolor sit amet, consectetur adipiscing elit.
...for example, games based on the orientation of the device could be messed up by such a change of the orientation.
CSS Painting API - Web APIs
for example: aside { background-image: paint(mypaintedimage); } the api defines paintworklet, a worklet that can be used to programmatically generate an image that responds to computed style changes.
... 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); ...
CSS Typed Object Model API - Web APIs
this is easier for authors (for example, numeric values are reflected with actual js numbers, and have unit-aware mathematical operations defined for them).
...subclasses include: cssimagevalue objects an interface representing values for properties that take an image, for example background-image, list-style-image, or border-image-source.
... cssnumericvalue.tosum cssnumericvalue.type cssnumericvalue.parse - returns a number parsed from a css string csspositionvalue represents values for properties that take a position, for example object-position.
Cache.match() - Web APIs
WebAPICachematch
for example, if set to true the ?value=bar part of http://foo.com/?value=bar would be ignored when performing a match.
... examples this example is taken from the custom offline page example (live demo).
... in this example, only html documents retrieved with the get http verb will be cached.
CanvasPattern.setTransform() - Web APIs
examples using the settransform method this is just a simple code snippet which uses the settransform method to create a canvaspattern with the specified pattern transformation from an svgmatrix.
... the pattern gets applied if you set it as the current fillstyle and gets drawn onto the canvas when using the fillrect() method, for example.
...); var img = new image(); img.src = 'https://mdn.mozillademos.org/files/222/canvas_createpattern.png'; img.onload = function() { var pattern = ctx.createpattern(img, 'repeat'); pattern.settransform(matrix.rotate(-45).scale(1.5)); ctx.fillstyle = pattern; ctx.fillrect(0, 0, 400, 400); }; note that newer browser versions started to support dommatrix as an input to settransform(), so for example you could replace the svgmatrix in the above example with the following: const matrix = new dommatrix([1, .2, .8, 1, 0, 0]); edit the code below and see your changes update live in the canvas: playable code <canvas id="canvas" width="400" height="200" class="playable-canvas"></canvas> <svg id="svg1" style="display:none"></svg> <div class="playable-buttons"> <input id="edit" type="button" v...
CanvasRenderingContext2D.bezierCurveTo() - Web APIs
examples how beziercurveto works this example shows how a cubic bézier curve is drawn.
...d points ctx.fillstyle = 'blue'; ctx.beginpath(); ctx.arc(start.x, start.y, 5, 0, 2 * math.pi); // start point ctx.arc(end.x, end.y, 5, 0, 2 * math.pi); // end point ctx.fill(); // control points ctx.fillstyle = 'red'; ctx.beginpath(); ctx.arc(cp1.x, cp1.y, 5, 0, 2 * math.pi); // control point one ctx.arc(cp2.x, cp2.y, 5, 0, 2 * math.pi); // control point two ctx.fill(); result in this example, the control points are red and the start and end points are blue.
... a simple bézier curve this example draws a simple bézier curve using beziercurveto().
CanvasRenderingContext2D.createImageData() - Web APIs
examples creating a blank imagedata object this snippet creates a blank imagedata object using the createimagedata() method.
... const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); const imagedata = ctx.createimagedata(100, 50); console.log(imagedata); // imagedata { width: 100, height: 50, data: uint8clampedarray[20000] } filling a blank imagedata object this example creates and fills a new imagedata object with purple pixels.
...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.drawWindow() - Web APIs
it is given as a css color string (for example, rgb() or rgba()).
... example this method draws a snapshot of the contents of a dom window into the canvas.
... for example, ctx.drawwindow(window, 0, 0, 100, 200, 'rgb(255,255,255)'); ...
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.
... html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); ctx.fillstyle = 'blue'; ctx.fillrect(10, 10, 100, 100); result creating multiple fill colors using loops in this example, we use two for loops to draw a grid of rectangles, each having a different fill color.
CanvasRenderingContext2D.fillText() - Web APIs
examples drawing filled text this example writes the words "hello world" using the filltext() method.
... <canvas id="canvas" width="400" height="150"></canvas> javascript the javascript code for this example follows.
... result restricting the text size this example writes the words "hello world," restricting its width to 140 pixels.
CanvasRenderingContext2D.filter - Web APIs
examples to view these examples, make sure to use a browser that supports this feature; see the compatibility table below.
... applying a blur this example blurs a piece of text using the filter property.
...this example applies the contrast, sepia, and drop-shadow filters to a photo of a gecko.
CanvasRenderingContext2D.quadraticCurveTo() - Web APIs
examples how quadraticcurveto works this example shows how a quadratic bézier curve is drawn.
...e ctx.beginpath(); ctx.moveto(50, 20); ctx.quadraticcurveto(230, 30, 50, 100); ctx.stroke(); // start and end points ctx.fillstyle = 'blue'; ctx.beginpath(); ctx.arc(50, 20, 5, 0, 2 * math.pi); // start point ctx.arc(50, 100, 5, 0, 2 * math.pi); // end point ctx.fill(); // control point ctx.fillstyle = 'red'; ctx.beginpath(); ctx.arc(230, 30, 5, 0, 2 * math.pi); ctx.fill(); result in this example, the control point is red and the start and end points are blue.
... a simple quadratic curve this example draws a simple quadratic bézier curve using quadraticcurveto().
CanvasRenderingContext2D.setLineDash() - Web APIs
for example, [5, 15, 25] will become [5, 15, 25, 5, 15, 25].
... examples basic example this example uses the setlinedash() method to draw a dashed line above a solid line.
... html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); // dashed line ctx.beginpath(); ctx.setlinedash([5, 15]); ctx.moveto(0, 50); ctx.lineto(300, 50); ctx.stroke(); // solid line ctx.beginpath(); ctx.setlinedash([]); ctx.moveto(0, 100); ctx.lineto(300, 100); ctx.stroke(); result some common patterns this example illustrates a variety of common line dash patterns.
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.
... html <canvas id="canvas"></canvas> javascript var canvas = document.getelementbyid('canvas'); var ctx = canvas.getcontext('2d'); ctx.strokestyle = 'blue'; ctx.strokerect(10, 10, 100, 100); result creating multiple stroke colors using loops in this example, we use two for loops and the arc() method to draw a grid of circles, each having a different stroke color.
CanvasRenderingContext2D.strokeText() - Web APIs
examples drawing text outlines this example writes the words "hello world" using the stroketext() method.
... <canvas id="canvas" width="400" height="150"></canvas> javascript the javascript code for this example follows.
... result restricting the text size this example writes the words "hello world," restricting its width to 140 pixels.
CanvasRenderingContext2D.textAlign - Web APIs
for example, if textalign is "center", then the text's left edge will be at x - (textwidth / 2).
... examples general text alignment this example demonstrates the three "physical" values of the textalign property: "left", "center", and "right".
...s.getcontext('2d'); const x = canvas.width / 2; ctx.beginpath(); ctx.moveto(x, 0); ctx.lineto(x, canvas.height); ctx.stroke(); ctx.font = '30px serif'; ctx.textalign = 'left'; ctx.filltext('left-aligned', x, 40); ctx.textalign = 'center'; ctx.filltext('center-aligned', x, 85); ctx.textalign = 'right'; ctx.filltext('right-aligned', x, 130); result direction-dependent text alignment this example demonstrates the two direction-dependent values of the textalign property: "start" and "end".
CanvasRenderingContext2D - Web APIs
the canvas tutorial has more explanation, examples, and resources, as well.
... basic example to get a canvasrenderingcontext2d instance, you must first have an html <canvas> element to work with: <canvas id="my-house" width="300" height="300"></canvas> to get the canvas' 2d rendering context, call getcontext() on the <canvas> element, supplying '2d' as the argument: const canvas = document.getelementbyid('my-house'); const ctx = canvas.getcontext('2d'); with the context in hand, you can draw anything you like.
...for an example, see clipping paths in the canvas tutorial.
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.
... a clip example in this example, we'll use a circular clipping path to restrict the drawing of a set of random stars to a particular region.
Optimizing canvas - Web APIs
to avoid this, make sure to round all co-ordinates used in calls to drawimage() using math.floor(), for example.
... for example, let's say you have a game with a ui on top, the gameplay action in the middle, and a static background on the bottom.
...for example, draw a polyline instead of multiple separate lines.
ConvolverNode - Web APIs
convolvernode example the following example shows basic usage of an audiocontext to create a convolver node.
... note: you will need to find an impulse response to complete the example below.
... see this codepen for an applied example.
Credential Management API - Web APIs
for example, user agents have a particularly hard time dealing with federated identity providers or esoteric sign-in mechanisms that use more than just a username and password.
...for example, a password stored in login.example.com may be used to log in to www.example.com.
...openid connect is an example of such a framework.
DOMImplementation.createHTMLDocument() - Web APIs
example this example creates a new html document and inserts it into an <iframe> in the current document.
... here's the html for this example: <body> <p>click <a href="javascript:makedocument()">here</a> to create a new document and insert it below.</p> <iframe id="theframe" src="about:blank" /> </body> the javascript implementation of makedocument() follows: function makedocument() { let frame = document.getelementbyid("theframe"); let doc = document.implementation.createhtmldocument("new document"); let p = doc.createelement("p"); p.innerhtml = "this is a new paragraph."; try { doc.body.appendchild(p); } catch(e) { console.log(e); } // copy the new html document into the frame let destdocument = frame.contentdocument; let srcnode = doc.documentelement; let newnode = destdocument.importnode(srcnode, true); destdocument.replacechild(newnode, destdocument.do...
... view live examples the returned document is pre-constructed with the following html: <!doctype html> <html> <head> <title>title</title> </head> <body> </body> </html> specifications specification status comment domthe definition of 'domimplementation.createhtmldocument' in that specification.
DataTransfer.effectAllowed - Web APIs
example this example shows the use of the effectallowed and dropeffect properties.
... <!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 = " + ev.datatransfer.effectallowed); // add this element's id to the drag payload so the drop handler will // know which element to add to its tree ev.datatransfer.setdata("text", ev.target.id); ev.datatransfer.effectallowed = "move"; } function drop_handler(ev) { console.log("drop: 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> </...
DataTransfer.items - Web APIs
example this example shows the use of the items and types properties.
... <!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 tree ev.datatransfer.setdata("text/plain", ev.target.id); ev.datatransfer.effectallowed = "move"; } function drop_handler(ev) { console.log("drop: target.id = " + ev.target.id); ev.preventdefault(); // get the id of the target and add the moved element to the target's dom var data = ev.datatransfer.getdata("text"); ev.target.appendchild(document.ge...
...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);">d...
DataTransferItemList.remove() - Web APIs
example this example shows the use of the remove() method.
...paragraph ...</p>", "text/html"); datalist.add("http://www.example.org","text/uri-list"); } function drop_handler(ev) { console.log("drop"); ev.preventdefault(); var data = event.datatransfer.items; // loop through the dropped items and log their data for (var i = 0; i < data.length; i++) { if ((data[i].kind == 'string') && (data[i].type.match('^text/plain'))) { // this item is the target node data[i].getasstring(function (s){ ...
... } function dragover_handler(ev) { console.log("dragover"); ev.preventdefault(); // set the dropeffect to move ev.datatransfer.dropeffect = "move" } function dragend_handler(ev) { console.log("dragend"); var datalist = ev.datatransfer.items; for (var i = 0; i < datalist.length; i++) { datalist.remove(i); } // clear any remaining drag data datalist.clear(); } html <h1>example uses of <code>datatransferitemlist</code> methods and property</h1> <div> <p id="source" ondragstart="dragstart_handler(event);" ondragend="dragend_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</...
Document.createElement() - Web APIs
see web component example for more details.
... examples basic example this creates a new <div> and inserts it before the element with the id "div1".
...nt.createelement("div"); // and give it some content const newcontent = document.createtextnode("hi there and greetings!"); // add the text node to the newly created div newdiv.appendchild(newcontent); // add the newly created element and its content into the dom const currentdiv = document.getelementbyid("div1"); document.body.insertbefore(newdiv, currentdiv); } web component example the following example snippet is taken from our expanding-list-web-component example (see it live also).
Document.createElementNS() - Web APIs
important namespace uris html http://www.w3.org/1999/xhtml svg http://www.w3.org/2000/svg mathml http://www.w3.org/1998/math/mathml xul http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul xbl http://www.mozilla.org/xbl example this creates a new <div> element in the xhtml namespace and appends it to the vbox element.
...de = document.createtextnode("this is text that was constructed dynamically with createelementns and createtextnode then inserted into the document using appendchild."); newdiv.appendchild(txtnode); container.appendchild(newdiv); } ]]></script> <vbox id="containerbox" flex="1"> <html:div> the script on this page will add dynamic content below: </html:div> </vbox> </page> the example given above uses inline script which is not recommended in xhtml documents.
... this particular example is actually an xul document with embedded xhtml, however, the recommendation still applies.
Document.domain - Web APIs
WebAPIDocumentdomain
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".
... const currentdomain = document.domain; closing a window if a document, such as www.example.xxx/good.html, has the domain of "www.example.xxx", this example attempts to close the window.
... const baddomain = "www.example.xxx"; if (document.domain === baddomain) { // just an example: window.close() sometimes has no effect window.close(); } specifications specification status comment html living standardthe definition of 'document.domain' in that specification.
Document.getElementsByTagNameNS() - Web APIs
example in the following example getelementsbytagnamens starts from a particular parent element, and searches topdown recursively through the dom from that parent element, looking for child elements matching the tag name parameter.
... to use the following example, just copy/paste it into a new file saved with the .xhtml extension.
... <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>getelementsbytagnamens example</title> <script type="text/javascript"> function getallparaelems() { var allparas = document.getelementsbytagnamens("http://www.w3.org/1999/xhtml", "p"); var num = allparas.length; alert("there are " + num + " &lt;p&gt; elements in this document"); } function div1paraelems() { var div1 = document.getelementbyid("div1") var div1paras = div1.getelementsbytagnamens("http://www.w3.org/1999/xhtml", "p"); var num = div1paras.length; alert("there are " + num + " &lt;p&gt; elements in div1 element"); } function div2paraelems() { var div2 = document.getelementbyid("div2") var div2paras = div2.getelementsbytagnamens("http://www.w3.org/1999/xhtml", "p"); var num = div2paras.length; a...
Document.implementation - Web APIs
syntax domimpobj = document.implementation; example var modname = "html"; var modver = "2.0"; var conformtest = document.implementation.hasfeature( modname, modver ); alert( "dom " + modname + " " + modver + " supported?: " + conformtest ); // alerts with: "dom html 2.0 supported?: true" if dom level 2 html module is supported.
... notes the w3c's dom level 1 recommendation only specified the hasfeature method, which is one way to determine if a dom module is supported by a browser (see example above and what does your user agent claim to support?).
...for example, the domimplementation interface includes a createdocumenttype method with which dtds can be created for one or more documents managed by the implementation.
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.
Document.open() - Web APIs
WebAPIDocumentopen
for example: all event listeners currently registered on the document, nodes inside the document, or the document's window are removed.
... examples the following simple code opens the document and replaces its content with a number of different html fragments, before closing it again.
... this call, for example opens github.com in a new window, with its opener set to null: document.open('https://www.github.com','', 'noopener=true') two-argument document.open() browsers used to support a two-argument document.open(), with the following signature: document.open(type, replace) where type specified the mime type of the data you are writing (e.g.
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> wi...
... var container = document.queryselector("#test"); var matches = container.queryselectorall("div.highlighted > p"); this example uses an attribute selector to return a list of the <iframe> elements in the document that contain an attribute named data-src: var matches = document.queryselectorall("iframe[data-src]"); here, an attribute selector is used to return a list of the list items contained within a list whose id is userlist which have a data-active attribute whose value is 1: var container = document.queryselector("#userlist"); var matches = container.queryselectorall("li[data-active='1']"); accessing the matches once the nodelist of matching elements is returned, you can examine it just like any array.
... in this example, when selecting .outer .inner in the context the <div> with the class select, the element with the class .inner is still found, even though .outer is not a descendant of the base element on which the search is performed (.select).
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.
...this example optimizes thescroll event for requestanimationframe.
...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.
Document.write() - Web APIs
WebAPIDocumentwrite
example <html> <head> <title>write example</title> <script> function newcontent() { document.open(); document.write("<h1>out with the old, in with the new!</h1>"); document.close(); } </script> </head> <body onload="newcontent();"> <p>some original document content.</p> </body> </html> notes the text you write is parsed into the document's structure model.
... in the example above, the h1 element becomes a node in the document.
...for example: <script> document.write("<h1>main title</h1>") </script> note: document.write() and document.writeln do not work in xhtml documents (you'll get an "operation is not supported" [ns_error_dom_not_supported_err] error in the error console).
DocumentOrShadowRoot.elementFromPoint() - Web APIs
if the element at the specified point belongs to another document (for example, the document of an <iframe>), that document's parent element is returned (the <iframe> itself).
... if the element at the given point is anonymous or xbl generated content, such as a textbox's scroll bars, then the first non-anonymous ancestor element (for example, the textbox) is returned.
... example this example creates two buttons which let you set the current color of the paragraph element located under the coordinates (2, 2).
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.
...the following simple example shows how an event object is passed to the event handler function, and can be used from within one such function.
Using the W3C DOM Level 1 Core - Web APIs
for example, the following document <html> <head> <title>my document</title> </head> <body> <h1>header</h1> <p>paragraph</p> </body> </html> has a dom tree that looks like this: (note that, although the above tree is similar to the above document's dom tree, it's not identical, as the actual dom tree preserves whitespace.) when a web browser parses an html document, it builds a dom tree and then...
... a simple example suppose the author wants to change the header of the above document and write two paragraphs instead of one.
...graph."); // create a new element to be the second paragraph var newelement = document.createelement("p"); // put the text in the paragraph newelement.appendchild(newtext); // and put the paragraph on the end of the document by appending it to // the body (which is the parent of para) para.parentnode.appendchild(newelement); } you can see this script as a complete example.
Element.animate() - Web APIs
WebAPIElementanimate
0.5 would indicate starting halfway through the first iteration for example, and with this value set, an animation with 2 iterations would end halfway through a third iteration.
... 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.
...for example, consider this simple animation — the keyframe object looks like so: let rotate360 = [ { transform: 'rotate(360deg)' } ]; we have only specified the end state of the animation, and the beginning state is implied.
Element.attachShadow() - Web APIs
there are some that can't have a shadow dom for security reasons (for example <a>), and more besides.
...this can be one of: open: elements of the shadow root are accessible from javascript outside the root, for example using element.shadowroot: element.shadowroot; // returns a shadowroot obj closed: denies access to the node(s) of a closed shadow root from javascript outside it: element.shadowroot; // returns null delegatesfocus a boolean that, when set to true, specifies behavior that mitigates custom element issues around focusability.
... examples the following example is taken from our word-count-web-component demo (see it live also).
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.
... the following example runs through the attribute nodes for the element in the document with id "paragraph", and prints each attribute's value.
... <!doctype html> <html> <head> <title>attributes example</title> <script type="text/javascript"> function listattributes() { var paragraph = document.getelementbyid("paragraph"); var result = document.getelementbyid("result"); // first, let's verify that the paragraph has some attributes if (paragraph.hasattributes()) { var attrs = paragraph.attributes; var output = ""; for(var i = attrs.length - 1; i >= 0; i--) { output += attrs[i].name + "->" + attrs[i].value; } result.value = output; } else { result.value = "no attributes to show"; } } </script> </head> <body> <p id="paragraph" style="color: green;">sample paragraph</p> <form action=""> <p> <input type="button" value="show first attribut...
Element: fullscreenchange event - Web APIs
examples in this example, a handler for the fullscreenchange event is added to the element whose id is fullscreen-div.
... what that means to the example code is that, if an element is currently in full-screen mode, the fullscreenchange handler logs the id of the full-screen element to the console.
... html <h1>fullscreenchange event example</h1> <div id="fullscreen-div"> <button id="toggle-fullscreen">toggle fullscreen mode</button> </div> javascript document.getelementbyid('fullscreen-div').addeventlistener('fullscreenchange', (event) => { // document.fullscreenelement will point to the element that // is in fullscreen mode if there is one.
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.
Element: paste event - Web APIs
bubbles yes cancelable yes interface clipboardevent event handler property onpaste if the cursor is in an editable context (for example, in a <textarea> or an element with contenteditable attribute set to true) then the default action is to insert the contents of the clipboard into the document at the cursor position.
... to override the default behavior (for example to insert some different data or a transformation of the clipboard contents) an event handler must cancel the default action using event.preventdefault(), and then insert its desired data manually.
... 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'); target.addeventlistener('paste', (event) => { let paste = (event.clipboarddata || window.clipboarddata).getdata('text'); paste = paste.touppercase(); const selection = window.getselection(); if (!selection.rangecount) return false; selection.deletefromdocument();...
Element.querySelector() - Web APIs
examples let's consider a few examples.
... find a specific element with specific values of an attribute in this first example, the first <style> element which either has no type or has type "text/css" in the html document body is returned: var el = document.body.queryselector("style[type='text/css'], style:not([type])"); the entire hierarchy counts this example demonstrates that the hierarchy of the entire document is considered when applying selectors, so that levels outside the specified baseelement are still considered when locating matches.
... 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.
...this example optimizes thescroll event for requestanimationframe.
... 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.
Element.setCapture() - Web APIs
example in this example, the current mouse coordinates are drawn while you mouse around after clicking and holding down on an element.
... <html> <head> <title>mouse capture example</title> <style type="text/css"> #mybutton { border: solid black 1px; color: black; padding: 2px; box-shadow: black 2px 2px; } </style> <script type="text/javascript"> function init() { var btn = document.getelementbyid("mybutton"); if (btn.setcapture) { btn.addeventlistener("mousedown", mousedown, false); btn.addeventlistener("mouseup", mouseup, false); } else { document.getelementbyid("output").innerhtml = "sorry, there appears to be no setcapture support on this browser"; } } function mousedown(e) { e.target.setcapture(); e.target.addeventlistener("mousemove", mousemoved, false); } function mouseup(e) { e.target.r...
...emoveeventlistener("mousemove", mousemoved, false); } function mousemoved(e) { var output = document.getelementbyid("output"); output.innerhtml = "position: " + e.clientx + ", " + e.clienty; } </script> </head> <body onload="init()"> <p>this is an example of how to use mouse capture on elements in gecko 2.0.</p> <p><a id="mybutton" href="#">test me</a></p> <div id="output">no events yet</div> </body> </html> view live examples notes the element may not be scrolled completely to the top or bottom, depending on the layout of other elements.
Element.tagName - Web APIs
WebAPIElementtagName
for example, if the element is an <img>, its tagname property is "img" (for html documents; it may be cased differently for xml/xhtml documents).
...for example, tagname called on a <div> element returns "div".
... example html <span id="born">when i was born...</span> javascript var span = document.getelementbyid("born"); console.log(span.tagname); in xhtml (or any other xml format), the original case will be maintained, so "span" would be output in case the original tag name was created lowercase.
Comparison of Event Targets - Web APIs
for example, mouse events are retargeted to their parent node when they happen over text nodes (bug 185889), and in that case .target will show the parent and .explicitoriginaltarget will show the text node.
... 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; ...
... example <hbox id="outer"> <hbox id="inner" onmouseover="dump('mouseover ' + event.relatedtarget.id + ' > ' + event.target.id + '\n');" onmouseout="dump('mouseout ' + event.target.id + ' > ' + event.relatedtarget.id + '\n');" style="margin: 100px; border: 10px solid black; width: 100px; height: 100px;" /> </hbox> ...
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 first definition looks like this, for example: customelements.define('open-shadow', class extends htmlelement { constructor() { super(); let pelem = document.createelement('p'); pelem.textcontent = this.getattribute('text'); let shadowroot = this.attachshadow({mode: 'open'}) .appendchild(pelem); } }); we then insert one of each element into our page: <open-shadow text="i have an open shadow root"></open-shadow> <closed-shadow text="i have a closed shadow root"></closed-shadow> then include a click event listener on the <html> element: document.queryselector('html').addeventlistener('click',function(e) { console.lo...
...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.
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.
...though there's only one cache in this example, the same approach can be used for multiple caches.
...in this example, www.chromium.org doesn't support cors.
FetchEvent.respondWith() - Web APIs
for example, if an <img> initiates the request, the response body needs to be image data.
... this means, for example, if a service worker intercepts a stylesheet or worker script, then the provided response.url will be used to resolve any relative @import or importscripts() subresource loads (bug 1222008).
... examples this fetch event tries to return a response from the cache api, falling back to the network otherwise.
FileList - Web APIs
WebAPIFileList
for example, if the html includes the following file input: <input id="fileitem" type="file"> the following line of code fetches the first file in the node's file list as a file object: var file = document.getelementbyid('fileitem').files[0]; method overview file item(index); properties attribute type description length integer a read-only value indicatin...
... example this example iterates over all the files selected by the user using an input element: // fileinput is an html input element: <input type="file" id="myfileinput" multiple> var fileinput = document.getelementbyid("myfileinput"); // files is a filelist object (similar to nodelist) var files = fileinput.files; var file; // loop through files for (var i = 0; i < files.length; i++) { // get item file = files.item(i); //or file = files[i]; alert(file.name); } he...
...re is a complete example.
FileReader.readAsDataURL() - Web APIs
example html <input type="file" onchange="previewfile()"><br> <img src="" height="200" alt="image preview..."> javascript function previewfile() { const preview = document.queryselector('img'); const file = document.queryselector('input[type=file]').files[0]; const reader = new filereader(); reader.addeventlistener("load", function () { // convert image file to base64 string preview.
...src = reader.result; }, false); if (file) { reader.readasdataurl(file); } } live result example reading multiple files html <input id="browse" type="file" onchange="previewfiles()" multiple> <div id="preview"></div> javascript function previewfiles() { var preview = document.queryselector('#preview'); var files = document.queryselector('input[type=file]').files; function readandpreview(file) { // make sure `file.name` matches our extensions criteria if ( /\.(jpe?g|png|gif)$/i.test(file.name) ) { var reader = new filereader(); reader.addeventlistener("load", function () { var image = new image(); image.height = 100; image.title = file.name; image.src = this.result; preview.appendchild( image ); }, fals...
...see also this more powerful example.
Fullscreen API - Web APIs
example in this example, a video is presented in a web page.
... 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.
...in a real-world deployment, at this time, you'll want to check for prefixed versions of this (mozfullscreenelement, msfullscreenelement, or webkitfullscreenelement, for example).
Geolocation API - Web APIs
concepts and usage you will often want to retrieve a user's location information in your web app, for example to plot their location on a map, or display personalized information relevant to their location.
...if they accept, then the browser will use the best available functionality on the device to access this information (for example, gps).
... examples in the following example the geolocation api is used to retrieve the user's latitude and longitude.
GlobalEventHandlers.onclick - Web APIs
examples detecting clicks this example simply changes the color of an element when it's clicked upon.
... html <div id="demo">click here</div> javascript document.getelementbyid('demo').onclick = function changecontent() { document.getelementbyid('demo').innerhtml = "help me"; document.getelementbyid('demo').style = "color: red"; } result getting the coordinates of clicks this example displays the coordinates at which the most recent mouse button click occurred.
... html <p>click anywhere in this example.</p> <p id="log"></p> javascript let log = document.getelementbyid('log'); document.onclick = inputchange; function inputchange(e) { log.textcontent = `position: (${e.clientx}, ${e.clienty})`; } result specification specification status comment html living standardthe definition of 'onclick' in that specification.
GlobalEventHandlers.ondrag - Web APIs
example this example includes the use of the ondrag attribute handler to set an element's drag event handler.
... <!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> <!-- <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 status comment html living standardthe definition of 'ondrag' in that specification.
GlobalEventHandlers.ondragend - Web APIs
example this example shows two ways to use the ondragend attribute handler to set an element's dragend event handler.
... <!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 = "dashed"; ev.datatransfer.setdata("text", ev.target.id); } function dragover_handler(ev) { console.log("dragover"); // change the target element's border to signify a drag over event // has occurred ev.currenttarget.style.background = "lightblue"; ev.preventdefault(); } function drop_handler(ev) {...
...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 z...
GlobalEventHandlers.ondragenter - Web APIs
example this example demonstrates using the ondragenter attribute handler to set an element's dragenter event handler.
... <!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 = "dashed"; ev.datatransfer.setdata("text", ev.target.id); } function dragover_handler(ev) { console.log("dragover"); // change the target element's border to signify a drag over event // has occurred ev.currenttarget.style.background = "lightblue"; ev.preventdefault(); } function drop_handler(ev) {...
...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 z...
GlobalEventHandlers.ondragexit - Web APIs
example this example demonstrates using the ondragexit attribute handler to set an element's dragexit event handler.
... <!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 = "dashed"; ev.datatransfer.setdata("text", ev.target.id); } function dragover_handler(ev) { console.log("dragover"); // change the target element's border to signify a drag over event // has occurred ev.currenttarget.style.background = "lightblue"; ev.preventdefault(); } function drop_handler(ev) {...
...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 z...
GlobalEventHandlers.ondragleave - Web APIs
example this example demonstrates using the ondragleave attribute handler to set an element's dragleave event handler.
... <!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 = "dashed"; ev.datatransfer.setdata("text", ev.target.id); } function dragover_handler(ev) { console.log("dragover"); // change the target element's background color to signify a drag over event // has occurred ev.currenttarget.style.background = "lightblue"; ev.preventdefault(); } function drop_handler(ev) {...
...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 z...
GlobalEventHandlers.ondragover - Web APIs
example this example demonstrates using the ondragover attribute handler to set an element's dragover event handler.
... <!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 specification status comment html living standardthe definition of 'ondragover' in that specification.
GlobalEventHandlers.ondragstart - Web APIs
example this example demonstrates using the ondragstart attribute handler to set an element's dragstart event handler.
... <!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 specification status comment html living standardthe definition of 'ondragstart' in that specification.
GlobalEventHandlers.ondrop - Web APIs
example this example demonstrates the use of the ondrop attribute to define an element's drop event handler.
... <!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 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 status comment html living standardthe definition of 'ondrop' in that specification.
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.
... the code snippet below, for example, takes the image in the <canvas> element whose id is "canvas", obtains a copy of it as a png image, then appends a new <img> element to the document, whose source image is the one created using the canvas.
...for example, to get the image in jpeg format: canvas.toblob(function(blob){...}, 'image/jpeg', 0.95); // jpeg at 95% quality a way to convert a canvas to an ico (mozilla only) this uses -moz-parse to convert the canvas to ico.
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 qualit...
...y with jpegs var fullquality = canvas.todataurl('image/jpeg', 1.0); // data:image/jpeg;base64,/9j/4aaqskzjrgabaq...9oadambaairaxeapwd/ad/6ap/z" var mediumquality = canvas.todataurl('image/jpeg', 0.5); var lowquality = canvas.todataurl('image/jpeg', 0.1); example: dynamically change images you can use this technique in coordination with mouse events in order to dynamically change images (gray-scale vs.
... color in this example): html <img class="grayscale" src="mypicture.png" alt="description of my picture" /> javascript window.addeventlistener('load', removecolors); function showcolorimg() { this.style.display = 'none'; this.nextsibling.style.display = 'inline'; } function showgrayimg() { this.previoussibling.style.display = 'inline'; this.style.display = 'none'; } function removecolors() { var aimages = document.getelementsbyclassname('grayscale'), nimgslen = aimages.length, ocanvas = document.createelement('canvas'), octx = ocanvas.getcontext('2d'); for (var nwidth, nheight, oimgdata, ograyimg, npixel, apix, npixlen, nimgid = 0; nimgid < nimgslen; nimgid++) { ocolorimg = aimages[nimgid]; nwidth = ocolorimg.offsetwidth; nheight = ocolorimg.offset...
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.
...r('.animated'); animated.addeventlistener('animationcancel', () => { console.log('animation canceled'); }); animated.style.display = 'none'; the same, but using the onanimationcancel property instead of addeventlistener(): const animated = document.queryselector('.animated'); animated.onanimationcancel = () => { console.log('animation canceled'); }; animated.style.display = 'none'; live example html <div class="animation-example"> <div class="container"> <p class="animation">you chose a cold night to visit our planet.</p> </div> <button class="activate" type="button">activate animation</button> <div class="event-log"></div> </div> css .container { height: 3rem; } .event-log { width: 25rem; height: 2rem; border: 1px solid black; margin: 0.2rem; p...
...adding: 0.2rem; } .animation.active { animation-duration: 2s; animation-name: slidein; animation-iteration-count: 2; } @keyframes slidein { from { transform: translatex(100%) scalex(3); } to { transform: translatex(0) scalex(1); } } js const animation = document.queryselector('p.animation'); const animationeventlog = document.queryselector('.animation-example>.event-log'); const applyanimation = document.queryselector('.animation-example>button.activate'); let iterationcount = 0; animation.addeventlistener('animationstart', () => { animationeventlog.textcontent = `${animationeventlog.textcontent}'animation started' `; }); animation.addeventlistener('animationiteration', () => { iterationcount++; animationeventlog.textcontent = `${animationeventlog.textcontent}'a...
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.lo...
...g('animation ended'); }; live example html <div class="animation-example"> <div class="container"> <p class="animation">you chose a cold night to visit our planet.</p> </div> <button class="activate" type="button">activate animation</button> <div class="event-log"></div> </div> css .container { height: 3rem; } .event-log { width: 25rem; height: 2rem; border: 1px solid black; margin: .2rem; padding: .2rem; } .animation.active { animation-duration: 2s; animation-name: slidein; animation-iteration-count: 2; } @keyframes slidein { from { margin-left: 100%; width: 300%; } to { margin-left: 0%; width: 100%; } } js const animation = document.queryselector('p.animation'); const animationeventlog = document.queryselector('.anim...
...ation-example>.event-log'); const applyanimation = document.queryselector('.animation-example>button.activate'); let iterationcount = 0; animation.addeventlistener('animationstart', () => { animationeventlog.textcontent = `${animationeventlog.textcontent}'animation started' `; }); animation.addeventlistener('animationiteration', () => { iterationcount++; animationeventlog.textcontent = `${animationeventlog.textcontent}'animation iterations: ${iterationcount}' `; }); animation.addeventlistener('animationend', () => { animationeventlog.textcontent = `${animationeventlog.textcontent}'animation ended'`; animation.classlist.remove('active'); applyanimation.textcontent = "activate animation"; }); animation.addeventlistener('animationcancel', () => { animationeventlog.textcontent = `${...
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:...
... const animated = document.queryselector('.animated'); let iterationcount = 0; animated.onanimationiteration = () => { iterationcount++; console.log(`animation iteration count: ${iterationcount}`); }; live example html <div class="animation-example"> <div class="container"> <p class="animation">you chose a cold night to visit our planet.</p> </div> <button class="activate" type="button">activate animation</button> <div class="event-log"></div> </div> css .container { height: 3rem; } .event-log { width: 25rem; height: 2rem; border: 1px solid black; margin: 0.2rem; padding: 0.2rem; } .animation.active { animation-duration: 2s; animation-name: slidein; animation-iteration-count: 2; } @keyframes slidein { from { transform: translatex(100...
...%) scalex(3); } to { transform: translatex(0) scalex(1); } } js const animation = document.queryselector('p.animation'); const animationeventlog = document.queryselector('.animation-example>.event-log'); const applyanimation = document.queryselector('.animation-example>button.activate'); let iterationcount = 0; animation.addeventlistener('animationstart', () => { animationeventlog.textcontent = `${animationeventlog.textcontent}'animation started' `; }); animation.addeventlistener('animationiteration', () => { iterationcount++; animationeventlog.textcontent = `${animationeventlog.textcontent}'animation iterations: ${iterationcount}' `; }); animation.addeventlistener('animationend', () => { animationeventlog.textcontent = `${animationeventlog.textcontent}'animation ended'`; ...
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'); };...
... live example html <div class="animation-example"> <div class="container"> <p class="animation">you chose a cold night to visit our planet.</p> </div> <button class="activate" type="button">activate animation</button> <div class="event-log"></div> </div> css .container { height: 3rem; } .event-log { width: 25rem; height: 2rem; border: 1px solid black; margin: 0.2rem; padding: 0.2rem; } .animation.active { animation-duration: 2s; animation-name: slidein; animation-iteration-count: 2; } @keyframes slidein { from { transform: translatex(100%) scalex(3); } to { transform: translatex(0) scalex(1); } } js const animation = document.queryselector('p.animation'); const animationeventlog = document.queryselector('.animation-example>.ev...
...ent-log'); const applyanimation = document.queryselector('.animation-example>button.activate'); let iterationcount = 0; animation.addeventlistener('animationstart', () => { animationeventlog.textcontent = `${animationeventlog.textcontent}'animation started' `; }); animation.addeventlistener('animationiteration', () => { iterationcount++; animationeventlog.textcontent = `${animationeventlog.textcontent}'animation iterations: ${iterationcount}' `; }); animation.addeventlistener('animationend', () => { animationeventlog.textcontent = `${animationeventlog.textcontent}'animation ended'`; animation.classlist.remove('active'); applyanimation.textcontent = "activate animation"; }); animation.addeventlistener('animationcancel', () => { animationeventlog.textcontent = `${animationeventlog...
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 canc...
...eled'); }; live example in the following example, we have a simple <div> element, styled with a transition that includes a delay: <div class="transition"></div> <div class="message"></div> .transition { width: 100px; height: 100px; background: rgba(255,0,0,1); transition-property: transform background; transition-duration: 2s; transition-delay: 2s; } .transition:hover { transform: rotate(90deg); background: rgba(255,0,0,0); } to this, we'll add some javascript to indicate that the transitionstart, transitionrun, transitioncancel and transitionend events fire.
... in this example, to cancel the transition, stop hovering over the transitioning box before the transition ends.
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 = () => { ...
...console.log('transition ended'); }; 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> .transition { width: 100px; height: 100px; background: rgba(255,0,0,1); transition-property: transform background; transition-duration: 2s; transition-delay: 1s; } .transition:hover { transform: rotate(90deg); background: rgba(255,0,0,0); } to this, we'll add some javascript to indicate that the transitionstart, transitionrun, transitioncancel and transitionend events fire.
... in this example, to cancel the transition, stop hovering over the transitioning box before the transition ends.
HTMLFormElement - Web APIs
for example: <input name="id"> will take precedence over <form id="…">.
... 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 infor...
... f.action = "a-different-url.cgi"; f.name = "a-different-name"; } </script> submit a <form> into a new window: <!doctype html> <html> <head> <meta charset="utf-8"> <title>example new-window form submission</title> </head> <body> <form action="test.php" target="_blank"> <p><label>first name: <input type="text" name="firstname"></label></p> <p><label>last name: <input type="text" name="lastname"></label></p> <p><label><input type="password" name="pwd"></label></p> <fieldset> <legend>pet preference</legend> <p><label><input type="radio" name="pet" value="ca...
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.
... example the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
HTMLInputElement.setSelectionRange() - Web APIs
this lets you indicate, for example, that the selection was set by the user clicking and dragging from the end of the selected text toward the beginning.
...for example, on input of type number: "failed to read the 'selectionstart' property from 'htmlinputelement': the input element's type ('number') does not support selection".
... example click the button in this example to select the third, fourth, and fifth characters in the text box ("zil" in the word "mozilla").
HTMLInputElement.stepUp() - Web APIs
input type default step value example step declaration date 1 (day) 7 day (one week) increments: <input type="date" min="2019-12-25" step="7"> month 1 (month) 12 month (one year) increments: <input type="month" min="2019-12" step="12"> week 1 (week) two week increments: <input type="week" min="2019-w23" step="2"> time 60 (seconds) 900 second (15 minute) increment...
... if the value before invoking the stepup() method is invalid—for example, if it doesn't match the constraints set by the step attribute—invoking the stepup() method will return a value that does match the form controls constraints.
... example click the button in this example to increment the number input type: html <p> <label>enter a number between 0 and 400 that is divisible by 5: <input type="number" step="5" id="thenumber" min="0" max="400"> </label> </p> <p> <label>enter how many values of step you would like to increment by or leave it blank: <input type="number" step="1" id="incrementer" min="0" max="25"> </labe...
HTMLMediaElement.captureStream() - Web APIs
this can be used, for example, as a source for a webrtc rtcpeerconnection.
... example in this example, an event handler is established so that clicking a button starts capturing the contents of a media element with the id "playback" into a mediastream.
... document.queryselector('.playandrecord').addeventlistener('click', function() { var playbackelement = document.getelementbyid("playback"); var capturestream = playbackelement.capturestream(); playbackelement.play(); }); see recording a media element for a longer and more intricate example and explanation.
HTMLMediaElement.readyState - Web APIs
have_future_data 3 data for the current playback position as well as for at least a little bit of time into the future is available (in other words, at least two frames of video, for example).
... examples this example will listen for audio data to be loaded for the element `example`.
... <audio id="example" preload="auto"> <source src="sound.ogg" type="audio/ogg" /> </audio> var obj = document.getelementbyid('example'); obj.addeventlistener('loadeddata', function() { if(obj.readystate >= 2) { obj.play(); } }); specifications specification status comment html living standardthe definition of 'htmlmediaelement.readystate' in that specification.
HTMLOrForeignElement.dataset - Web APIs
for example, the attribute named data-abc-def corresponds to the key abcdef.
... for example: null is converted into the string "null".
... 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.dateofbirth; // result: el.dataset.dateofbirth === undefined // 'somedataattr' in el.dataset === false el.dataset.somedataattr = 'mydata'; // result: 'somedataattr' in el.dataset === true specifications specification status comment ...
HTMLSelectElement - Web APIs
htmlselectelement.autofocus a boolean reflecting the autofocus html attribute, which indicates whether the control should have input focus when the page loads, unless the user overrides it, for example by typing in a different control.
... example get information about the selected option /* assuming we have the following html <select id='s'> <option>first</option> <option selected>second</option> <option>third</option> </select> */ var select = document.getelementbyid('s'); // return the index of the selected option console.log(select.selectedindex); // 1 // return the value of the selected option console.log(select.optio...
...see the example provided in the documentation for the change event for details.
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="nosc...
...rollbars" onkeyup="autogrow(this);"></textarea></p> <p><input type="submit" value="send" /></p> </fieldset> </form> insert html tags example insert some html tags or smiles or any custom text in a textarea.
...</textarea></p> </form> maximum length and number of lines example create a textarea with a maximum number of characters per line and a maximum number of lines: first, create a function that takes the text field and a key event as input and determines if any of the limits have been reached.
Headers - Web APIs
WebAPIHeaders
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.
...see their dedicated pages for example code.
... 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...
Working with the History API - Web APIs
example of pushstate() method suppose http://mozilla.org/foo.html executes the following javascript: let stateobj = { foo: "bar", } history.pushstate(stateobj, "page 2", "bar.html") this will cause the url bar to display http://mozilla.org/bar.html, but won't cause the browser to load bar.html or even check that bar.html exists.
... example of replacestate() method suppose http://mozilla.org/foo.html executes the following javascript: let stateobj = { foo: "bar" } history.pushstate(stateobj, "page 2", "bar.html") the explanation of these two lines above can be found at the above section example of pushstate() method section.
... this can happen, for example, if the page sets a state object (using pushstate() or replacestate()) and then the user restarts their browser.
IDBCursor.direction - Web APIs
the direction read-only property of the idbcursor interface is a domstring that returns the direction of traversal of the cursor (set using idbobjectstore.opencursor for example).
... example 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.
...for a complete working example, see our idbcursor example (view example live.) function backwards() { list.innerhtml = ''; var transaction = db.transaction(['rushalbumlist'], 'readonly'); var objectstore = transaction.objectstore('rushalbumlist'); objectstore.opencursor(null,'prev').onsuccess = function(event) { var cursor = event.target.result; if(cursor) { var listitem = document.createelement('li...
IDBCursor.update() - Web APIs
WebAPIIDBCursorupdate
example 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.
...note also that you can't directly put cursor.value into an update call, hence the below example using an intermediary updatedata variable.
...for a complete working example, see our idbcursor example (view example live.) function updateresult() { list.innerhtml = ''; const transaction = db.transaction(['rushalbumlist'], 'readwrite'); const objectstore = transaction.objectstore('rushalbumlist'); objectstore.opencursor().onsuccess = function(event) { const cursor = event.target.result; if (cursor) { if (cursor.value.albumtitle === 'a farewell to kings') { const updatedata = cursor.value; updatedata.year = 2050; const request = cursor.update(updatedata); ...
IDBDatabase: close event - Web APIs
this could happen, for example, if the underlying storage is removed or if the user clears the database in the browser's history preferences.
... 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 will contain objectstore.createindex('hours', 'hours', { unique: false }); objectstore.createindex('minutes', 'minutes', { unique: false }); objectstore.createindex...
...('day', 'day', { unique: false }); objectstore.createindex('month', 'month', { unique: false }); objectstore.createindex('year', 'year', { unique: false }); }; dbopenrequest.onsuccess = (event) => { const db = dbopenrequest.result; db.addeventlistener('close', () => { console.log('database connection closed'); }); }; the same example, using the onclose property instead of addeventlistener(): // 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 objectstore.createindex('hours', 'hours', {...
IDBIndex - Web APIs
WebAPIIDBIndex
properties idbindex.isautolocale read only returns a boolean indicating whether the index had a locale value of auto specified upon its creation (see createindex()'s optionalparameters.) idbindex.locale read only returns the locale of the index (for example en-us, or pl) if it had a locale value specified upon its creation (see createindex()'s optionalparameters.) idbindex.name the name of this index.
... example in the following example we open a transaction and an object store, then get the index lname from a simple contacts database.
...for a complete working example, see our idbindex-example demo repo (view the example live.) function displaydatabyindex() { tableentry.innerhtml = ''; var transaction = db.transaction(['contactslist'], 'readonly'); var objectstore = transaction.objectstore('contactslist'); var myindex = objectstore.index('lname'); myindex.opencursor().onsuccess = function(event) { var cursor = event.target.result; if(cursor) { var tablerow = document.creat...
IDBKeyRange - Web APIs
for example, you can iterate over all values of a key in the value range a–z.
... examples the following example illustrates how you'd use a key range.
... note: for a more complete example allowing you to experiment with key range, have a look at our idbkeyrange-example 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 =...
IDBObjectStore.index() - Web APIs
the index() method of the idbobjectstore interface opens a named index in the current object store, after which it can be used to, for example, return a series of records sorted by that index using a cursor.
... example in the following example we open a transaction and an object store, then get the index lname from a simple contacts database.
...for a complete working example, see our idbindex-example demo repo (view the example live.) function displaydatabyindex() { tableentry.innerhtml = ''; var transaction = db.transaction(['contactslist'], 'readonly'); var objectstore = transaction.objectstore('contactslist'); var myindex = objectstore.index('lname'); myindex.opencursor().onsuccess = function(event) { var cursor = event.target.result; if(cursor) { var tablerow = document.creat...
IDBObjectStore - Web APIs
idbobjectstore.index() opens an index from this object store after which it can, for example, be used to return a sequence of records sorted by that index using a cursor.
... example this example shows a variety of different uses of object stores, from updating the data structure with idbobjectstore.createindex inside an onupgradeneeded function, to adding a new item to our object store with idbobjectstore.add.
... for a full working example, see our to-do notifications app (view example live.) // let us open our database var dbopenrequest = window.indexeddb.open("todolist", 4); dbopenrequest.onsuccess = function(event) { note.innerhtml += '<li>database initialised.</li>'; // store the result of opening the database in db.
IDBOpenDBRequest.onupgradeneeded - Web APIs
inside the event handler function you can include code to upgrade the database structure, as shown in the example below.
...}; example in the following example you can see the onupgradeneeded handler being used to update the database structure if a database with a higher version number is loaded.
... for a full working example, see our to-do notifications app (view example live.) var db; // request version 3 of the database.
IDBRequest.transaction - Web APIs
example the following example requests a given record title, onsuccess gets the associated record from the idbobjectstore (made available as objectstoretitlerequest.result), updates one property of the record, and then puts the updated record back into the object store in another request.
...for a full working example, see our to-do notifications app (view example live.) var title = "walk dog"; // open up a transaction as usual var objectstore = db.transaction(['todolist'], "readwrite").objectstore('todolist'); // get the to-do list object that has this title as it's title var objectstoretitlerequest = objectstore.get(title); objectstoretitlerequest.onsuccess = function() { // grab the data object returned as the result var data = objectstoretitlerequest.result; // update the notified value in the object to "yes" data.notified = "yes"; // create another request that inserts the item back // into the database var updatetitlerequest = objectstore.put(data); ...
... // log the transaction that originated this request console.log("the transaction that originated this request is " + updatetitlerequest.transaction); // when this new request succeeds, run the displaydata() // function again to update the display updatetitlerequest.onsuccess = function() { displaydata(); }; }; this example shows how a the transaction property can be used during a version upgrade to access existing object stores:​ var openrequest = indexeddb.open('db', 2); console.log(openrequest.transaction); // will log "null".
IDBRequest - Web APIs
this property can be null for certain requests, for example those returned from idbfactory.open unless an upgrade is needed.
... example in the following code snippet, we open a database asynchronously and make a request; onerror and onsuccess functions are included to handle the success and error cases.
... for a full working example, see our to-do notifications app (view example live.) var db; // let us open our database var dbopenrequest = window.indexeddb.open("todolist", 4); // these two event handlers act on the database being // opened successfully, or not dbopenrequest.onerror = function(event) { note.innerhtml += '<li>error loading database.</li>'; }; dbopenrequest.onsuccess = function(event) { note.innerhtml += '<li>database initialised.</li>'; // store the result of opening the database.
IDBTransaction: abort event - Web APIs
bubbles yes cancelable no interface event event handler property onabort this can happen for any of the following reasons: bad requests, (for example, trying to add the same key twice, or put the same index key when the key has a uniqueness constraint), an explicit abort() call an uncaught exception in the request's success/error handler, an i/o error (an actual failure to write to disk, for example disk detached, or other os/hardware failure) quota exceeded.
... 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.
... dbopenrequest.onsuccess = event => { const db = dbopenrequest.result; // open a read/write db transaction, ready for adding the data const transaction = db.transaction(['todolist'], 'readwrite'); // add a listener for `abort` transaction.addeventlistener('abort', () => { console.log('transaction was aborted'); }); // abort the transaction transaction.abort(); }; the same example, but assigning the event handler to the onabort property: // 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...
IDBTransaction.error - Web APIs
it can be a reference to the same error as the request object that raised it, or a transaction failure (for example quotaexceedederror or unknownerror).
... example in the following code snippet, we open a read/write transaction on our database and add some data to an object store.
...for a full working example, see our to-do notifications app (view example live.) // let us open our database var dbopenrequest = window.indexeddb.open("todolist", 4); dbopenrequest.onsuccess = function(event) { note.innerhtml += '<li>database initialised.</li>'; // store the result of opening the database in the db variable.
IDBTransaction - Web APIs
4f7f8" stroke="#d4dde4" stroke-width="2px" /><text x="221" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">idbtransaction</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} transactions are started when the transaction is created, not when the first request is placed; for example consider this: var trans1 = db.transaction("foo", "readwrite"); var trans2 = db.transaction("foo", "readwrite"); var objectstore2 = trans2.objectstore("foo") var objectstore1 = trans1.objectstore("foo") objectstore2.put("2", "key"); objectstore1.put("1", "key"); after the code is executed the object store should contain the value "2", since trans2 should run after trans1.
...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.
...for a full working example, see our to-do notifications app (view example live.) // let us open our database var dbopenrequest = window.indexeddb.open("todolist", 4); dbopenrequest.onsuccess = function(event) { note.innerhtml += '<li>database initialised.</li>'; // store the result of opening the database in the db // variable.
ImageCapture - Web APIs
example the following code is taken from chrome's grab frame - take photo sample.
... since imagecapture requires some place to capture an image from, the example below starts with a device's media device (in other words a camera).
... this example shows, roughly, a mediastreamtrack extracted from a device's mediastream.
ImageData.data - Web APIs
WebAPIImageDatadata
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.
... let imagedata = new imagedata(100, 100); console.log(imagedata.data); // uint8clampedarray[40000] console.log(imagedata.data.length); // 40000 filling a blank imagedata object this example creates and fills a new imagedata object with colorful pixels.
...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().
Browser storage limits and eviction criteria - Web APIs
this will only be evicted if the user chooses to (for example, in firefox you can choose to delete all stored data or only stored data from selected origins by going to preferences and using the options under privacy & security > cookies & site data).
...this will cause storage initialization to fail; for example, open() will fire an error event.
...for example: mozilla.org — group1, origin1 www.mozilla.org — group1, origin2 joe.blogs.mozilla.org — group1, origin3 firefox.com — group2, origin4 in this group, mozilla.org, www.mozilla.org, and joe.blogs.mozilla.org can aggregately use a maximum of 20% of the global limit.
InputEvent.inputType - Web APIs
possible changes include for example inserting, deleting, and formatting text.
... examples this example logs the inputtype for input events on an editable <div>.
... note: see also masayuki nakano's inputevent test suite for a more detailed example.
KeyboardEvent.code - Web APIs
for example, the code returned is "keyq" for the q key on a qwerty layout keyboard, but the same code value also represents the ' key on dvorak keyboards and the a key on azerty keyboards.
... 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='" + event.code + "'"; let el = do...
... handle keyboard events in a game this example establishes an event listener for keydown events that handle keyboard input for a game that uses the typical "wasd" keyboard layout for steering forward, left, backward, and right.
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.
... if more function keys are available, their names continue the pattern here by continuing to increment the numeric portion of each key's name, so that, for example, "f24" is a valid key value.
KeyboardEvent.location - Web APIs
dom_key_location_left 1 the key was the left-hand version of the key; for example, the left-hand control key was pressed on a standard 101 key us keyboard.
... dom_key_location_right 2 the key was the right-hand version of the key; for example, the right-hand control key is pressed on a standard 101 key us keyboard.
... syntax var location = event.location; example function keyevent(event) { console.log("location of key pressed: " + event.location); } specifications specification status comment document object model (dom) level 3 events specificationthe definition of 'keyboardevent.location' in that specification.
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.
... this example also demonstrates how to include buffered entries (those that ocurred before observer() was called), which is done by setting the buffered option to true.
... note that in this example data is only sent to the server when the user leaves the tab.
LocalFileSystem - Web APIs
for example, if you were to create a mail app, you might create a temporary storage for caching assets (like images and attachments) to speed up performance, while creating persistent storage for unique data—such as drafts of emails that were composed while offline—that should not be lost before they are backed up into the cloud.
... example the following is a code snippet that shows how you can request a file system storage.
...for example, you cannot run from file://.
MediaDeviceInfo.groupId - Web APIs
two devices have the same group identifier if they belong to the same physical device; for example, a monitor with both a built-in camera and microphone.
... examples in this example, we assemble a list of the devices which are part of the same group as a given device.
... this version of the example puts the passed-in device at the top of the result list, then adds any other members of the group that are found: const getdevicegroup = maindevinfo => { let devlist = [maindevinfo]; navigator.mediadevices.enumeratedevices() .then(devices => { devices.foreach(device => { if ((device.groupid === maindevinfo.groupid) && (device.deviceid !== maindevinfo.deviceid)) { ...
MediaDeviceInfo - Web APIs
two devices have the same group identifier if they belong to the same physical device — for example a monitor with both a built-in camera and a microphone.
... mediadeviceinfo.labelread only returns a domstring that is a label describing this device (for example "external usb webcam").
... example here's an example that uses enumeratedevices() to get a list of devices.
MediaDevices.getDisplayMedia() - Web APIs
see using the screen capture api for more details and an example.
...another potential cause for this event: the document in whose context getdisplaymedia() was called is not fully active; for example, perhaps it is not the frontmost tab.
... example in the example below, a startcapture() method is created which initiates screen capture given a set of options specified by the displaymediaoptions parameter.
MediaDevices.ondevicechange - Web APIs
example in this example, we create a function called updatedevicelist(), which is called once when mediadevices.getusermedia() successfully obtains a stream, and then is called any time the device list changes.
...because the example provides a handler for the devicechange event, the list is refreshed any time a media device is attached to or removed from the device running the sample.
...-bottom: 4px; color: white; background-color: darkgreen; } h2 { margin-bottom: 4px; } .left { float:left; width: 48%; margin-right: 2% } .right { float:right; width: 48%; margin-left: 2% } .devicelist { border: 1px solid black; list-style-type: none; margin-top: 2px; padding: 6px; } javascript content other code below is other code which, while needed to make this example work, isn'tt related directly to ondevicechange, so we won't go into any detail.
MediaError.message - Web APIs
example this example creates a <audio> element, establishes an error handler for it, then lets the user click buttons to choose whether to assign a valid audio file or a missing file to the element's src attribute.
... the example creates an <audio> element and lets the user assign either a valid music file to it, or a link to a file which doesn't exist.
... result you can try out this example below, and can see the example in action outside this page here.
MediaSession - Web APIs
for example, a smartphone might have a standard panel in its lock screen that provides controls for media.
... 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.mediasessi...
...on.setactionhandler('pause', function() {}); navigator.mediasession.setactionhandler('seekbackward', function() {}); navigator.mediasession.setactionhandler('seekforward', function() {}); navigator.mediasession.setactionhandler('previoustrack', function() {}); navigator.mediasession.setactionhandler('nexttrack', function() {}); } the following example sets up event handlers for pausing and playing: var audio = document.queryselector("#player"); audio.src = "song.mp3"; navigator.mediasession.setactionhandler('play', play); navigator.mediasession.setactionhandler('pause', pause); function play() { audio.play(); navigator.mediasession.playbackstate = "playing"; } function pause() { audio.pause(); navigator.mediasession.playbackstate = "paused"; } specifications specif...
MediaTrackConstraints.displaySurface - Web APIs
for example, if your app needs to know that the surface being shared is a monitor or application—meaning that there's possibly a non-content backdrop—it can use code similar to this: let mayhavebackdropflag = false; let displaysurface = displaystream.getvideotracks()[0].getsettings().displaysurface; if (displaysurface === "monitor" || displaysurface ==="application") { mayhavebackdropflag = true; } ...
... examples here are some example constraints objects for getdisplaymedia() that make use of the displaysurface property.
... in addition, see example: constraint exerciser in capabilities, constraints, and settings for a complete example showing how constraints are used.
MediaTrackConstraints.facingMode - Web APIs
an exact value in this case indicates that the specified facing mode is specifically required; for example: var constraints = { facingmode: { exact: "user" } }; this indicates that only a user-facing camera is acceptable; if there is no user-facing camera, or the user declines permission to use that camera, the media request will fail.
... "user" the video source is facing toward the user; this includes, for example, the front-facing camera on a smartphone.
... example see example: constraint exerciser in capabilities, constraints, and settings for an example.
MediaTrackSettings.groupId - Web APIs
for example, a headset has two devices on it: a microphone which can serve as a source for audio tracks and a speaker which can serve as an output for audio.
...however, it can be used to ensure that audio input and output are both being performed on the same headset, for example, or to ensure that the built-in camera and microphone on a phone are being used for video conferencing purposes.
... example see example: constraint exerciser in capabilities, constraints, and settings for an example.
MediaTrackSettings - Web APIs
for example, because rtp doesn't provide some of these values during negotiation of a webrtc connection, a track associated with a rtcpeerconnection will not include certain values, such as facingmode or groupid.
...standard cd-quality audio, for example, has a sample rate of 41,000 samples per second.
...cd-quality audio, for example, is 16-bit, so this value would be 16 in that case.
MediaTrackSupportedConstraints.frameRate - Web APIs
see the example to see how this can be used.
... example this simple example looks to see if your browser supports constraining the frame rate when requesting video tracks.
...script let result = document.getelementbyid("result"); if (navigator.mediadevices.getsupportedconstraints().framerate) { result.innerhtml = "supported!"; } else { result.innerhtml = "not supported!"; } html <div id="result"> </div> css #result { font: 14px "arial", sans-serif; } result the output, showing if your browser supports the framerate constraint, is: while this example is trivial, you can replace the simple output of "supported" vs.
Media Session API - Web APIs
for example, to set the current state of the media session to playing: navigator.mediasession.playbackstate = "playing"; interfaces mediametadata allows a web page to provide rich media metadata, for display in a platform ui.
... examples the following example shows feature detection for the media session api.
...the following example adds a pointerup event to an on-page play button, which is then used to kick off the media session code: playbutton.addeventlistener('pointerup', function(event) { var audio = document.queryselector('audio'); // user interacted with the page.
Using Navigation Timing - Web APIs
for example, to measure the perceived loading time for a page: window.addeventlistener("load", function() { let now = new date().gettime(); let loadingtime = now - performance.timing.navigationstart; document.queryselector(".output").innertext = loadingtime + " ms"; }, false); this code, executed when the load event occurs, subtracts from the current time the time at which the navigation wh...
... let's add this information to the example above.
...e performancenavigation.type_reload: output += "reload"; break; case performancenavigation.type_back_forward: output += "history"; break; default: output += "unknown"; break; } output += "<br/>redirects: " + performance.navigation.redirectcount; document.queryselector(".output").innerhtml = output; }, false); this amends the previous example by looking at the contents of the performance.navigation object.
Navigation Timing API - Web APIs
for example, this interface can be used to determine how much time it takes to load or unload a document.
... 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).
... calculate page render time as another example of an interesting piece of data you can obtain using the navigation timing api that you can't otherwise easily get, you can get the amount of time it took to render the page: const rendertime = perfdata.domcomplete - perfdata.domloading; this is obtained by starting with the time at which loading of the dom and its dependencies is complete (domcomplete) and subtracting from it the time at which...
Navigator.getBattery() - Web APIs
for example, it might not be explicitly allowed or restricted via feature-policy battery feature.
... example this example fetches the current charging state of the battery and establishes a handler for the chargingchange event, so that the charging state is recorded whenever it changes.
... 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.getUserMedia() - Web APIs
your callback can then assign the stream to the desired object (such as an <audio> or <video> element), as shown in the following example: function(stream) { var video = document.queryselector('video'); video.srcobject = stream; video.onloadedmetadata = function(e) { // do something with the video here.
... 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.
Navigator.sendBeacon() - Web APIs
for example, which link the user clicked before navigating away and unloading the page.
... the following example shows theoretical analytics code that attempts to submit data to a server with a synchronous xmlhttprequest in an unload handler.
... the following example shows a theoretical analytics code pattern that submits data to a server using the sendbeacon() method.
Network Information API - Web APIs
examples detect connection changes this example watches for changes to the user's connection.
...this example would be called soon after page load to check for a connection type where preloading a video may not be desirable.
...for simplicity and clarity, this example only tests for one connection type.
Node.nextSibling - Web APIs
WebAPINodenextSibling
therefore a node obtained, for example, using node.firstchild or node.previoussibling may refer to a whitespace text node rather than the actual element the author intended to get.
... example <div id="div-1">here is div-1</div> <div id="div-2">here is div-2</div> <script> var el = document.getelementbyid('div-1').nextsibling, i = 1; console.group('siblings of div-1:'); while (el) { console.log(i, '.
...script **************************************************/ in the above example, #text nodes are inserted in the dom where whitespace occurs between tags (i.e.
NodeList - Web APIs
WebAPINodeList
this can be circumvented by using array.prototype.foreach() — see this document's example.
... for example, node.childnodes is live: const parent = document.getelementbyid('parent'); let child_nodes = parent.childnodes; console.log(child_nodes.length); // let's assume "2" parent.appendchild(document.createelement('div')); console.log(child_nodes.length); // outputs "3" static nodelists in other cases, the nodelist is static, where any changes in the dom does not affect the content of the collection.
... example it's possible to loop over the items in a nodelist using a for loop: for (let i = 0; i < mynodelist.length; i++) { let item = mynodelist[i]; } don't use for...in to enumerate the items in nodelists, since they will also enumerate its length and item properties and cause errors if your script assumes it only has to deal with element objects.
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 ...
...to see a example in action, check out our to-do list example (also see the app running live.) note: in the above example we spawn notifications in response to a user gesture (clicking a button).
...firefox is already doing this from version 72, for example.
OfflineAudioContext.OfflineAudioContext() - Web APIs
for example, a 5-second buffer with a samplerate of 48000hz would have a length of 5 * 48000 = 240000 sample-frames.
... example const offlinectx = new offlineaudiocontext({ numberofchannels: 2, length: 44100 * 40, samplerate: 44100, }); const source = offlinectx.createbuffersource(); // etc...
... for a full working example, see our offline-audio-context-promise github repo (see the source code too.) specifications specification status comment web audio apithe definition of 'offlineaudiocontext()' in that specification.
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 ...
... var container = document.queryselector("#test"); var matches = container.queryselectorall("div.highlighted > p"); this example uses an attribute selector to return a list of the <iframe> elements in the document that contain an attribute named data-src: var matches = document.queryselectorall("iframe[data-src]"); here, an attribute selector is used to return a list of the list items contained within a list whose id is userlist which have a data-active attribute whose value is 1: var container = document.queryselector("#userlist"); var matches = container.queryselectorall("li[data-active=1]"); user notes queryselectorall() behaves differently than most common javascript dom libraries, which might lead to unexpected results.
... in this example, when selecting .outer .inner in the context the <div> with the class select, the element with the class .inner is still found, even though .outer is not a descendant of the base element on which the search is performed (.select).
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.
... // paymentresponse.methodname contains the selected payment method // paymentresponse.details contains a payment method specific response await response.complete("success"); } catch (err) { console.error("uh oh, something bad happened", err.message); } } the following example shows how to update the payment sheet as it's being presented to the end-user.
PaymentResponse.retry() - Web APIs
for example, if the user chose to pay by credit card using the basic-card payment method, this is a basiccarderrors object.
... see the example below for a thorough example, but the basic concept, in outline form, is: create a new paymentrequest (new paymentrequest()) display the payment request (paymentrequest.show() if show() resolves, the returned paymentresponse describes the requested payment and the options chosen by the user.
...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) { ...
Payment processing concepts - Web APIs
for example, when using a credit card to pay, the credit card processing service is the payment method provider.
...the conditions that make payment possible vary depending on the payment method and the user's payment request; for example, if the user chooses to pay using a credit card that isn't accepted by the payee, the payment can't be made.
... paymentrequest.onmerchantvalidation = function(event) { event.complete(fetchvalidationdata(event.validationurl)); } in this example, fetchvalidationdata() is a function which loads the payment handler specific identifying information from the address given by validationurl.
PerformanceEntry - Web APIs
a performance entry can be directly created by making a performance mark or measure (for example by calling the mark() method) at an explicit point in an application.
... performanceentry.entrytype read only a domstring representing the type of performance metric such as, for example, "mark".
... example the following example checks all performanceentry properties to see if the browser supports them and if so, write their values to the console.
Using the Performance API - Web APIs
however, if the browser is unable to provide a time value accurate to 5 microseconds (because of hardware or software constraints, for example), the browser can represent the value as a time in milliseconds accurate to a millisecond.
... the following code example shows the use of domhighrestimestamp and the performance.now() method.
...in the following example, json serialization for the performance, performance.timing and performance.navigation objects is printed in the object element.
Multi-touch interaction - Web APIs
this document demonstrates via example code, using pointer events with different multi-touch interactions.
... example this example demonstrates using pointer events' various event types (pointerdown, pointermove, pointerup pointercancel, etc.) for different multi-touch interactions.
...it may be called multiple times (for example, if the user moves the pointer) before a different event type is fired.
PublicKeyCredential.getClientExtensionResults() - Web APIs
note: this method may only be used in top-level contexts and will not be available in an <iframe> for example.
... 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...
... uint8array(16) /* from the server */, name: "jdoe@example.com", displayname: "john doe" }, pubkeycredparams: [ { type: "public-key", alg: -7 } ] }; navigator.credentials.create({ publickey }) .then(function (newcredentialinfo) { var mybuffer = newcredentialinfo.getclientextensionresults(); // mybuffer will contain the result of any of the processing of the "loc" and "uvi" extensions }).catch(function (err) { console.error(err); }); specifications specification status comment web authentication: an api for accessing public key credentials level 1the definition of 'getclientextensionresults()' in that specification.
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" }, // cryp...
...tographic challenge from the server challenge: new uint8array(26), // user user: { id: new uint8array(16), name: "john.p.smith@example.com", displayname: "john p.
... filter out authenticators which are bound to the device authenticatorselection:{ authenticatorattachment: "cross-platform", requireresidentkey: true, userverification: "preferred" }, // exclude already existing credentials for the user 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 */ } ] } }; // create the new credential with the options above navigator.credentials.create(createcredentialoptions) .then(function (ne...
Web Push API Notifications best practices - Web APIs
in our above example, the program manager is awaiting your response and so a push notification is appropriate.
...for example, if the user views more than one article, or lingers on your page for several minutes, they may be interested in receiving updates.
...for example, safari 12.1 now requires—and other browsers either already do, or are planning[1] to do so—that the user interact with the page in some way before the page can request permission to perform push notifications.
Push API - Web APIs
WebAPIPush API
this allows apps to react to push messages being received, for example, by displaying a notification (using serviceworkerregistration.shownotification().) each subscription is unique to a service worker.
... serviceworkerglobalscope.onpushsubscriptionchange an event handler fired whenever a pushsubscriptionchange event occurs; for example, when a push subscription has been invalidated, or is about to be invalidated (e.g.
... 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.
... it also specifies stun:stun.example.com as the stun server for ice to use during negotiation.
... let config = { iceservers: [ { urls: [ "stun:stun.example.com" ] }, ], bundlepolicy: "max-compat" }; let pc = new rtcpeerconnection(config); specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcconfiguration.bundlepolicy' in that specification.
RTCConfiguration.iceServers - Web APIs
examples the configuration below opens a new peer connection, specifying two servers for the ice agent to use for negotiation.
...the second server has two urls: stun:stun.example.com and stun:stun-1.example.com.
... var configuration = { iceservers: [{ urls: "stun:stun.services.mozilla.com", username: "louis@mozilla.com", credential: "webrtcdemo" }, { urls: ["stun:stun.example.com", "stun:stun-1.example.com"] }] }; var pc = new rtcpeerconnection(configuration); specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcconfiguration.iceservers' in that specification.
RTCConfiguration - Web APIs
<<<--- add link to information about identity --->>> example the configuration below establishes two ice servers.
...the second server has two urls: stun:stun.example.com and stun:stun-1.example.com.
... var configuration = { iceservers: [{ urls: "stun:stun.services.mozilla.com", username: "louis@mozilla.com", credential: "webrtcdemo" }, { urls: ["stun:stun.example.com", "stun:stun-1.example.com"] }] }; var pc = new rtcpeerconnection(configuration); specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcconfiguration' in that specification.
RTCDTMFSender.toneBuffer - Web APIs
using tone buffer strings for example, if you're writing code to control a voicemail system by sending dtmf codes, you might use a string such as "*,1,5555".
... in this example, we would send "*" to request access to the vm system, then, after a pause, send a "1" to start playback of voicemail messages, then after a pause, dial "5555" as a pin number to open the messages.
... example tbd specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcdtmfsender.tonebuffer' in that specification.
RTCIceCandidate.candidate - Web APIs
in the example above, the priority is 2043278322.
...the complete list of attributes for this example candidate is: foundation = 4234997325 component = "rtp" (the number 1 is encoded to this string; 2 becomes "rtcp") protocol = "udp" priority = 2043278322 ip = "192.168.0.56" port = 44323 type = "host" example in this example, we see a function which receives as input an sdp string containing an ice candidate received from the remote peer during the signaling process.
... this example could be simplified somewhat; you may more often see the code look something like this, taking advantage of more advanced ecmascript 2016 features: let handlenewicecandidate = candidatesdp => mypeerconnection.addicecandidate(new rtcicecandidate(candidatesdp)); specifications specification status comment webrtc 1.0: real-time communication between browsersthe definitio...
RTCIceCandidate.usernameFragment - Web APIs
for example, a browser might choose to always use a 24-character ufrag in which bit 4 of each character is randomly selected between 0 and 1.
... another example: it might take a user-defined string and append three 8-bit random bytes to the end.
... example although the webrtc infrastructure will filter out obsolete candidates for you after an ice restart, you can do it yourself if you're trying to absolutely minimize the number of messages going back and forth.
RTCIceCandidateInit.usernameFragment - Web APIs
for example, a browser might choose to always use a 24-character ufrag in which bit 4 of each character is randomly selected between 0 and 1.
... another example: it might take a user-defined string and append three 8-bit random bytes to the end.
... example ...
RTCIceServer.url - Web APIs
WebAPIRTCIceServerurl
it was removed from the specification in june 2013 but is still broadly used in older examples and books, so we include documentation here to help adapt old code to new browsers.
... example this example creates a new rtcpeerconnection which will use a stun server at stunserver.example.org to negotiate connections.
... mypeerconnection = new rtcpeerconnection({ iceservers: [ { url: "stun:stunserver.example.org" } ] }); unfortunately, the only way to tell ice that the server has a backup domain name of stunserver2.example.org is to add a new entry to the iceservers array for it.
RTCInboundRtpStreamStats.qpSum - Web APIs
you can, for example, use the value of rtcreceivedrtpstreamstats.framesdecoded if receiving the media or rtcsentrtpstreamstats.framesencoded if sending it to get the number of frames handled so far, and compute an average from there.
...for example, for the vp8 codec, the qp value can be anywhere from 1 to 127 and is found in the frame header element "y_ac_qi", whose value is defined in rfc 6386: 19.2.
... example calculating average quantization the calculateaverageqp() function shown below computes the average qp for the given rtcstats object that contains rtp stream statistics, returning 0 if the object doesn't describe an rtp stream.
RTCPeerConnection.createOffer() - Web APIs
for example, in the case of music or other non-voice transmission, this can cause loss of important low-volume sounds.
... example here we see a handler for the negotiationneeded event which creates the offer and sends it to the remote system over a signaling channel.
... see signaling and video calling for the complete example from which this snippet is derived; this will help you to understand how the signaling code here works.
RTCPeerConnection: icecandidate event - Web APIs
g for icegatheringstatechange events: pc.addeventlistener("icegatheringstatechange", ev => { switch(pc.icegatheringstate) { case "new": /* gathering is either just starting or has been reset */ break; case "gathering": /* gathering has begun or is ongoing */ break; case "complete": /* gathering has ended */ break; } }); as you can see in this example, the icegatheringstatechange event lets you know when the value of the rtcpeerconnection property icegatheringstate has been updated.
... examples this example creates a simple handler for the icecandidate event that uses a function called sendmessage() to create and send a reply to the remote peer through the signaling server.
... first, an example using addeventlistener(): pc.addeventlistener("icecandidate", ev => { if (ev.candidate) { sendmessage({ type: "new-ice-candidate", candidate: event.candidate }); } }, false); you can also set the onicecandidate event handler property directly: pc.onicecandidate = ev => { if (ev.candidate) { sendmessage({ type: "new-ice-candidate", candidate: event.candidate }); } }; specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'icecandidate' in that specification.
RTCPeerConnection.setConfiguration() - Web APIs
if, for example, the rtcpeerconnection() constructor was called with no parameters, you would have to then call setconfiguration() to add ice servers before ice negotiation could begin.
...perhaps the user has moved into a new region, so using new regional ice servers is necessary, for example.
... example in this example, it has already been determined that ice restart is needed, and that negotiation needs to be done using a different ice server.
RTCPeerConnection.setLocalDescription() - Web APIs
return value a promise which is fulfilled once the value of rtcpeerconnection.localdescription is successfully changed or rejected if the change cannot be applied (for example, if the specified description is incompatible with one or both of the peers on the connection).
... examples implicit descriptions one of the advantages of the parameter-free form of setlocaldescription() is that it lets you simplify your negotiation code substantially.
... providing your own offer or answer the example below shows the implementation of a handler for the negotiationneeded event that explicitly creates an offer, rather than letting setlocaldescription() do it.
RTCPeerConnection.signalingState - Web APIs
for example, if you receive an answer while the signalingstate isn't "have-local-offer", you know that something is wrong, since you should only receive answers after creating an offer but before an answer has been received and passed into rtcpeerconnection.setlocaldescription().
... this value may also be useful during debugging, for example.
... example var pc = new rtcpeerconnection(configuration); var state = pc.signalingstate; specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcpeerconnection.signalingstate' in that specification.
RTCRtpStreamStats.qpSum - Web APIs
you can, for example, use the value of rtcreceivedrtpstreamstats.framesdecoded if receiving the media or rtcsentrtpstreamstats.framesencoded if sending it to get the number of frames handled so far, and compute an average from there.
...for example, for the vp8 codec, the qp value can be anywhere from 1 to 127 and is found in the frame header element "y_ac_qi", whose value is defined in rfc 6386: 19.2.
... example calculating average quantization the calculateaverageqp() function shown below computes the average qp for the given rtcrtpstreamstats object, returning 0 if the object doesn't describe an rtp stream.
ReadableStream.tee() - Web APIs
you might do this for example in a serviceworker if you want to fetch a response from the server and stream it to the browser, but also stream it to the serviceworker cache.
... examples in the following simple example, a previously-created stream is teed, then both resulting streams (contained in two members of a generated array) are passed to a function that reads the data out of the two streams and prints each stream's chunks sequentially to a different part of the ui.
... see simple tee example for the full code.
Request() - Web APIs
WebAPIRequestRequest
errors type description typeerror since firefox 43, request() will throw a typeerror if the url has credentials, such as http://user:password@example.com.
... example in our fetch request example (see fetch request live) we create a new request object using the constructor, then fetch it using a globalfetch.fetch call.
... var myimage = document.queryselector('img'); var myrequest = new request('flowers.jpg'); fetch(myrequest).then(function(response) { return response.blob(); }).then(function(response) { var objecturl = url.createobjecturl(response); myimage.src = objecturl; }); in our fetch request with init example (see fetch request init live) we do the same thing except that we pass in an init object when we invoke fetch(): var myimage = document.queryselector('img'); var myheaders = new headers(); myheaders.append('content-type', 'image/jpeg'); var myinit = { method: 'get', headers: myheaders, mode: 'cors', cache: 'default' }; var myrequest = new request('...
Request - Web APIs
WebAPIRequest
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 pas...
...sing the request object in as a parameter to a windoworworkerglobalscope.fetch() call, for example: fetch(request) .then(response => response.blob()) .then(blob => { image.src = url.createobjecturl(blob); }); in the following snippet, we create a new request using the request() constructor with some initial data and body content for an api request which need a body payload: const request = new request('https://example.com', {method: 'post', body: '{"foo": "bar"}'}); const url = request.url; const method = request.method; const credentials = request.credentials; const bodyused = request.bodyused; note: the body type can only be a blob, buffersource, formdata, urlsearchparams, usvstring or readablestream type, so for adding a json object to the payload you need to stringify that ob...
... you could then fetch this api request by passing the request object in as a parameter to a windoworworkerglobalscope.fetch() call, for example and get the response: fetch(request) .then(response => { if (response.status === 200) { return response.json(); } else { throw new error('something went wrong on api server!'); } }) .then(response => { console.debug(response); // ...
Resize Observer API - Web APIs
for example, media queries / window.matchmedia are great for updating layouts at specific points when the viewport changes sizes, but what if you want to change layout in response to a specific element's size changing, which isn't the outer container?
...the window resize event), then figure out what the new dimensions or other features of the element after a resize using element.getboundingclientrect or window.getcomputedstyle, for example.
... 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
an application can use the timing metrics to determine, for example, the length of time it takes to load a specific resource, such as an xmlhttprequest, <svg>, image, or script.
...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.
...however, if the browser is unable to provide a time value accurate to 5 µs (because, for example, due to hardware or software constraints), the browser can represent a the value as a time in milliseconds accurate to a millisecond.
SVGGraphicsElement: paste event - Web APIs
bubbles yes cancelable yes interface clipboardevent event handler property onpaste if the cursor is in an editable context (for example, in a <textarea> or an element with contenteditable attribute set to true) then the default action is to insert the contents of the clipboard into the document at the cursor position.
... to override the default behavior (for example to insert some different data or a transformation of the clipboard contents) an event handler must cancel the default action using event.preventdefault(), and then insert its desired data manually.
... example html <?xml version="1.0" encoding="utf-8"?> <svg viewbox="0 0 140 30" width="600" height="320" xmlns="http://www.w3.org/2000/svg"> <foreignobject x="5" y="-10" width="90" height="20"> <input xmlns="http://www.w3.org/1999/xhtml" value="copy this text"/> </foreignobject> <text x="5" y="30" id="element-to-paste-text" tabindex="1">paste it here</text> </svg> css input { font-size: 10px; width: 100%; height: 90%; box-sizing: border-box; border: 1px solid black; } javascript document.getelementbyid("element-to-paste-text").addeventlistener("paste", evt => { evt.target.textcontent = evt.clipboarddata.getdata("text/plain").touppercase(); evt...
Selection.modify() - Web APIs
WebAPISelectionmodify
example this example demonstrates the various granularity options for modifying a selection.
... click somewhere inside the example (optionally selecting some text), and then click the button to expand the selection.
... html <p>click somewhere in this example.
SharedWorker() - Web APIs
exceptions a securityerror is raised if the document is not allowed to start workers, for example if the url has an invalid syntax or if the same-origin policy is violated.
... 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.postmessage([first.value,second.value]); console.log('message posted to worker'); } myworker.port.onmessage = function(e) { result1.textcontent = e.data; console.log('message received from worker'); } for a full example, see our...
... basic shared worker example (run shared worker.) specifications specification status comment html living standardthe definition of 'sharedworker()' in that specification.
SpeechSynthesisErrorEvent.error - Web APIs
audio-busy the operation couldn't be completed at this time because the user-agent couldn't access the audio output device (for example, the user may need to correct this by closing another application.) audio-hardware the operation couldn't be completed at this time because the user-agent couldn't identify an audio output device (for example, the user may need to connect a speaker or configure system settings.) network the operation couldn't be completed at this time because some required network communication failed.
... synthesis-unavailable the operation couldn't be completed at this time because no synthesis engine was available (for example, the user may need to install or configure a synthesis engine.) synthesis-failed the operation failed because the synthesis engine raised an error.
... examples var synth = window.speechsynthesis; var inputform = document.queryselector('form'); var inputtxt = document.queryselector('input'); var voiceselect = document.queryselector('select'); var voices = synth.getvoices(); ...
Storage - Web APIs
WebAPIStorage
it allows, for example, the addition, modification, or deletion of stored data items.
... examples here we access a storage object by calling localstorage.
...e = localstorage.getitem('image'); document.getelementbyid('bgcolor').value = currentcolor; document.getelementbyid('font').value = currentfont; document.getelementbyid('image').value = currentimage; htmlelem.style.backgroundcolor = '#' + currentcolor; pelem.style.fontfamily = currentfont; imgelem.setattribute('src', currentimage); } note: to see this running as a complete working example, see our web storage demo.
TextTrack.mode - Web APIs
WebAPITextTrackmode
however, that means that if you wish to perform any actions involving the track's cues while handling, for example, the load event—in order to process some aspect of the cues upon page load—and the track mode was initially disabled, you'll have to change the mode to either hidden or showing in order to trigger loading of the cues.
... tracks whose kind is "descriptions" are presented in a non-visual form (for example, the text might be spoken to describe the action in the video).
... example in this example, we configure the text track's cues so that every time a cue is finished, the video automatically pauses playback.
Touch.force - Web APIs
WebAPITouchforce
a value of 0.0 is returned if no value is known (for example the touch device does not support this property).
... example this example illustrates using the touch interface's touch.force property.
...for example // minimum pressure vs.
TouchEvent - Web APIs
this surface can be a touch screen or trackpad, for example.
...this is also sent if the touch point moves off the edge of the surface; for example, if the user's finger slides off the edge of the screen.
... example see the example on the main touch events article.
URL - Web APIs
WebAPIURL
usage notes the constructor takes a url parameter, and an optional base parameter to use as a base if the url parameter is a relative url: const url = new url('../cats', 'http://www.example.com/dogs'); console.log(url.hostname); // "www.example.com" console.log(url.pathname); // "/cats" url properties can be set to construct the url: url.hash = 'tabby'; console.log(url.href); // "http://www.example.com/cats#tabby" urls are encoded according to the rules found in rfc 3986.
... for instance: url.pathname = 'démonstration.html'; console.log(url.href); // "http://www.example.com/d%c3%a9monstration.html" the urlsearchparams interface can be used to build and manipulate the url query string.
... const response = await fetch(new url('http://www.example.com/démonstration.html')); specifications specification status comment file apithe definition of 'url' 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.
... params.set('baz', 3); params.tostring(); // "foo=1&bar=2&baz=3" below is a real-life example demonstrating how to create a url and set some search parameters.
... you can copy and paste the example in a code environment like codepen, jsfiddle, or the multi-line javascript interpreter in firefox.
VTTCue() - Web APIs
WebAPIVTTCueVTTCue
for example, if a cue is to be visible from 50 seconds to a one minute, five and a half seconds in the media's playback, starttime will be 50.0.
...given the example cue mentioned under starttime, the value of endtime would be 65.5.
... example // create a cue that is shown from 2 to 3 seconds and uses the given text.
Visual Viewport API - Web APIs
for example, what if you need a set of image controls to remain on screen regardless of the pinch zoom level of the device?
... example the code below is based on the sample the specification, though it adds a few things that make it function better.
... one thing that may not be clear in this example is the use of the pendingupdate flag and the call to requestanimationframe().
WebGLRenderingContext.vertexAttribPointer() - Web APIs
for example, your vertex shader may be using a position and a color attribute.
... examples this example shows how to send your vertex attributes to the shader program.
... for example, the following vertex: { "position": [1.0, 2.0, 1.5], "normal": [1.0, 0.0, 0.0], "texcoord": [0.5, 0.25] } will be stored in the array buffer as follows: 00 00 80 3f 00 00 00 40 00 00 0c 3f 7f 00 00 00 7f ff 3f ff creating the array buffer first, we dynamically create the array buffer from json data using a dataview.
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.
..." + "your browser or device may not support webgl."; return; } gl.viewport(0, 0, gl.drawingbufferwidth, gl.drawingbufferheight); gl.enable(gl.scissor_test); gl.scissor(30, 10, 60, 60); gl.clearcolor(1.0, 1.0, 0.0, 1.0); gl.clear(gl.color_buffer_bit); }); }, false); the source code of this example is also available on github.
WebGLShader - Web APIs
examples creating a vertex shader note that there are many other strategies for writing and accessing shader source code strings.
... these example are for illustration purposes only.
... var vertexshadersource = 'attribute vec4 position;\n' + 'void main() {\n' + ' gl_position = position;\n' + '}\n'; //use the createshader function from the example above var vertexshader = createshader(gl, vertexshadersource, gl.vertex_shader) creating a fragment shader var fragmentshadersource = 'void main() {\n' + ' gl_fragcolor = vec4(1.0, 1.0, 1.0, 1.0);\n' + '}\n'; //use the createshader function from the example above var fragmentshader = createshader(gl, fragmentshadersource, gl.fragment_shader) specifications specification status comment webgl 1.0the definition of 'webglshader' in that specification.
Basic scissoring - Web APIs
« previousnext » in this example, we see how to draw simple rectangles and squares using webgl scissoring operations.
... here we see another example of the distinction between fragments and pixels.
... gl.clearcolor(1.0, 1.0, 0.0, 1.0); gl.clear(gl.color_buffer_bit); }, false); the source code of this example is also available on github.
Clearing by clicking - Web APIs
« previousnext » this example demonstrates how to combine user interaction with webgl graphics operations by clearing the rendering context with a random color when the user clicks.
... clearing the rendering context with random colors this example provides a simple illustration of how to combine webgl and user interaction.
... function getrandomcolor() { return [math.random(), math.random(), math.random()]; } }, false); the source code of this example is also available on github.
Detect WebGL - Web APIs
« previousnext » this example demonstrates how to detect a webgl rendering context and reports the result to the user.
... feature-detecting webgl in this first example we are going to check whether the browser supports webgl.
..." + "your browser or device may not support webgl."; } } }, false); the source code of this example is also available on github.
Scissor animation - Web APIs
« previousnext » a simple webgl example in which we have some animation fun using scissoring and clearing operations.
... animation with scissoring in this example, we are animating squares using scissor() and clear().
...webgl"); if (!gl) { var paragraph = document.queryselector("p"); paragraph.innerhtml = "failed to get webgl context." + "your browser or device may not support webgl."; return null; } gl.viewport(0, 0, gl.drawingbufferwidth, gl.drawingbufferheight); gl.clearcolor(0.0, 0.0, 0.0, 1.0); gl.clear(gl.color_buffer_bit); return gl; } })(); the source code of this example is also available on github.
Introduction to the Real-time Transport Protocol (RTP) - Web APIs
for example, rtcp handles qos monitoring.
... note: this example makes use of modern javascript features including async functions and the await expression.
... in the examples below, we'll refer to the peer which is turning "hold" mode on and off as the local peer and the user being placed on hold as the remote peer.
Lifetime of a WebRTC session - Web APIs
see signaling and video calling for an actual example with a step-by-step explanation of what the code does.
...one of the users might transition from a cellular to a wifi network, or the network might become congested, for example.
...not all browsers will perform ice restart due to network congestion, for example.
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.
Fundamentals of WebXR - Web APIs
for example, if a headset uses a 2560x1440 screen, with the left half being used for the left eye's view and the right half or the right eye's view, the framebuffer is used like this: the simplest headsets have no integrated sensors, and simply focus each half of the screen into the corresponding eye.
... a common example of this is google cardboard, a type of headset first created by google which can be cheaply created using cardboard or other inexpensive materials.
... webxr application life cycle starting up and shutting down a webxr session movement, orientation, and motion: a webxr example ...
Keyframe Formats - Web APIs
element.animate([ { opacity: 1, easing: 'ease-out' }, { opacity: 0.1, easing: 'ease-in' }, { opacity: 0 } ], 2000); in this example, the specified easing only applies from the keyframe where it is specified until the next keyframe.
...for example, consider this simple animation — the keyframe object looks like so: let rotate360 = [ { transform: 'rotate(360deg)' } ]; we have only specified the end state of the animation, and the beginning state is implied.
...the property names are specified using camel-case so for example background-color becomes backgroundcolor and background-position-x becomes backgroundpositionx.
Using the Web Animations API - Web APIs
in the above example, to make sure that alice’s color changes at 30% (not 50%) for the color change, we are giving it offset: 0.3.
...in the red queen’s race example, alice and the red queen are running to stay in place (check out the full code on codepen): because small children tire out easily, unlike automaton chess pieces, alice is constantly slowing down.
...for instance, in the growing and shrinking alice game example, you might have noticed something odd about the cake’s duration: duration: alicechange.effect.getcomputedtiming().duration / 2 to understand what’s happening here, let’s take a look at alice’s animation: var alicechange = document.getelementbyid('alice').animate( [ { transform: 'translate(-50%, -50%) scale(.5)' }, { transform: 'translate(-50%, -50%) scale(2)' } ], { dur...
Web audio spatialization basics - Web APIs
as if its extensive variety of sound processing (and other) options wasn't enough, the web audio api also includes facilities to allow you to emulate the difference in sound as a listener moves around a sound source, for example panning as you move around a sound source inside a 3d game.
...if you just want a simple stereo panning effect, our stereopannernode example (see source code) should give you everything you need.
...r sound rotation const q = math.pi/rotationrate; //rotation increment in radians we can also use this to work out degrees rotated, which will help with the css transforms we will have to create (note we need both an x and y-axis for the css transforms): // get degrees for css const degreesx = (q * 180)/math.pi; const degreesy = (q * 180)/math.pi; let's take a look at our left rotation as an example.
Web Workers API - Web APIs
for example, you can't directly manipulate the dom from inside a worker, or use some default methods and properties of the window object.
... 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).
... basic shared worker example (run shared worker).
Window.content - Web APIs
WebAPIWindowcontent
this is useful in xul windows that have a <browser> (or tabbrowser or <iframe>) with type="content-primary" attribute on it — the most famous example is firefox main window, browser.xul.
... note: some examples use _content instead of content.
... syntax var windowobject = window.content; example executing the following code in a chrome xul window with a <browser type="content-primary"/> element in it draws a red border around the first div on the page currently displayed in the browser: content.document.getelementsbytagname("div")[0].style.border = "solid red 1px"; specification none.
Window.matchMedia() - Web APIs
WebAPIWindowmatchMedia
there's a good example of this in the article on window.devicepixelratio.
... 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.
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", "...
...?page=3"); history.back(); // logs "location: http://example.com/example.html?page=1, state: {"page":1}" history.back(); // logs "location: http://example.com/example.html, state: null" history.go(2); // logs "location: http://example.com/example.html?page=3, state: {"page":3}" the same example using the onpopstate event handler property: window.onpopstate = function(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", "?page=3"); history.back(); // logs "location: http://example.com/example.html?page=1, state: {"page":1}" history.back(); // logs "location: http://example.com/example.html, state: ...
...null" history.go(2); // logs "location: http://example.com/example.html?page=3, state: {"page":3}" note that even though the original history entry (for http://example.com/example.html) has no state object associated with it, a popstate event is still fired when we activate that entry after the second call to history.back().
Window: unhandledrejection event - Web APIs
you can prevent this by calling preventdefault() on the promiserejectionevent; see preventing default handling below for an example.
... examples here we have a few examples showing ways you can make use of the unhandledrejection event.
... basic error logging this example simply logs information about the unhandled promise rejection to the console.
WindowOrWorkerGlobalScope.btoa() - Web APIs
for example, you can encode control characters such as ascii values 0 through 31.
... example const encodeddata = window.btoa('hello, world'); // encode a string const decodeddata = window.atob(encodeddata); // decode the string unicode strings the btoa() function takes a javascript string as a parameter.
...for example: // convert a unicode string to a string in which // each 16-bit unit occupies only one byte function tobinary(string) { const codeunits = new uint16array(string.length); for (let i = 0; i < codeunits.length; i++) { codeunits[i] = string.charcodeat(i); } return string.fromcharcode(...new uint8array(codeunits.buffer)); } // a string that contains characters occupying > 1 byte const m...
WorkerGlobalScope - Web APIs
for example: importscripts('foo.js', 'bar.js'); non-standard methods workerglobalscope.dump() allows you to write a message to stdout — i.e.
... example you won't access workerglobalscope directly in your code; however, its properties and methods are inherited by more specific global scopes such as dedicatedworkerglobalscope and sharedworkerglobalscope.
... for example, you could import another script into the worker and print out the contents of the worker scope's navigator object using the following two lines: importscripts('foo.js'); console.log(navigator); since the global scope of the worker script is effectively the global scope of the worker you are running (dedicatedworkerglobalscope or whatever) and all worker global scopes inherit methods, properties, etc.
XMLHttpRequest.getAllResponseHeaders() - Web APIs
an example of what a raw header string looks like: date: fri, 08 dec 2017 21:04:30 gmt\r\n content-encoding: gzip\r\n x-content-type-options: nosniff\r\n server: meinheld/0.6.1\r\n x-frame-options: deny\r\n content-type: text/html; charset=utf-8\r\n connection: keep-alive\r\n strict-transport-security: max-age=63072000\r\n vary: cookie, accept-encoding\r\n content-length: 6502\r\n x-xss-protection: 1; mode...
... example this example examines the headers in the request's readystatechange event handler, xmlhttprequest.onreadystatechange.
... the header string into an array // of individual headers var arr = headers.trim().split(/[\r\n]+/); // create a map of header names to values var headermap = {}; arr.foreach(function (line) { var parts = line.split(': '); var header = parts.shift(); var value = parts.join(': '); headermap[header] = value; }); } } once this is done, you can, for example: var contenttype = headermap["content-type"]; this obtains the value of the content-type header into the variable contenttype.
XRInputSource.gripSpace - Web APIs
for example, if a user were holding a virtual straight rod, the native origin of this xrspace would be located at the approximate center of mass of the user's fist.
...for example, only inputs whose targetraymode is tracked-pointer provide a gripspace.
... 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.targetRayMode - Web APIs
example this fragment of code shows part of a function to be called once every frame.
... for each such input, this example looks for inputs whose targetraymode is tracked-pointer, indicating that the input is in fact intended to represent a targeting device rather than a gazing device, screen tap, or mouse click.
...*/ } } see the article inputs and input sources for more details and a more complete example.
XRInputSource.targetRaySpace - Web APIs
example this fragment of code shows part of a function to be called once every frame.
... for each such input, this example looks for inputs whose targetraymode is tracked-pointer, indicating that the input is in fact intended to represent a targeting device rather than a gazing device, screen tap, or mouse click.
...*/ } } see the article inputs and input sources for more details and a more complete example.
XRReferenceSpace.getOffsetReferenceSpace() - Web APIs
this is demonstrated in the example implementing rotation based on non-xr inputs, which demonstrates a way to use this method to let the user use their mouse to pitch and yaw their viewing angle.
... examples below are some examples showing how to use getoffsetreferencespace().
...in this example, we'll show code that lets the user look around by right-clicking and moving the mouse to change the viewing angle.
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) { handleoffhandsqueeze(event.inputsource, event.frame); } }; finishing an ongoing squeeze action this example exapnds somewhat on the previous example by demonstrating a way to implement the ability for the user to drop an object that was previously picked up by the user..
... 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.requestAnimationFrame() - Web APIs
example the following example requests xrsession with "inline" mode so that it can be displayed in an html element (without the need for a separate ar or vr device).
... } }) }) the following example was taken directly from the spec draft.
... this example demonstrates a design pattern that ensures seamless transition between non-immersive animations created via window.requestanimationframe and immersive xr animations.
XRTargetRayMode - Web APIs
examples this fragment of code shows part of a function to be called once every frame.
... for each such input, this example looks for inputs whose targetraymode is tracked-pointer, indicating that the input is in fact intended to represent a targeting device rather than a gazing device, screen tap, or mouse click.
...*/ } } see the article inputs and input sources for more details and a more complete example.
XRView.transform - Web APIs
WebAPIXRViewtransform
examples for each view making up the presented scene, the view's transform represents the position and orientation of the viewer or camera relative to the reference space's origin.
... in this example, we see an outline of a code fragment used while rendering an xrframe, which makes use of the view transform to place objects in the world during rendering.
... note: this example is derived from a larger example...
XRView - Web APIs
WebAPIXRView
it's possible to have xrview objects which represent overlapping regions as well as entirely disparate regions; in a game, you might have views that can be presented to observe a remote site using a security camera or other device, for example.
... examples preparing to render every view for a pose to draw eerything the user sees each frame requires iterating over the list of views returned by the xrviewerpose object's views list: for (let view of pose.views) { let viewport = gllayer.getviewport(view); gl.viewport(viewport.x, viewport.y, viewport.width, viewport.height); // draw the scene; the eye being drawn is identified // by view.
... you can find a more extensive and complete example in our article movement, orientation, and motion.
XRViewerPose.views - Web APIs
this array's length may potentially vary over the lifetime of the xrsession (for example, if the viewer enables or disables stereo mode on their xr output device).
... examples in this example—part of the code to render an xrframe, getviewerpose() is called to get an xrviewerpose using the same reference space the code is using as its base reference space.
... this code is derived from drawing a frame in movement, orientation, and motion: a webxr example.
XRWebGLLayer.getNativeFramebufferScaleFactor() static method - Web APIs
see the usage notes and examples for details.
... for example, consider a device which uses a 2560x1440 pixel frame buffer (which is used to render two views, for the left and right eyes, side by side each at a resolution of 1280x1440 pixels).
... 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: scal...
Using the aria-valuenow attribute - Accessibility
for example, a slider may have rendered values of small, medium, and large.
... 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
for example, a slider may have rendered values of small, medium, and large.
... 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 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.
... <img role="presentation" tabindex="-1" src="images/treecontracted.gif" /> <span role="treeitem" tabindex="0">cats</span> </div> <div id="catgroup" role="group"> <div id="siamese" role="treeitem"> <span tabindex="-1">siamese</span> </div> <div id="tabby" role="treeitem"> <span tabindex="-1">tabby</span> </div> </div> </div> </div> example 2: using the group role with a html drop-down menu 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.
ARIA: document role - Accessibility
<button>close</button> </div> this example shows a dialog widget with some controls and a section with some informational text that the assistive technology user can read when tabbing to it.
...for example, if the document is collapsible, then the state and the value of aria-expanded must be maintained.
... examples an example is gmail and the single conversation view.
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.
...for example, setting aria-busy to true during the update operation if needed, and then to false upon completion.
... examples example implementation of feed pattern specifications specification status accessible rich internet applications (wai-aria) 1.1the definition of 'feed' in that specification.
ARIA: form role - Accessibility
anything that is not a <form> cannot be submitted, therefore you would have to use javascript to build an alternative data submission mechanism, for example with xmlhttprequest.
... 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> <textarea id="comment" name="comment"></textarea> <input value="comment" type="submit"> </div> it is recommended to use <form> instead.
...for example, a declaration of role="form" with an of aria-label="contact form" may be announced redundantly as, "contact form form".
ARIA: List role - Accessibility
see best practices for a full example.
... 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.
... for example, our above example should be rewritten as follows: <ul> <li>list item 1</li> <li>list item 2</li> <li>list item 3</li> </ul> or use an ordered list if the order of the list items matters: <ol> <li>list item 1</li> <li>list item 2</li> <li>list item 3</li> </ol> note: the aria list/listitem roles don't distinguish between ordered and unordered lists.
ARIA: Listitem role - Accessibility
see best practices for a full example.
... 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.
...for example, our above example should be rewritten as follows: <ul> <li>list item 1</li> <li>list item 2</li> <li>list item 3</li> </ul> or use an ordered list if the order of the list items matters: <ol> <li>list item 1</li> <li>list item 2</li> <li>list item 3</li> </ol> note: the aria list/listitem roles don't distinguish between ordered and unordered lists.
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 &amp; 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,...
...an example of this would be repeating the main navigation at the top and bottom of the page.
...for example, a declaration of role="navigation" with an of aria-label="primary navigation" may be announced redundantly as, "primary navigation navigation".
ARIA: Region role - Accessibility
<div role="region" aria-label="example"> <!-- region content --> </div> description the region role is an aria landmark role.
... 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!
... <div role="region" aria-labelledby="please-reconsider"> <h3 id="please-reconsider">please reconsider your document structure</h3> <!-- content --> </div> in this example, the region's label is being generated by the aria-labelledby attribute.
ARIA: row role - Accessibility
for example, in a table with 15 columns, and columns 4, 5, and 6 are in the dom, aria-colindex="4" could be set on every row.
...for example, if a table has 1,500 rows, but only the header and rows 47 and 52 are in the dom, aria-rowindex="1" would be set on the header row, and aria-rowindex="47" and aria-rowindex="52" would be set on the 47th and 52nd row, respectively.
... 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</spa...
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.
...an example of this would be repeating the sitewide search at the top and bottom of the page.
...for example, a declaration of role="search" with an of aria-label="sitewide search" may be announced redundantly as, "sitewide search search".
ARIA: switch role - Accessibility
the aria switch role is functionally identical to the checkbox role, except that instead of representing "checked" and "unchecked" states, which are fairly generic in meaning, the switch role represents the states "on" and "off." this example creates a widget and assigns the aria switch role to it.
... examples the following examples should help you understand how to apply and use the switch role.
... adding the switch role in aria this simple example just creates a widget and assigns the aria switch role to it.
ARIA: textbox role - Accessibility
for example, in a combobox, focus may remain on the textbox while the value of aria-activedescendant on the textbox element refers to a descendant of a popup listbox that is controlled by the textbox.this attribute must be updated programmatically as the focus changes.
... 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.
... <div role="textbox" contenteditable="true"></div> example 2: adding the role in the html code for multi-line input the snippet below shows how the textbox role is added directly into the html source code.
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/ ...
... form validation wcag 2.0 and aria-conformant live form validation tables german tutorial on creating an accessible form simple grid example at codetalks date picker grid at codetalks wcag 2.0 and aria-conformant sortable tables ...
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 ...
...using firefox as an example, it explains that by changing the value the image.animation_mode from "normal" to "none", all animated images will be blocked.
...in the screenshot below, you can see an example of windows 10 accessibility settings allowing for color filters to be selected.
Keyboard - Accessibility
focusable elements should have interactive semantics if an element can be focused using the keyboard, then it should be interactive; that is, the user should be able to do something to it and produce a change of some kind (for example, activating a link or changing an option).
...however, you should only add tabindex if you have also made the element interactive, for example, by defining appropriate event handlers keyboard events.
... see also global event handlers: onkeydown global event handlers: onkeyup interactive elements must be focusable if the user can interact with an element (for example, using touch or a pointing device), then it should be focusable using the keyboard.
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.
... the "good" <div> has a light purple background, which makes the text easy to read: example1 <div class="good"> good contrast </div> div { font-family: sans-serif; text-align: center; font-size: 2rem; font-weight: bold; width: 250px; padding: 30px; border-radius: 20px; box-shadow: 1px 1px 1px black; } .good { background-color: #fae6fa; } the "bad" <div> on the other hand has a very dark purple background, which makes the text much harder to read: example2 <div class="bad"> bad contrast </div> div { font-family: sans-serif; text-align: center; font-size: 2rem; font-weight: bold; width: 250px; padding: 30px; border-radius: 20px; box-shadow: 1px 1px 1px black; } .bad { background-color: #400064; } solution when cho...
...try using it on the live examples in the description section.
-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.
...for example: .img1 { width: 100px; height: 100px; -moz-context-properties: fill, stroke; fill: lime; stroke: purple; } now that you've done this, the svg image can use the values of the fill and stroke properties, for example: <img class="img1" src="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg'> <rect width='100%' height='100%' stroke-width='30px' fill='context-fill red' stroke='context-stroke' fill-opacity='0.5'/></svg>"> here we've set the image src to a data uri containing a simple svg image; the <rect> inside has been made to take its fill and stroke val...
... note: you can find a working example on github.
::after (:after) - CSS: Cascading Style Sheets
WebCSS::after
examples simple usage let's create two classes: one for boring paragraphs and one for exciting ones.
... html <p class="boring-text">here is some plain old boring text.</p> <p>here is some normal text that is neither boring nor exciting.</p> <p class="exciting-text">contributing to mdn is easy and fun.</p> css .exciting-text::after { content: " <- exciting!"; color: green; } .boring-text::after { content: " <- boring"; color: red; } result decorative example we can style text or images in the content property almost any way we want.
...</span> css .ribbon { background-color: #5bc8f7; } .ribbon::after { content: "this is a fancy orange box."; background-color: #ffba10; border-color: black; border-style: dotted; } result tooltips this example uses ::after, in conjunction with the attr() css expression and a data-descr custom data attribute, to create tooltips.
:not() - CSS: Cascading Style Sheets
WebCSS:not
for example, :not(*) matches any element which is not an element, which is obviously nonsense, so the accompanying rule will never be applied.
...for example, #foo:not(#bar) will match the same element as the simpler #foo, but has a higher specificity.
... 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 :not(div):not(span) { font-weight: bold; } /* elements that are not `.crazy` or `.fancy` ...
:nth-child() - CSS: Cascading Style Sheets
'='<attr-modifier> = i | s examples example selectors tr:nth-child(odd) or tr:nth-child(2n+1) represents the odd rows of an html table: 1, 3, 5, etc.
...this may seem weird at first, but it makes more sense when the b part of the formula is >0, like in the next example.
... detailed example html <h3><code>span:nth-child(2n+1)</code>, without an <code>&lt;em&gt;</code> among the child elements.</h3> <p>children 1, 3, 5, and 7 are selected.</p> <div class="first"> <span>span 1!</span> <span>span 2</span> <span>span 3!</span> <span>span 4</span> <span>span 5!</span> <span>span 6</span> <span>span 7!</span> </div> <br> <h3><code>span:nth-child(2n+1)</code>, with an ...
:nth-last-child() - CSS: Cascading Style Sheets
'='<attr-modifier> = i | s examples example selectors tr:nth-last-child(odd) or tr:nth-last-child(2n+1) represents the odd rows of an html table: 1, 3, 5, etc., counting from the end.
... table example html <table> <tbody> <tr> <td>first line</td> </tr> <tr> <td>second line</td> </tr> <tr> <td>third line</td> </tr> <tr> <td>fourth line</td> </tr> <tr> <td>fifth line</td> </tr> </tbody> </table> css table { border: 1px solid blue; } /* selects the last three elements */ tr:nth-last-child(-n+3) { background-color:...
...in this example, list items turn red when there are at least three of them in a given list.
:target - CSS: Cascading Style Sheets
WebCSS:target
/* selects an element with an id matching the current url's fragment */ :target { border: 2px solid black; } for example, the following url has a fragment (denoted by the # sign) that points to an element called section2: http://www.example.com/index.html#section2 the following element would be selected by a :target selector when the current url is equal to the above: <section id="section2">example</section> syntax :target examples a table of contents the :target pseudo-class can be used to highlight the portion of a page that has been linked to from a table of contents.
... html <ul> <li><a href="#example1">open example #1</a></li> <li><a href="#example2">open example #2</a></li> </ul> <div class="lightbox" id="example1"> <figure> <a href="#" class="close"></a> <figcaption>lorem ipsum dolor sit amet, consectetur adipiscing elit.
... donec felis enim, placerat id eleifend eu, semper vel sem.</figcaption> </figure> </div> <div class="lightbox" id="example2"> <figure> <a href="#" class="close"></a> <figcaption>cras risus odio, pharetra nec ultricies et, mollis ac augue.
:where() - CSS: Cascading Style Sheets
WebCSS:where
examples comparing :where() and :is() this example shows how :where() works, and also illustrates the difference between :where() and :is().
... </footer> </article> in this somewhat-contrived example, we have two articles that each contain a section, an aside, and a footer.
... note: you can also find this example on github; see is-where.
@document - CSS: Cascading Style Sheets
WebCSS@document
@document url("https://www.example.com/") { h1 { color: green; } } syntax an @document rule can specify one or more matching functions.
...for example, a .
... 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.
@keyframes - CSS: Cascading Style Sheets
for example: @keyframes identifier { 0% { top: 0; left: 0; } 30% { top: 50px; } 68%, 72% { left: 50px; } 100% { top: 100px; left: 100%; } } here, the top property animates using the 0%, 30%, and 100% keyframes, and left animates using the 0%, 68%, 72% and 100% keyframes.
...for example: @keyframes identifier { 0% { top: 0; } 50% { top: 30px; left: 20px; } 50% { top: 10px; } 100% { top: 0; } } in this example, at the 50% keyframe, the values used are top: 10px and left: 20px.
... 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.
forced-colors - CSS: Cascading Style Sheets
examples note: no browser currently implements this feature so the following example will not work.
... this example has an annoying color palette by default.
... this example does not take advantage of the colors provided by the user agent.
light-level - CSS: Cascading Style Sheets
for example: night time, or a dimly illuminated indoor environment.
...for example: bright daylight.
... examples this code will likely not work on any devices (device compatibility is low).
Alternative style sheets - CSS: Cascading Style Sheets
an example: specifying the alternative stylesheets the alternate stylesheets are commonly specified using a <link> element with rel="alternate stylesheet" and title="..." attributes.
... for example: <link href="reset.css" rel="stylesheet" type="text/css"> <link href="default.css" rel="stylesheet" type="text/css" title="default style"> <link href="fancy.css" rel="alternate stylesheet" type="text/css" title="fancy"> <link href="basic.css" rel="alternate stylesheet" type="text/css" title="basic"> in this example, the styles "default style", "fancy", and "basic" will be listed in the page style submenu, with "default style" pre-selected.
... try it out click here for a working example you can try out.
Box alignment in grid layout - CSS: Cascading Style Sheets
basic example in this example using grid layout, there is extra space in the grid container after laying out the fixed width tracks on the inline (main) axis.
... the block axis crosses the inline axis in the direction that blocks are displayed down the page — for example paragraphs in english are displayed one below the other vertically.
...the exception to this rule is where the item has an intrinsic aspect ratio, for example an image.
Styling Columns - CSS: Cascading Style Sheets
in the example below, the column-gap is set to 40px.
... in this next example i have created a 5px dotted rule with a color of rebeccapurple, using the longhand values.
... in this next example we have a very wide rule of 40px and a 10px gap.
Backwards Compatibility of Flexbox - CSS: Cascading Style Sheets
flex containers in the following live example, i have floated two blocks and then set display: flex on the container.
...for example, two contiguous flex items with display: table-cell will become two separate display: block flex items, instead of being wrapped into a single anonymous table.” - 4.
... flex items the vertical-align property the live example below demonstrates use of the vertical-align property along with display: inline-block.
CSS Grid Layout - CSS: Cascading Style Sheets
for example, a grid container's child elements could position themselves so they actually overlap and layer, similar to css positioned elements.
... basic example the example below shows a three-column track grid with new rows created at a minimum of 100 pixels and a maximum of auto.
... 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 counters - CSS: Cascading Style Sheets
for example, you can use counters to automatically number the headings in a webpage.
... basic example this example adds "section [the value of the counter]:" to the beginning of each heading.
... example of a nested counter css ol { counter-reset: section; /* creates a new instance of the section counter with each ol element */ list-style-type: none; } li::before { counter-increment: section; /* increments only this instance of the ...
CSS Overflow - CSS: Cascading Style Sheets
basic example the following interactive example shows how changing the value of the overflow property, changes how the overflow of a fixed height box is dealt with.
... the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
The stacking context - CSS: Cascading Style Sheets
the example in this example, every positioned element creates its own stacking context, because of their positioning and z-index values.
...in our example (sorted according to the final rendering order): root div #2 - z-index is 2 div #3 - z-index is 4 div #5 - z-index is 1, stacked under an element with a z-index of 4, which results in a rendering order of 4.1 div #6 - z-index is 3, stacked under an element with a z-index of 4, which results in a rendering order of 4.3 div #4 - z-index is 6, stacked...
... under an element with a z-index of 4, which results in a rendering order of 4.6 div #1 - z-index is 5 example html <div id="div1"> <h1>division element #1</h1> <code>position: relative;<br/> z-index: 5;</code> </div> <div id="div2"> <h1>division element #2</h1> <code>position: relative;<br/> z-index: 2;</code> </div> <div id="div3"> <div id="div4"> <h1>division element #4</h1> <code>position: relative;<br/> z-index: 6;</code> </div> <h1>division element #3</h1> <code>position: absolute;<br/> z-index: 4;</code> <div id="div5"> <h1>division element #5</h1> <code>position: relative;<br/> z-index: 1;</code> </div> <div id="div6"> <h1>division element #6</h1> <code>position: absolute;<br/> z-inde...
Browser compatibility and Scroll Snap - CSS: Cascading Style Sheets
if you have already used the old implementation as a fallback, or feel you want to support users of old firefox (or -webkit prefixed safari), then you can continue to use the old specification as outlined in the example below.
... in this initial example we have used the old specification alongside the current specification in order to make scroll snapping work in all browsers which support some form of scroll snapping.
... the example adds the scroll-snap-points-y and scroll-snap-destination properties, which are deprecated, to make scroll snapping work in firefox.
Sticky footers - CSS: Cascading Style Sheets
the recipe download this example note: in this example and the following one we are using a wrapper set to min-height: 100% in order that our live example works.
... choices made in the above example we achieve the sticky footer using css grid layout.
... the flexbox example starts out in the same way, but we use display:flex rather than display:grid on the .wrapper; we also set flex-direction to column.
Specificity - CSS: Cascading Style Sheets
class selectors (e.g., .example), attributes selectors (e.g., [type="radio"]) and pseudo-classes (e.g., :hover).
... id selectors (e.g., #example).
... 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.
Viewport concepts - CSS: Cascading Style Sheets
iframe { width: 50vw; } if the iframe is set to 50vw, it will be 50% of the width of the 1200px parent document in our example above, or 600px, with 1vw being 6px.
... <svg height="300" width="400"></svg> in this examples, the viewport has an aspect ratio of 3::4, and is, but default, 400 by 300 units, with a unit generally being a css pixel.
...for example, if a mobile screen has a width of 320px, a website might be rendered with a virtual viewport of 980px, and then it will be shrunk down to fit into the 320px space, which, depending on the design, is illegible for many if not everyone.
align-self - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...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 c...
all - CSS: Cascading Style Sheets
WebCSSall
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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-duration - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... formal definition initial value0sapplies toall elements, ::before and ::after pseudo-elementsinheritednocomputed valueas specifiedanimation typediscrete formal syntax <time># examples see css animations for examples.
animation-name - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...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>e...
background-clip - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...)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-origin - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...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('mainbac...
background-position-x - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...]#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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...]#where <length-percentage> = <length> | <percentage> examples basic example the following example shows a simple background image implementation, with background-position-x and background-position-y used to define the image's horizontal and vertical positions separately.
background - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...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 ...
<basic-shape> - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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 lev...
border-block-end-style - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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 ...
border-block-end-width - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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 leve...
border-block-end - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...)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 'bord...
border-block-start-color - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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 l...
border-block-start-style - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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 value...
border-block-start-width - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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 le...
border-block-start - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...)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-bloc...
border-bottom-color - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...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-width - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...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-w...
border-bottom - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...)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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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> <...
border-color - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...)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 e...
border-image-repeat - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...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-source - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...| <'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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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-...
border-inline-end-style - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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-...
border-inline-end-width - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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 value...
border-inline-end - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...)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 specificatio...
border-inline-start-color - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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-st...
border-inline-start-style - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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-...
border-inline-start-width - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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-sta...
border-inline-start - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...)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 specific...
border-left-color - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...)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-width - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...)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-right-color - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...)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-width - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...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 t...
border-right - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...)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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... examples spacing and padding table cells this example applies a spacing of .5em vertically and 1em horizontally between a table's cells.
border-top-color - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...)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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...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-width - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...)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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...the 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, ...
border - CSS: Cascading Style Sheets
WebCSSborder
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...)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
WebCSSbottom
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...)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).
caption-side - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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 { c...
clear - CSS: Cascading Style Sheets
WebCSSclear
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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.
color-adjust - CSS: Cascading Style Sheets
for example, when printing, a browser might opt to leave out all background images and to adjust text colors to be sure the contrast is optimized for reading on white paper.
...for example, a page might include a list of information with rows whose background colors alternate between white and a light grey.
... 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.
color - CSS: Cascading Style Sheets
WebCSScolor
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...)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 sta...
column-count - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...)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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
WebCSScolumns
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...]+ | 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...]+ | 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.
direction - CSS: Cascading Style Sheets
WebCSSdirection
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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.
element() - CSS: Cascading Style Sheets
WebCSSelement
examples these examples can be viewed live in builds of firefox that support -moz-element().
... a somewhat realistic example this example uses a hidden <div> as a background.
... a somewhat more bizarre example this example uses a hidden <button> element in a repeating pattern as its background.
empty-cells - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... formal definition initial valueshowapplies totable-cell elementsinheritedyescomputed valueas specifiedanimation typediscrete formal syntax show | hide example showing and hiding empty table cells html <table class="table_1"> <tr> <td>moe</td> <td>larry</td> </tr> <tr> <td>curly</td> <td></td> </tr> </table> <br> <table class="table_2"> <tr> <td>moe</td> <td>larry</td> </tr> <tr> <td>curly</td> <td></td> </tr> </table> css .table_1 { empty-cells: show; } .table_2 { empty-cells: hide; } td, th {...
blur() - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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 specif...
grayscale() - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
WebCSSflex-flow
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
WebCSSflex-grow
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
WebCSSflex-wrap
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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 fl...
flex - CSS: Cascading Style Sheets
WebCSSflex
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...| <'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 r...
font-feature-settings - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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 form...
font-optical-sizing - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...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-synthesis - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...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-ligatures - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... | 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 - CSS: Cascading Style Sheets
WebCSSfont
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...<'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.
<frequency> - CSS: Cascading Style Sheets
WebCSSfrequency
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.
grid-area - CSS: Cascading Style Sheets
WebCSSgrid-area
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...] | [ 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 specification...
grid-auto-columns - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...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 layo...
grid-auto-flow - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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()"> <labe...
grid-auto-rows - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...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 d...
grid-column-end - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...] | [ 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-sta...
grid-column-start - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...] | [ 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-s...
grid-column - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...] | [ 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...] | [ 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...] | [ 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-star...
grid-row - CSS: Cascading Style Sheets
WebCSSgrid-row
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...] | [ 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; gr...
grid-template-areas - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...)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-te...
grid-template-rows - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...)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-templa...
grid-template - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...<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: lightb...
grid - CSS: Cascading Style Sheets
WebCSSgrid
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
.../ <'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 co...
height - CSS: Cascading Style Sheets
WebCSSheight
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...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
WebCSShyphens
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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.
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 ...
... providing fallback images .help::before { content: image("try.webp", "try.svg", "try.gif"); } in this example, the browser will display an image as generated content before the content of the element with the class of help.
...if not, the svg example will be shown.
Inheritance - CSS: Cascading Style Sheets
a typical example of an inherited property is the color property.
... a typical example of a non-inherited property is the border property.
...for example: font { all: revert; font-size: 200%; font-weight: bold; } this reverts the style of the font property to the user agent's default unless a user stylesheet exists, in which case that is used instead.
inline-size - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
WebCSSisolation
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...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-items - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...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.
letter-spacing - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...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-s...
list-style-image - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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-...
list-style - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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 def...
margin-block-start - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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 d...
margin-inline-start - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...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 1t...
margin-left - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...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.
mask-repeat - CSS: Cascading Style Sheets
example: an image with an original width of 260px, repeated three times, might stretch until each repetition is 300px wide, and then another image will be added.
... 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...
...on> <option value="no-repeat">no-repeat</option> </select> javascript content var repetition = document.getelementbyid("repetition"); repetition.addeventlistener("change", function (evt) { document.getelementbyid("masked").style.maskrepeat = evt.target.value; }); result multiple mask image support you can specify a different <repeat-style> for each mask image, separated by commas: .examplethree { mask-image: url('mask1.png'), url('mask2.png'); mask-repeat: repeat-x, repeat-y; } each image is matched with the corresponding repeat style, from first specified to last.
max-height - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
..., 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
WebCSSmax-width
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...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.
min-block-size - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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 specificat...
min-width - CSS: Cascading Style Sheets
WebCSSmin-width
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...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.
minmax() - CSS: Cascading Style Sheets
WebCSSminmax
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...| [ [ 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.
order - CSS: Cascading Style Sheets
WebCSSorder
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... & the 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...)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 spec...
outline-offset - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
WebCSSoutline
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...the 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 inter...
overflow-wrap - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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 ...
overflow-y - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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.
padding-block-end - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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 ...
padding-block-start - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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 a...
padding-bottom - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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 ...
padding-inline-start - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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 val...
padding-left - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...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
WebCSSpadding
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...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; ...
perspective - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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-colo...
place-self - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... examples simple demonstration in the following example we have a simple 2 x 2 grid layout.
scroll-behavior - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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-snap-type - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... examples snapping in different axes html <div class="holster"> <div class="container x mandatory-scroll-snapping" dir="ltr"> <div>x mand.
shape-margin - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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 ...
shape-outside - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...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.
<string> - CSS: Cascading Style Sheets
WebCSSstring
for example, \22 represents a double quote, \27 a single quote ('), and \a9 the copyright symbol (©).
...for example, \\ will create a single backslash.
... 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." ...
table-layout - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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-decoration-line - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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-deco...
text-decoration-style - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...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: r...
text-emphasis - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...: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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...&& 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; } resu...
text-orientation - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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-rendering - CSS: Cascading Style Sheets
one very visible effect is optimizelegibility, which enables ligatures (ff, fi, fl, etc.) in text smaller than 20px for some fonts (for example, microsoft's calibri, candara, constantia, and corbel, or the dejavu font family).
... 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.
... html <p class="small">lyowat - ff fi fl ffl</p> <p class="big">lyowat - ff fi fl ffl</p> css .small { font: 19.9px "constantia", "times new roman", "georgia", "palatino", serif; } .big { font: 20px "constantia", "times new roman", "georgia", "palatino", serif; } result optimizespeed vs optimizelegibility this example shows the difference between the appearance of optimizespeed and optimizelegibility (in your browser; other browsers may vary).
text-shadow - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...)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:...
<time> - CSS: Cascading Style Sheets
WebCSStime
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.
top - CSS: Cascading Style Sheets
WebCSStop
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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 specificati...
touch-action - CSS: Cascading Style Sheets
the touch-action css property sets how an element's region can be manipulated by a touchscreen user (for example, by zooming features built into the browser).
...multiple directions may be combined except when there is a simpler representation (for example, "pan-left pan-right" is invalid since "pan-x" is simpler, but "pan-left pan-down" is valid).
...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.
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.
... html <section id="example-element" tabindex="0"> <div class="face front">1</div> <div class="face back">2</div> <div class="face right">3</div> <div class="face left">4</div> <div class="face top">5</div> <div class="face bottom">6</div> </section> css #example-element { width: 100px; height: 100px; transform-style: preserve-3d; transition: transform 1.5s; transform: rotate3d(1, 1, 1, 30deg); margin: 50px auto; } #example-element:hover, #example-element:focus { transform: rotate3d(1, 1, 1, 30deg) matrix3d(1,0,0,0,0,1,6,0,0,0,1,0,50,100,0,1.1); } .face { display: flex; align-items: center; justify-content: center; width: 100%; height: 100%; position: absolute; backface-visibility: inherit; font-size: 60px; color: #fff; } .front { background:...
...ght { background: rgba(210,0,0,.7); transform: rotatey(90deg) translatez(50px); } .left { background: rgba(0,0,210,.7); transform: rotatey(-90deg) translatez(50px); } .top { background: rgba(210,210,0,.7); transform: rotatex(90deg) translatez(50px); } .bottom { background: rgba(210,0,210,.7); transform: rotatex(-90deg) translatez(50px); } result matrix translation and scale example another transform3d() example, which implements an animated combined translate and scale.
perspective() - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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="perspect...
rotate3d() - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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: 800...
rotateX() - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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 <di...
transform - CSS: Cascading Style Sheets
WebCSStransform
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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.
white-space - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...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
WebCSSwidth
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...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> <...
word-break - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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.
z-index - CSS: Cascading Style Sheets
WebCSSz-index
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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 */ b...
Live streaming web audio and video - Developer guides
for example: <video src="rtsp://myhost.com/mymedia.format"> <!-- fallback here --> </video> media source extensions (mse) media source extensions is a w3c working draft that plans to extend htmlmediaelement to allow javascript to generate media streams for playback.
... for example, you could implement mpeg-dash using javascript while offloading the decoding to mse.
...so for example, if we detect that the network is slow, we can start requesting lower quality (smaller) chunks for the next segment.
Media buffering, seeking, and time ranges - Developer guides
sometimes it's useful to know how much <audio> or <video> has downloaded or is playable without delay — a good example of this is the buffered progress bar of an audio or video player.
... this will work with <audio> or <video>; for now let's consider a simple audio example: <audio id="my-audio" controls src="music.mp3"> </audio> we can access these attributes like so: var myaudio = document.getelementbyid('my-audio'); var bufferedtimeranges = myaudio.buffered; timeranges object timeranges are a series of non-overlapping ranges of time, with start and stop times.
...for example: var played = audio.played; // returns a timeranges object this could be useful for establishing the parts of your media that are most listened to or watched.
Block formatting context - Developer guides
examples contain internal floats make float content and alongside content the same height.
... in the following example, we have a floated element inside a <div> with a border applied.
...{ height:150px; } .box { background-color: rgb(224, 206, 247); border: 5px solid rebeccapurple; } .box[style] { background-color: aliceblue; border: 5px solid steelblue; } .float { float: left; width: 200px; height: 100px; background-color: rgba(255, 255, 255, .5); border:1px solid black; padding: 10px; } exclude external floats in the following example, we are using display:flow-root and floats to implement double columns layout, beacuse an element in the normal flow that establishes a new bfc must not overlap the margin box of any floats in the same block formatting context as the element itself.
HTML5 Parser - Developer guides
WebGuideHTMLHTML5HTML5 Parser
if you tested your site only with gecko 1.x or webkit (for example, firefox-only intranets or webkit-oriented mobile sites), then you might have tags that match this pattern, and they will behave differently with gecko 2.
...for example, if the document lacked a </title> closing tag, the parser would reparse to look for the first '<' in the document, or if a comment was not closed, it would look for the first '>'.
...(there are also some element whose end tags can be omitted in some cases, such as <p> in the example below, but it's simpler to always use end tags for those elements than to make sure that the end tags are only omitted when they aren't necessary.) for example, the following code writes a balanced sub-tree: <script> document.write("<div>"); document.write("<p>some content goes here.</p>"); document.write("</div>"); </script> <!-- non-script html goes here.
Separate sites for mobile and desktop - Developer guides
the good the first option is the most popular by far: use user-agent detection to route users on phones to a separate mobile site, typically at m.example.com.
...examples most of the major web applications you see in the wild have chosen this path, including facebook, youtube, digg, and flickr.
...if you’d like to see the source code behind an example of this approach in action, feel free to check out the github repository for amo or sumo.
Developer guides
having native audio and video in the browser means we can use these data streams with technologies such as <canvas>, webgl or web audio api to modify audio and video directly, for example adding reverb/compression effects to audio, or grayscale/sepia filters to video.
... user input and controls modern web user input goes beyond simple mouse and keyboard: think of touchscreens for example.
... 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: min - HTML: Hypertext Markup Language
WebHTMLAttributesmin
for example, if we have <input type="number" min="10" step="2"> any even integer, 10 or great, is valid.
...for 4.2 to be valid, step would have had to be set to any, 0.1, 0.2, or any the min value would have had to be a number ending in .2, such as <input type="number" min="-5.2"> syntax for min values by input type input type example example date yyyy-mm-dd <input type="date" min="2019-12-25" step="1"> month yyyy-mm <input type="month" min="2019-12" step="12"> week yyyy-w## <input type="week" min="2019-w23" step=""> time hh:mm <input type="time" min="09:00" step="900"> datetime-local yyyy-mm-ddthh:mm <input type="datetime-local" min="2019-12-25t19:30"> number <number> <input ...
... syntax for min values for other elements input type syntax example <meter> <number> <meter id="fuel" min="0" max="100" low="33" high="66" optimum="80" value="40"> at 40/100</meter> impact on step the value of min and step define what are valid values, even if the step attribute is not included, as step defaults to 0.
HTML attribute: rel - HTML: Hypertext Markup Language
WebHTMLAttributesrel
if the most appropriate icon is later found to be inappropriate, for example because it uses an unsupported format, the browser proceeds to the next-most appropriate, and so on.
...for example, with type="application/rss+xml" it creates a hyperlink referencing a syndication feed.
...if the most appropriate icon is later found to be inappropriate, for example because it uses an unsupported format, the browser proceeds to the next-most appropriate, and so on.
Allowing cross-origin use of images and canvas - HTML: Hypertext Markup Language
storing an image from a foreign origin in this example, we wish to permit images from a foreign origin to be retrieved and saved to local storage.
... that handles the newly-downloaded image is found in the imagereceived() method: function imagereceived() { let canvas = document.createelement("canvas"); let context = canvas.getcontext("2d"); canvas.width = downloadedimg.width; canvas.height = downloadedimg.height; context.drawimage(downloadedimg, 0, 0); imagebox.appendchild(canvas); try { localstorage.setitem("saved-image-example", canvas.todataurl("image/png")); } catch(err) { console.log("error: " + err); } } imagereceived() is called to handle the "load" event on the htmlimageelement that receives the downloaded image.
... you can try out or remix this example on glitch.
<address>: The Contact Address element - HTML: Hypertext Markup Language
WebHTMLElementaddress
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... examples this example demonstrates the use of <address> to demarcate the contact information for an article's author.
<area> - HTML: Hypertext Markup Language
WebHTMLElementarea
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...(the 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 pol...
<aside>: The Aside element - HTML: Hypertext Markup Language
WebHTMLElementaside
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... examples using <aside> this example uses <aside> to mark up a paragraph in an article.
<blockquote>: The Block Quotation element - HTML: Hypertext Markup Language
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... example this example demonstrates the use of the <blockquote> element to quote a passage from rfc 1149, a standard for the transmission of ip datagrams on avian carriers.
<center>: The Centered Text element (obsolete) - HTML: Hypertext Markup Language
WebHTMLElementcenter
example 1 <center>this text will be centered.
... <p>so will this paragraph.</p></center> example 2 (css alternative) <div style="text-align:center">this text will be centered.
... <p>so will this paragraph.</p></div> example 3 (css alternative) <p style="text-align:center">this line will be centered.<br> and so will this line.</p> note applying text-align:center to a <div> or <p> element centers the contents of those elements while leaving their overall dimensions unchanged.
<code>: The Inline Code element - HTML: Hypertext Markup Language
WebHTMLElementcode
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... example a paragraph of text that includes <code>: <p>the function <code>selectall()</code> highlights all the text in the input field so the user can, for example, copy or delete the text.</p> the output generated by this html looks like this: notes to represent multiple lines of code, wrap the <code> element within a <pre> element.
<col> - HTML: Hypertext Markup Language
WebHTMLElementcol
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... examples please see the <table> page for examples on <col>.
<colgroup> - HTML: Hypertext Markup Language
WebHTMLElementcolgroup
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... examples please see the <table> page for examples on <colgroup>.
<data> - HTML: Hypertext Markup Language
WebHTMLElementdata
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
WebHTMLElementdatalist
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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 ...
<dd>: The Description Details element - HTML: Hypertext Markup Language
WebHTMLElementdd
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... example for an example, see <dl> examples.
<dt>: The Description Term element - HTML: Hypertext Markup Language
WebHTMLElementdt
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... example for an example, see the example provided for the <dl> element.
<embed>: The Embed External Content element - HTML: Hypertext Markup Language
WebHTMLElementembed
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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.
<figcaption>: The Figure Caption element - HTML: Hypertext Markup Language
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... examples please see the <figure> page for examples on <figcaption>.
<footer> - HTML: Hypertext Markup Language
WebHTMLElementfooter
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... examples <footer> some copyright info or perhaps some author info for an &lt;article&gt;?
<header> - HTML: Hypertext Markup Language
WebHTMLElementheader
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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://janesmit...
<i>: The Idiomatic Text element - HTML: Hypertext Markup Language
WebHTMLElementi
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... examples this example demonstrates using the <i> element to mark text that is in another language.
<ins> - HTML: Hypertext Markup Language
WebHTMLElementins
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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.
<legend> - HTML: Hypertext Markup Language
WebHTMLElementlegend
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... examples see <form> for examples on <legend>.
<li> - HTML: Hypertext Markup Language
WebHTMLElementli
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... examples for more detailed examples, see the <ol> and <ul> pages.
<main> - HTML: Hypertext Markup Language
WebHTMLElementmain
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... example <!-- other content --> <main> <h1>apples</h1> <p>the apple is the pomaceous fruit of the apple tree.</p> <article> <h2>red delicious</h2> <p>these bright red apples are the most common found in many supermarkets.</p> <p>...
<map> - HTML: Hypertext Markup Language
WebHTMLElementmap
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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 ke...
<nextid>: The NeXT ID element (Obsolete) - HTML: Hypertext Markup Language
WebHTMLElementnextid
html "0.a" - from the beginning through january 10, 1991 this tag had not been invented as yet, so no examples are found from this period.
... example the user enters four section headings into the table of contents (and presumably also writing paragraph material within these sections).
...</p> </body> </html> html reference working nextid tag element example 5.2.6.
<object> - HTML: Hypertext Markup Language
WebHTMLElementobject
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...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...
<optgroup> - HTML: Hypertext Markup Language
WebHTMLElementoptgroup
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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 specificati...
<option>: The HTML Option element - HTML: Hypertext Markup Language
WebHTMLElementoption
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... examples see <select> for examples.
<p>: The Paragraph element - HTML: Hypertext Markup Language
WebHTMLElementp
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... example html <p>this is the first paragraph of text.
<progress>: The Progress Indicator element - HTML: Hypertext Markup Language
WebHTMLElementprogress
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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.
<q>: The Inline Quotation element - HTML: Hypertext Markup Language
WebHTMLElementq
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... example <p>according to mozilla's website, <q cite="https://www.mozilla.org/about/history/details/">firefox 1.0 was released in 2004 and became a big success.</q></p> specifications specification status comment html living standardthe definition of '<q>' in that specification.
<rtc>: The Ruby Text Container element - HTML: Hypertext Markup Language
WebHTMLElementrtc
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
WebHTMLElementruby
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
WebHTMLElements
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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.
<small>: the side comment element - HTML: Hypertext Markup Language
WebHTMLElementsmall
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... examples basic usage <p>this is the first sentence.
<span> - HTML: Hypertext Markup Language
WebHTMLElementspan
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... example example 1 html <p><span>some text</span></p> result example 2 html <li><span> <a href="portfolio.html" target="_blank">see my portfolio</a> </span></li> css li span { background: gold; } result specifications specification status comment html living standardthe definition of '<span>' in that specification.
<strong>: The Strong Importance element - HTML: Hypertext Markup Language
WebHTMLElementstrong
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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 specificati...
<td>: The Table Data Cell element - HTML: Hypertext Markup Language
WebHTMLElementtd
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... examples see <table> for examples on <td>.
<tfoot>: The Table Foot element - HTML: Hypertext Markup Language
WebHTMLElementtfoot
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... examples please see the <table> page for examples on <tfoot>.
<th> - HTML: Hypertext Markup Language
WebHTMLElementth
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... examples see <table> for examples on <th>.
<thead>: The Table Head element - HTML: Hypertext Markup Language
WebHTMLElementthead
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... examples see <table> for examples on <thead>.
<title>: The Document Title element - HTML: Hypertext Markup Language
WebHTMLElementtitle
example <title>awesome interesting stuff</title> this example establishes a page whose title (as displayed at the top of the window or in the window's tab) as "awesome interesting stuff".
... example <title>menu - blue house chinese food - foodyum: online takeout today!</title> to help the user, update the page title value to reflect significant page state changes (such as form validation problems).
... example <title>2 errors - your order - blue house chinese food - foodyum: online takeout today!</title> mdn understanding wcag, guideline 2.4 explanations understanding success criterion 2.4.2 | w3c understanding wcag 2.0 specifications specification status comment html living standardthe definition of '<title>' in that specification.
<tt>: The Teletype Text element (obsolete) - HTML: Hypertext Markup Language
WebHTMLElementtt
if none of the semantic elements are appropriate for your use case (for example, if you simply need to show some content in a non-proportional font), you should consider using the <span> element, styling it as desired using css.
... permitted aria roles any dom interface htmlelement attributes this element only includes the global attributes examples basic example this example uses <tt> to show text entered into, and output by, a terminal application.
...you can override this using css by creating a rule using the tt selector, as seen in the example overriding the default font above.
<ul>: The Unordered List element - HTML: Hypertext Markup Language
WebHTMLElementul
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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!
class - HTML: Hypertext Markup Language
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...for example, attribute to describe an attribute rather than italics, although an element of this class may be presented by italics.
contenteditable - HTML: Hypertext Markup Language
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... if the attribute is given without a value, like <label contenteditable>example label</label>, its value is treated as an empty string.
data-* - HTML: Hypertext Markup Language
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...for example, a space-ship "sprite" in a game could be a simple <img> element with a class attribute and several data-* attributes: <img class="spaceship cruiserx3" src="shipx3.png" data-ship-id="324" data-weapons="laseri laserii" data-shields="72%" data-x="414354" data-y="85160" data-z="31940" onclick="spaceships[this.dataset.shipid].blasted()"> for a more in-depth tutorial about using html data att...
itemid - HTML: Hypertext Markup Language
however, the following example correctly illustrates that a urn may also be used.
... example 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.
... hamilton <dt>publication date <dd><time itemprop="pubdate" datetime="1996-01-26">26 january 1996</time> </dl> structured data itemscope itemtype: itemid http://vocab.example.net/book: urn:isbn:0-330-34032-8 itemprop title the reality dysfunction itemprop author peter f.
style - HTML: Hypertext Markup Language
this attribute and the <style> element have mainly the purpose of allowing for quick styling, for example for testing purposes.
... the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
tabindex - HTML: Hypertext Markup Language
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...an example of this would be using a <div> element to describe a button, instead of the <button> element.
title - HTML: Hypertext Markup Language
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...some caution must be taken, as this means the following renders across two lines: html <p>newlines in <code>title</code> should be taken into account, like <abbr title="this is a multiline title">example</abbr>.</p> result title attribute inheritance if an element has no title attribute, then it inherits it from its parent node, which in turn may inherit it from its parent, and so on.
Global attributes - HTML: Hypertext Markup Language
for example, html5-compliant browsers hide content marked as <foo hidden>...</foo>, even though <foo> is not a valid html element.
...for example, it can be used to hide elements of the page that can't be used until the login process has been completed.
...this attribute and the <style> element have mainly the purpose of allowing for quick styling, for example for testing purposes.
Link types - HTML: Hypertext Markup Language
for example, a blog entry could link to a monthly index page this way.
...if the most appropriate icon is later found to be inappropriate, for example because it uses an unsupported format, the browser proceeds to the next-most appropriate, and so on.
... nofollow indicates that the linked document is not endorsed by the author of this one, for example if it has no control over it, if it is a bad example or if there is commercial relationship between the two (sold link).
Microdata - HTML: Hypertext Markup Language
this vocabulary defines a standard set of type names and property names, for example, schema.org music event indicates a concert performance, with startdate and location properties to specify the concert's key details.
...for example, yandex, a major search engine in russia, supports microformats such as hcard (company contact information), hrecipe (food recipe), hreview (market reviews) and hproduct (product data) and provides its own format for the definition of the terms and encyclopedic articles.
... example html <div itemscope itemtype="http://schema.org/softwareapplication"> <span itemprop="name">angry birds</span> - requires <span itemprop="operatingsystem">android</span><br> <link itemprop="applicationcategory" href="http://schema.org/gameapplication"/> <div itemprop="aggregaterating" itemscope itemtype="http://schema.org/aggregaterating"> rating: <span itemprop="ratingvalue">...
HTML: Hypertext Markup Language
WebHTML
for example, the <title> tag can be written as <title>, <title>, or in any other way.
... 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.
HTTP authentication - HTTP
the auth_basic_user_file directive then points to a .htpasswd file containing the encrypted user credentials, just like in the apache example above.
... location /status { auth_basic "access to the staging site"; auth_basic_user_file /etc/apache2/.htpasswd; } access using credentials in the url many clients also let you avoid the login prompt by using an encoded url containing the username and the password like this: https://username:password@www.example.com/ the use of these urls is deprecated.
...in firefox, it is checked if the site actually requires authentication and if not, firefox will warn the user with a prompt "you are about to log in to the site “www.example.com” with the username “username”, but the website does not require authentication.
HTTP conditional requests - HTTP
comparing versions of the same resource is a bit tricky: depending on the context, there are two kinds of equality checks: strong validation is used when byte to byte identity is expected, for example when resuming a download.
...for example, a page that would differ from another only by a different date in its footer, or different advertising, would be considered identical to the other with weak validation.
...in this example, both last-modified and etag are sent, but it could equally have been only one of them.
Access-Control-Allow-Headers - HTTP
examples a custom header here's an example of what an access-control-allow-headers header might look like.
... access-control-allow-headers: x-custom-header multiple headers this example shows access-control-allow-headers when it specifies support for multiple headers.
... access-control-allow-headers: accept example preflight request let's look at an example of a preflight request involving access-control-allow-headers.
Clear-Site-Data - HTTP
so https://example.com as well as https://stage.example.com, will have cookies cleared.
... examples sign out of web site if a user signs out of your website or service, you might want to remove locally stored data.
... you can achieve that by adding the clear-site-data header when sending the page confirming that logging out from the site has been accomplished successfully (https://example.com/logout, for example): clear-site-data: "cache", "cookies", "storage", "executioncontexts" clearing cookies if this header is delivered with the response at https://example.com/clear-cookies, all cookies on the same domain https://example.com and any subdomains (like https://stage.example.com, etc), will be cleared out.
Content-Disposition - HTTP
when dealing with multiple files in the same field (for example, the multiple attribute of an <input type="file"> element), there can be several subparts with the same name.
... 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.
... an example of an html form posted using the multipart/form-data format that makes use of the content-disposition header: post /test.html http/1.1 host: example.org content-type: multipart/form-data;boundary="boundary" --boundary content-disposition: form-data; name="field1" value1 --boundary content-disposition: form-data; name="field2"; filename="example.txt" value2 --boundary-- specifications specification title rfc 7578 returning values from forms: multipart/form-data rfc 6266 use of the content-disposition header field in the hypertext transfer protocol (http) rfc 2183 communicating presentation information in internet messages: the content-disposition heade...
Content-Language - HTTP
for example, if "content-language: de-de" is set, it says that the document is intended for german language speakers (however, it doesn't indicate the document is written in german.
... for example, it might be written in english as part of a language course for german speakers.
... 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.
CSP: report-uri - HTTP
examples see content-security-policy-report-only for more information and examples.
... content-security-policy: default-src https:; report-uri /csp-violation-report-endpoint/ /csp-violation-report-endpoint/ could for example run a php something like the following that logs the json detailing the violation and, if the violation is the first one added to the log file, sends an email to an administrator: <?php // start configure $log_file = dirname(__file__) .
... '/csp-violations.log'; $log_file_size_limit = 1000000; // bytes - once exceeded no further entries are added $email_address = 'admin@example.com'; $email_subject = 'content-security-policy violation'; // end configuration $current_domain = preg_replace('/www\./i', '', $_server['server_name']); $email_subject = $email_subject .
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).
... <img src="http://example.com/image.png"> <img src="http://not-example.com/image.png"> these urls will be rewritten before the request is made, meaning that no insecure requests will hit the network.
... <img src="https://example.com/image.png"> <img src="https://not-example.com/image.png"> navigational upgrades to third-party resources brings a significantly higher potential for breakage, these are not upgraded: <a href="https://example.com/">home</a> <a href="http://not-example.com/">home</a> finding insecure requests with the help of the content-security-policy-report-only header and the report-uri directive, you can set-up an enforced policy and a reported policy like this: content-security-policy: upgrade-insecure-requests; default-src https: content-security-policy-report-only: default-src https:; report-uri /endpoint that way, you still upgrade insecure requ...
Digest - HTTP
WebHTTPHeadersDigest
the representation itself may be: fully contained in the response message body not at all contained in the message body (for example, in a response to a head request) partially contained in the message body (for example, in a response to a range request).
...the choice of digest algorithm also determines the encoding to use: for example sha-256 uses base64 encoding.
... 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 the original definition inconsistent with current http specifications.
ETag - HTTP
WebHTTPHeadersETag
for example, mdn uses a hexadecimal hash of the wiki article content.
... 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.
... for example, when editing mdn, the current wiki content is hashed and put into an etag in the response: etag: "33a64df551425fcc55e4d42a148795d9f25f89d4" when saving changes to a wiki page (posting data), the post request will contain the if-match header containing the etag values to check freshness against.
Expect - HTTP
WebHTTPHeadersExpect
for example, the server may reject a request if its content-length is too large.
... 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.
... put /somewhere/fun http/1.1 host: origin.example.com content-type: video/h264 content-length: 1234567890987 expect: 100-continue the server now checks the request headers and may respond with a 100 (continue) response to instruct the client to go ahead and send the message body, or it will send a 417 (expectation failed) status if any of the expectations cannot be met.
Public-Key-Pins - HTTP
example hpkp has the potential to lock out users for a long time if used incorrectly!
... public-key-pins: pin-sha256="cupctazwkaasuywhhnedttwpy3obake3h2+sozs7sws="; pin-sha256="m8hztczm3eluxkcjr2s5p4hhybnf6lhkmjahkhpgpwe="; max-age=5184000; includesubdomains; report-uri="https://www.example.org/hpkp-report" in this example, pin-sha256="cupctazwkaasuywhhnedttwpy3obake3h2+sozs7sws=" pins the server's public key used in production.
...finally, report-uri="https://www.example.org/hpkp-report" explains where to report pin validation failures.
Referer - HTTP
WebHTTPHeadersReferer
the referer header allows servers to identify where people are visiting them from and may use that data for analytics, logging, or optimized caching, for example.
..."username:password" in "https://username:password@example.com/foo/bar/") are not included.
... 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 ...
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".
... forcing lookup of specific hostnames you can force the lookup of specific hostnames without providing specific anchors using that hostname by using the rel attribute on the <link> element with a link type of dns-prefetch: <link rel="dns-prefetch" href="https://www.mozilla.org/contribute/"> in this example, the domain name "www.mozilla.org/contribute" will be pre-resolved.
... similarly, the link element can be used to resolve hostnames without providing a complete url, but only, by preceding the hostname with two slashes: <link rel="dns-prefetch" href="//www.mozilla.org/contribute/"> forced prefetching of hostnames might be useful, for example, on the homepage of a site to force pre-resolution of domain names that are referenced frequently throughout the site even though they are not used on the home page itself.
CONNECT - HTTP
WebHTTPMethodsCONNECT
for example, the connect method can be used to access websites that use ssl (https).
... request has body no successful response has body yes safe no idempotent no cacheable no allowed in html forms no syntax connect www.example.com:443 http/1.1 example some proxy servers might need authority to create a tunnel.
... connect server.example.com:80 http/1.1 host: server.example.com:80 proxy-authorization: basic agvsbg86d29ybgq= specifications specification title rfc 7231, section 4.3.6: connect hypertext transfer protocol (http/1.1): semantics and content ...
PATCH - HTTP
WebHTTPMethodsPATCH
for example if an auto-incrementing counter field is an integral part of the resource, then a put will naturally overwrite it (since it overwrites everything), but not necessarily so for patch.
... request has body yes successful response has body yes safe no idempotent no cacheable no allowed in html forms no syntax patch /file.txt http/1.1 example request patch /file.txt http/1.1 host: www.example.com content-type: application/example if-match: "e0023aa4e" content-length: 100 [description of changes] response a successful response is indicated by any 2xx status code.
... in the example below a 204 response code is used, because the response does not carry a payload body.
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.
... http 400 (bad request) response { "age": 20, "type": "network-error", "url": "https://example.com/previous-page", "body": { "elapsed_time": 338, "method": "post", "phase": "application", "protocol": "http/1.1", "referrer": "https://example.com/previous-page", "sampling_fraction": 1, "server_ip": "137.205.28.66", "status_code": 400, "type": "http.error", "url": "https://example.com/bad-request" } } dns name not resolved note that the phase is set to dns in this report and no server_ip is available to include.
... { "age": 20, "type": "network-error", "url": "https://example.com/previous-page", "body": { "elapsed_time": 18, "method": "post", "phase": "dns", "protocol": "http/1.1", "referrer": "https://example.com/previous-page", "sampling_fraction": 1, "server_ip": "", "status_code": 0, "type": "dns.name_not_resolved", "url": "https://example-host.com/" } } the type of the network error may be one of the following pre-defined values from the specification, but browsers can add and send their own error types: dns.unreachable the user's dns server is unreachable dns.name_not_resolved the user's dns server responded but was unable to resolve an ip address for the requested uri.
Using Promises - JavaScript
read the following example: new promise((resolve, reject) => { console.log('initial'); resolve(); }) .then(() => { throw new error('something failed'); console.log('do this'); }) .catch(() => { console.error('do that'); }) .then(() => { console.log('do this, no matter what happened before'); }); this will output the following text: initial do that do this, no matter what happened before note...
...the most obvious example is the settimeout() function: settimeout(() => saysomething("10 seconds passed"), 10*1000); mixing old-style callbacks and promises is problematic.
...several of these mistakes manifest in the following example: // bad example!
static - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...} examples using static in classes the following example demonstrates several things: how a static method is implemented on a class.
Classes - JavaScript
public field declarations with the javascript field declaration syntax, the above example can be written as: class rectangle { height = 0; width; constructor(height, width) { this.height = height; this.width = width; } } by declaring fields up-front, class definitions become more self-documenting, and the fields are always present.
... for example, when using methods such as map() that returns the default constructor, you want these methods to return a parent array object, instead of the myarray object.
...an ecmascript class can only have a single superclass, so multiple inheritance from tooling classes, for example, is not possible.
SyntaxError: Using //@ to indicate sourceURL pragmas is deprecated. Use //# instead - JavaScript
examples deprecated syntax syntax with the "@" sign is deprecated.
... //@ sourcemappingurl=http://example.com/path/to/your/sourcemap.map standard syntax use the "#" sign instead.
... //# sourcemappingurl=http://example.com/path/to/your/sourcemap.map or, alternatively, you can set a sourcemap header to your javascript file to avoid having a comment at all: sourcemap: /path/to/file.js.map ...
SyntaxError: test for equality (==) mistyped as assignment (=)? - JavaScript
examples assignment within conditional expressions it is advisable to not use simple assignments in a conditional expression (such as if...else), because the assignment can be confused with equality when glancing over the code.
... for example, do not use the following code: if (x = y) { // do the right thing } if you need to use an assignment in a conditional expression, a common practice is to put additional parentheses around the assignment.
... for example: if ((x = y)) { // do the right thing } otherwise, you probably meant to use a comparison operator (e.g.
ReferenceError: invalid assignment left-hand side - JavaScript
for example, a single "=" sign was used instead of "==" or "===".
...this might be due to a mismatch of a assignment operator and a comparison operator, for example.
... examples typical invalid assignments if (math.pi = 3 || math.pi = 4) { console.log('no way!'); } // referenceerror: invalid assignment left-hand side var str = 'hello, ' += 'is it me ' += 'you\'re looking for?'; // referenceerror: invalid assignment left-hand side in the if statement, you want to use a comparison operator ("=="), and for the string concatenation, the plus ("+") operator is needed.
URIError: malformed URI sequence - JavaScript
examples encoding encoding replaces each instance of certain characters by one, two, three, or four escape sequences representing the utf-8 encoding of the character.
... an urierror will be thrown if there is an attempt to encode a surrogate which is not part of a high-low pair, for example: encodeuri('\ud800'); // "urierror: malformed uri sequence" encodeuri('\udfff'); // "urierror: malformed uri sequence" a high-low pair is ok.
... for example: encodeuri('\ud800\udfff'); // "%f0%90%8f%bf" decoding decoding replaces each escape sequence in the encoded uri component with the character that it represents.
Method definitions - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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.
setter - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... ( { 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.concat() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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.lo...
Array.prototype.copyWithin() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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.flat() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...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.from() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...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(mapp...
Array.prototype.indexOf() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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.keys() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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.pop() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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.some() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...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.splice() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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 re...
ArrayBuffer() constructor - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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.compareExchange() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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.store() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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.
BigInt.asIntN() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... examples staying in 64-bit ranges the bigint.asuintn() method can be useful to stay in the range of 64-bit arithmetic.
BigInt.prototype.valueOf() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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.
Boolean - JavaScript
for example, the condition in the following if statement evaluates to true: var x = new boolean(false); if (x) { // this code is executed } this behavior does not apply to boolean primitives.
... for example, the condition in the following if statement evaluates to false: var x = false; if (x) { // this code is not executed } do not use a boolean object to convert a non-boolean value to a boolean value.
... 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 = ...
DataView.prototype.buffer - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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.prototype.getDate() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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.getHours() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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.getSeconds() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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.getUTCDay() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... examples using getutcday() the following example assigns the weekday portion of the current date to the variable weekday.
Date.prototype.getUTCHours() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... examples using getutchours() the following example assigns the hours portion of the current time to the variable hours.
Date.prototype.getUTCMonth() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... examples using getutcmonth() the following example assigns the month portion of the current date to the variable month.
Date.prototype.setMonth() - JavaScript
for example, if you use 15 for monthvalue, the year will be incremented by 1, and 3 will be used for month.
...for example, if the current value is 31st august 2016, calling setmonth with a value of 1 will return 2nd march 2016.
... examples using setmonth() var thebigday = new date(); thebigday.setmonth(6); //watch out for end of month transitions var endofmonth = new date(2016, 7, 31); endofmonth.setmonth(1); console.log(endofmonth); //wed mar 02 2016 00:00:00 specifications specification ecmascript (ecma-262)the definition of 'date.prototype.setmonth' in that specification.
Date.prototype.setTime() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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.toDateString() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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.toString() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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 specificatio...
Date.prototype.toTimeString() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
based on rfc7231 and modified according to ecma-262 toutcstring, it can have negative values in the 2021 version the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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.
Function.length - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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.prototype.toString() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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) ...
Generator.prototype.next() - JavaScript
for example, in variable = yield expression, the value passed to the .next() function will be assigned to variable.
... 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: undefi...
...nerator { } page.next(); // object {value: (3) [1, 2, 3], done: false} page.next(); // object {value: (3) [4, 5, 6], done: false} page.next(); // object {value: (2) [7, 8], done: false} page.next(); // object {value: undefined, done: true} sending values to the generator in this example, next is called with a value.
Infinity - JavaScript
property attributes of infinity writable no enumerable no configurable no the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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 'infin...
Intl.Collator.prototype.compare() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... examples using compare for array sort use the compare getter function for sorting arrays.
Intl.Collator.prototype.resolvedOptions() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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.prototype.formatRange() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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 speci...
Intl.DateTimeFormat.supportedLocalesOf() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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.DisplayNames() constructor - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... "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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... examples using format the following example shows how to create a list formatter using the english language.
Intl.Locale.prototype.toString() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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 usedopti...
Intl.NumberFormat.supportedLocalesOf() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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.RelativeTimeFormat.prototype.format() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... examples basic format usage the following example shows how to create a relative time formatter using the english language.
Intl.RelativeTimeFormat.prototype.formatToParts() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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.getCanonicalLocales() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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.
Map.prototype[@@iterator]() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... examples using delete() var mymap = new map(); mymap.set('bar', 'foo'); mymap.delete('bar'); // returns true.
Map.prototype.entries() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
math.e=e≈2.718\mathtt{\mi{math.e}} = e \approx 2.718 the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the math.ln10 property represents the natural logarithm of 10, approximately 2.302: math.ln10=ln(10)≈2.302\mathtt{\mi{math.ln10}} = \ln(10) \approx 2.302 the source for this interactive example is stored in a github repository.
... if you'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
the math.ln2 property represents the natural logarithm of 2, approximately 0.693: math.ln2=ln(2)≈0.693\mathtt{\mi{math.ln2}} = \ln(2) \approx 0.693 the source for this interactive example is stored in a github repository.
... if you'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
the math.log10e property represents the base 10 logarithm of e, approximately 0.434: math.log10e=log10(e)≈0.434\mathtt{\mi{math.log10e}} = \log_10(e) \approx 0.434 the source for this interactive example is stored in a github repository.
... if you'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
the math.log2e property represents the base 2 logarithm of e, approximately 1.442: math.log2e=log2(e)≈1.442\mathtt{\mi{math.log2e}} = \log_2(e) \approx 1.442 the source for this interactive example is stored in a github repository.
... if you'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
the math.pi property represents the ratio of the circumference of a circle to its diameter, approximately 3.14159: math.pi=π≈3.14159\mathtt{\mi{math.pi}} = \pi \approx 3.14159 the source for this interactive example is stored in a github repository.
... if you'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
the math.sqrt1_2 property represents the square root of 1/2 which is approximately 0.707: math.sqrt1_2=12=12≈0.707\mathtt{\mi{math.sqrt1_2}} = \sqrt{\frac{1}{2}} = \frac{1}{\sqrt{2}} \approx 0.707 the source for this interactive example is stored in a github repository.
... if you'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
the math.sqrt2 property represents the square root of 2, approximately 1.414: math.sqrt2=2≈1.414\mathtt{\mi{math.sqrt2}} = \sqrt{2} \approx 1.414 the source for this interactive example is stored in a github repository.
... if you'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
the math.abs() function returns the absolute value of a number, that is math.abs(x)=|x|={xifx>00ifx=0-xifx<0{\mathtt{\operatorname{math.abs}(z)}} = {|z|} = \begin{cases} x & \text{if} \quad x \geq 0 \\ x & \text{if} \quad x < 0 \end{cases} the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the math.acos() function returns the arccosine (in radians) of a number, that is ∀x∊[-1;1],math.acos(x)=arccos(x)= the unique y∊[0;π]such thatcos(y)=x\forall x \in [{-1};1],\;\mathtt{\operatorname{math.acos}(x)} = \arccos(x) = \text{ the unique } \; y \in [0; \pi] \, \text{such that} \; \cos(y) = x the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the math.acosh() function returns the hyperbolic arc-cosine of a number, that is ∀x≥1,math.acosh(x)=arcosh(x)= the unique y≥0such thatcosh(y)=x\forall x \geq 1, \mathtt{\operatorname{math.acosh}(x)} = \operatorname{arcosh}(x) = \text{ the unique } \; y \geq 0 \; \text{such that} \; \cosh(y) = x the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the math.asin() function returns the arcsine (in radians) of a number, that is ∀x∊[-1;1],math.asin(x)=arcsin(x)= the unique y∊[-π2;π2]such thatsin(y)=x\forall x \in [{-1};1],\;\mathtt{\operatorname{math.asin}(x)} = \arcsin(x) = \text{ the unique } \; y \in \left[-\frac{\pi}{2}; \frac{\pi}{2}\right] \, \text{such that} \; \sin(y) = x the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the math.asinh() function returns the hyperbolic arcsine of a number, that is math.asinh(x)=arsinh(x)= the unique ysuch thatsinh(y)=x\mathtt{\operatorname{math.asinh}(x)} = \operatorname{arsinh}(x) = \text{ the unique } \; y \; \text{such that} \; \sinh(y) = x the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the math.atan() function returns the arctangent (in radians) of a number, that is math.atan(x)=arctan(x)= the unique y∊[-π2;π2]such thattan(y)=x\mathtt{\operatorname{math.atan}(x)} = \arctan(x) = \text{ the unique } \; y \in \left[-\frac{\pi}{2}; \frac{\pi}{2}\right] \, \text{such that} \; \tan(y) = x the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... examples using math.atan2() math.atan2(90, 15); // 1.4056476493802699 math.atan2(15, 90); // 0.16514867741462683 math.atan2(±0, -0); // ±pi.
Math.atanh() - JavaScript
the math.atanh() function returns the hyperbolic arctangent of a number, that is ∀x∊(-1,1),math.atanh(x)=arctanh(x)= the unique ysuch thattanh(y)=x\forall x \in \left( -1, 1 \right), \mathtt{\operatorname{math.atanh}(x)} = \operatorname{arctanh}(x) = \text{ the unique } \; y \; \text{such that} \; \tanh(y) = x the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the math.cbrt() function returns the cube root of a number, that is math.cbrt(x)=x3=the uniqueysuch thaty3=x\mathtt{math.cbrt(x)} = \sqrt[3]{x} = \text{the unique} \; y \; \text{such that} \; y^3 = x the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...-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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... examples using math.ceil() the following example shows example usage of math.ceil().
Math.clz32() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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 definiti...
Math.cos() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the math.cosh() function returns the hyperbolic cosine of a number, that can be expressed using the constant e: math.cosh(x)=ex+e-x2\mathtt{\operatorname{math.cosh(x)}} = \frac{e^x + e^{-x}}{2} the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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.imul() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...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.log10() - JavaScript
the math.log10() function returns the base 10 logarithm of a number, that is ∀x>0,math.log10(x)=log10(x)=the uniqueysuch that10y=x\forall x > 0, \mathtt{\operatorname{math.log10}(x)} = \log_10(x) = \text{the unique} \; y \; \text{such that} \; 10^y = x the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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 definit...
Math.log1p() - JavaScript
the math.log1p() function returns the natural logarithm (base e) of 1 + a number, that is ∀x>-1,math.log1p(x)=ln(1+x)\forall x > -1, \mathtt{\operatorname{math.log1p}(x)} = \ln(1 + x) the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...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
the math.log2() function returns the base 2 logarithm of a number, that is ∀x>0,math.log2(x)=log2(x)=the uniqueysuch that2y=x\forall x > 0, \mathtt{\operatorname{math.log2}(x)} = \log_2(x) = \text{the unique} \; y \; \text{such that} \; 2^y = x the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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 th...
Math.min() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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/...
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.
... getting a random number between 0 (inclusive) and 1 (exclusive) function getrandom() { return math.random(); } getting a random number between two values this example returns a random number between the specified values.
... function getrandomarbitrary(min, max) { return math.random() * (max - min) + min; } getting a random integer between two values this example returns a random integer between the specified values.
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.
... getting a random number between 0 (inclusive) and 1 (exclusive) function getrandom() { return math.random(); } getting a random number between two values this example returns a random number between the specified values.
... function getrandomarbitrary(min, max) { return math.random() * (max - min) + min; } getting a random integer between two values this example returns a random integer between the specified values.
Math.round() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the math.sinh() function returns the hyperbolic sine of a number, that can be expressed using the constant e: math.sinh(x)=ex-e-x2\mathtt{\operatorname{math.sinh(x)}} = \frac{e^x - e^{-x}}{2} the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the math.sqrt() function returns the square root of a number, that is ∀x≥0,math.sqrt(x)=x=the uniquey≥0such thaty2=x\forall x \geq 0, \mathtt{math.sqrt(x)} = \sqrt{x} = \text{the unique} \; y \geq 0 \; \text{such that} \; y^2 = x the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...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
property attributes of nan writable no enumerable no configurable no the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
..."foo"/3) examples testing against nan nan compares unequal (via ==, !=, ===, and !==) to any other value -- including to another nan value.
Number.EPSILON - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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_VALUE - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... examples using max_value the following code multiplies two numeric values.
Number.MIN_SAFE_INTEGER - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... examples using min_value the following code divides two numeric values.
Number.NEGATIVE_INFINITY - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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.prototype.toExponential() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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 d...
Number.prototype.toFixed() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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.valueOf() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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.
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 fo...
...r number the following example shows the minimum and maximum integer values that can be represented as number object.
... using number to convert a date object the following example converts the date object to a numerical value using number as a function: let d = new date('december 17, 1995 03:24:00') console.log(number(d)) this logs 819199440000.
Object.defineProperties() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...(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.entries() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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.fromEntries() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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 = obje...
Object.getOwnPropertyDescriptor() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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, // writ...
Object.getOwnPropertySymbols() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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 ec...
Object.getPrototypeOf() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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.isExtensible() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... examples using object.isextensible // new objects are extensible.
Object.isFrozen() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... examples using object.isfrozen // a new object is extensible, so it is not frozen.
Object.isSealed() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... examples using object.issealed // objects aren't sealed by default.
Object.keys() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... examples using object.preventextensions // object.preventextensions returns the object // being made non-extensible.
Object.seal() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... examples using object.seal var obj = { prop: function() {}, foo: 'bar' }; // new properties may be added, existing properties // may be changed or removed.
Object.setPrototypeOf() - JavaScript
o1st !== object.prototype && o1st !== function.prototype; o1st = this.getprototypeof(o2nd) ) { o2nd = o1st; } if (oproto.constructor === string) { onewproto = function.prototype; oreturn = function.apply(null, array.prototype.slice.call(arguments, 1)); this.setprototypeof(oreturn, olast); } this.setprototypeof(o2nd, onewproto); return oreturn; } usage first example: appending a chain to a prototype function mammal() { this.ismammal = 'yes'; } function mammalspecies(smammalspecies) { this.species = smammalspecies; } mammalspecies.prototype = new mammal(); mammalspecies.prototype.constructor = mammalspecies; var ocat = new mammalspecies('felis'); console.log(ocat.ismammal); // 'yes' function animal() { this.breathing = 'yes'; } object.appendchain...
...(ocat, new animal()); console.log(ocat.breathing); // 'yes' second example: transforming a primitive value into an instance of its constructor and append its chain to a prototype function mysymbol() { this.issymbol = 'yes'; } var nprime = 17; console.log(typeof nprime); // 'number' var oprime = object.appendchain(nprime, new mysymbol()); console.log(oprime); // '17' console.log(oprime.issymbol); // 'yes' console.log(typeof oprime); // 'object' third example: appending a chain to the function.prototype object and appending a new function to that chain function person(sname) { this.identity = sname; } var george = object.appendchain(new person('george'), 'console.log("hello guys!!");'); console.log(george.identity); // 'george' george(); // 'hello gu...
... 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
for example: function person(name) { this.name = name; } person.prototype.tosource = function person_tosource() { return 'new person(' + uneval(this.name) + ')'; }; console.log(new person('joe').tosource()); // ---> new person("joe") built-in tosource() methods each core javascript type has its own tosource() method.
...for example: var obj1 = {}; var obj2 = { a: obj1 }; obj1.b = obj2; console.log('cyclical: ' + (obj1.b.a == obj1)); var objsource = obj1.tosource(); // returns "({b:{a:{}}})" obj1 = eval(objsource); console.log('cyclical: ' + (obj1.b.a == obj1)); if a cyclical structure is employed and tosource() is needed, the object must provide an override to tosource(), either using a reference to a constructor or ...
... 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.tosource(); // returns ({name:"gabby", breed:"lab", color:"chocolate", sex:"female"}) specifications not part of any standard.
Object.prototype.valueOf() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
(the only difference is that a for...in loop enumerates properties in the prototype chain as well.) the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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.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(() =>...
Promise.reject() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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.
handler.apply() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... examples trapping a function call the following code traps a function call.
handler.construct() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... examples trapping the new operator the following code traps the new operator.
handler.defineProperty() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... examples trapping of defineproperty the following code traps object.defineproperty().
handler.deleteProperty() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... examples trapping the delete operator the following code traps the delete operator.
handler.get() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... examples trap for getting a property value the following code traps getting a property value.
handler.getOwnPropertyDescriptor() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... examples trapping of getownpropertydescriptor the following code traps object.getownpropertydescriptor().
handler.getPrototypeOf() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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 prox...
handler.has() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... examples trapping the in operator the following code traps the in operator.
handler.isExtensible() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... examples trapping of isextensible the following code traps object.isextensible().
handler.ownKeys() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... examples trapping of getownpropertynames the following code traps object.getownpropertynames().
handler.preventExtensions() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... examples trapping of preventextensions the following code traps object.preventextensions().
Reflect.apply() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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 sp...
Reflect.defineProperty() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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 ...
Reflect.get() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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.getownpropertydescript...
Reflect.getPrototypeOf() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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-objec...
Reflect.has() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... examples using reflect.isextensible() see also object.isextensible().
Reflect.ownKeys() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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(met...
Reflect.preventExtensions() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... examples using reflect.preventextensions() see also object.preventextensions().
Reflect.set() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... examples using reflect.setprototypeof() reflect.setprototypeof({}, object.prototype) // true // it can change an object's [[prototype]] to null.
get RegExp[@@species] - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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.prototype.flags - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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 'rege...
RegExp.prototype.ignoreCase - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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.source - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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.toString() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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 rege...
Set.prototype[@@iterator]() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... examples using the delete() method const myset = new set(); myset.add('foo'); myset.delete('bar'); // returns false.
Set.prototype.entries() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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 ecmascr...
Set.prototype.has() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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.
SharedArrayBuffer() constructor - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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.
String.prototype[@@iterator]() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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.codePointAt() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...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 defin...
String.prototype.concat() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... examples using concat() the following example combines strings into a new string.
String.prototype.endsWith() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...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.prototype.fontcolor() - JavaScript
for example, the hexadecimal rgb values for salmon are red=fa, green=80, and blue=72, so the rgb triplet for salmon is "fa8072".
... examples using fontcolor() the following example uses the fontcolor() method to change the color of a string by producing a string with the html <font> tag.
...g(worldstring.fontcolor('red') + ' is red in this line'); // '<font color="red">hello, world</font> is red in this line' console.log(worldstring.fontcolor('ff00') + ' is red in hexadecimal in this line'); // '<font color="ff00">hello, world</font> is red in hexadecimal in this line' with the element.style object you can get the element's style attribute and manipulate it more generically, for example: document.getelementbyid('yourelemid').style.color = 'red'; specifications specification ecmascript (ecma-262)the definition of 'string.prototype.fontcolor' in that specification.
String.fromCodePoint() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...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.lastIndexOf() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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.matchAll() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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=...
String.prototype.padEnd() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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().pa...
String.prototype.repeat() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...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.search() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... examples using search() the following example searches a string with two different regex objects to show a successful search (positive value) vs.
String.prototype.startsWith() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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 's...
String.prototype.toLocaleUpperCase() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...the 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.tolocaleu...
String.prototype.toLowerCase() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... examples using tolowercase() console.log('alphabet'.tolowercase()); // 'alphabet' specifications specification ecmascript (ecma-262)the definition of 'string.prototype.tolowercase' in that specification.
String.prototype.trim() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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.
String - JavaScript
for example: let s1 = '2 + 2' // creates a string primitive let s2 = new string('2 + 2') // creates a string object console.log(eval(s1)) // returns the number 4 console.log(eval(s2)) // returns the string "2 + 2" for these reasons, the code may break when it encounters string objects when it expects a primitive string instead, although generally, authors need not worry about...
...() <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.
... for example: let outputstrings = [] for (let i = 0, n = inputvalues.length; i < n; ++i) { outputstrings.push(string(inputvalues[i])); } specifications specification ecmascript (ecma-262)the definition of 'string' in that specification.
Symbol.asyncIterator - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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 yo...
Symbol.hasInstance - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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.iterator - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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.replace - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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.split - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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.unscopables - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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.
Symbol - JavaScript
creates a new symbol each time: symbol('foo') === symbol('foo') // false the following syntax with the new operator will throw a typeerror: let sym = new symbol() // typeerror this prevents authors from creating an explicit symbol wrapper object instead of a new symbol value and might be surprising as creating explicit wrapper objects around primitive data types is generally possible (for example, new boolean, new string and new number).
... examples using the typeof operator with symbols the typeof operator can help you to identify symbols.
...this prevents you from silently creating a new string property name from a symbol, for example.
TypedArray.BYTES_PER_ELEMENT - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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) speci...
TypedArray.prototype.copyWithin() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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 specific...
TypedArray.prototype.entries() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... // 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...; 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...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.f...
TypedArray.prototype.includes() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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 speci...
TypedArray.prototype.indexOf() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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 spec...
TypedArray.prototype.map() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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" specificatio...
TypedArray.of() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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.some() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... examples using sort for more examples, see also the array.prototype.sort() method.
TypedArray.prototype.subarray() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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 specific...
TypedArray.prototype.values() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... examples new is required starting with ecmascript 2015, typedarray constructors must be constructed with the new operator.
WeakMap.prototype.delete() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... examples using the delete method var wm = new weakmap(); wm.set(window, 'foo'); wm.delete(window); // returns true.
WeakMap.prototype.get() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... examples using the get method var wm = new weakmap(); wm.set(window, 'foo'); wm.get(window); // returns "foo".
WeakMap.prototype.has() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... examples using the delete method var ws = new weakset(); var obj = {}; ws.add(window); ws.delete(obj); // returns false.
WeakSet.prototype.has() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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.
WebAssembly.Memory() constructor - JavaScript
examples creating a new memory instance there are two ways to get a webassembly.memory object.
...the following example creates a new webassembly memory instance with an initial size of 10 pages (640kib), and a maximum size of 100 pages (6.4mib).
...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.Memory - JavaScript
examples creating a new memory object there are two ways to get a webassembly.memory object.
...the following example creates a new webassembly memory instance with an initial size of 10 pages (640kib), and a maximum size of 100 pages (6.4mib).
... 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.customSections() - JavaScript
(read high level structure for information on section structures, and how normal sections ("known sections") and custom sections are distinguished.) this provides developers with a way to include custom data inside wasm modules for other purposes, for example the name custom section, which allows developers to provide names for all the functions and locals in the module (like "symbols" in a native build).
...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.
...since there is a "name" section in the example, an arraybuffer object is returned.
decodeURI() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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 defin...
decodeURIComponent() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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.
isFinite() - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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 // m...
null - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...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
property attributes of undefined writable no enumerable no configurable no the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... // 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
chaining the assignment operator is possible in order to assign a single value to multiple variables the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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 assignment (&=) - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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 OR assignment (|=) - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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 assignment (^=) - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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.
Division (/) - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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.
Exponentiation assignment (**=) - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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); // tr...
Grouping operator ( ) - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... examples using the grouping operator overriding multiplication and division first, then addition and subtraction to evaluate addition first.
Inequality (!=) - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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 ope...
Left shift assignment (<<=) - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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" < ...
Less than or equal (<=) - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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); // t...
Logical AND assignment (&&=) - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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.
Remainder (%) - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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 assignment (>>=) - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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.
Strict equality (===) - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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 consol...
Strict inequality (!==) - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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 conso...
Subtraction (-) - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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 assignment (>>>=) - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... '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.
function* expression - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... examples using function* the following example defines an unnamed generator function and assigns it to x.
Function expression - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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.
typeof - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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 ...
yield* - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... examples using yield the following code is the declaration of an example generator function.
class - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... examples basic const usage constants can be declared with uppercase or lowercase, but a common convention is to use all-uppercase letters.
do...while - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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.
export - JavaScript
but a default export can be imported with any name for example: // file test.js let k; export default k = 12; // some other file import m from './test'; // note that we have the freedom to use import m instead of import k, because k was default export console.log(m); // will log 12 you can also rename named exports to avoid naming conflicts: export { myfunction as function1, myvariable as variable }; re-exporting / aggregating it is ...
... 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 ...
...using the default export if we want to export a single value or to have a fallback value for your module, you could use a default export: // module "my-module.js" export default function cube(x) { return x * x * x; } then, in another script, it is straightforward to import the default export: import cube from './my-module.js'; console.log(cube(3)); // 27 using export from let's take an example where we have the following hierarchy: childmodule1.js: exporting myfunction and myvariable childmodule2.js: exporting myclass parentmodule.js: acting as an aggregator (and doing nothing else) top level module: consuming the exports of parentmodule.js this is what it would look like using code snippets: // in childmodule1.js let myfunction = ...; // assign something useful to myfunction ...
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 ...
... async function* asyncgenerator() { let i = 0; while (i < 3) { yield i++; } } (async function() { for await (let num of asyncgenerator()) { console.log(num); } })(); // 0 // 1 // 2 for a more concrete example of iterating over an async generator using for await...of, consider iterating over data from an api.
... this example first creates an async iterable for a stream of data, then uses it to find the size of the response from the api.
for...in - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... 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.
function declaration - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
...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.
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.
... for example, with the following html: <script type="module"> import './index.mjs?someurlinfo=5'; </script> ..the following javascript file will log the `someurlinfo parameter: // index.mjs new url(import.meta.url).searchparams.get('someurlinfo'); // 5 the same applies when a file imports another: // index.mjs import './index2.mjs?someurlinfo=5'; // index2.mjs new url(import.meta.url).searchparams.get('...
...someurlinfo'); // 5 note that while node.js will pass on query parameters (or the hash) as in the latter example, as of node 14.1.0, a url with query parameters will err when loading in the form node --experimental-modules index.mjs?someurlinfo=5 (it is treated as a file rather than a url in this context).
while - JavaScript
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
... examples using while the following while loop iterates as long as n is less than three.
Strict mode - JavaScript
for example, nan is a non-writable global variable.
...still, this hiding makes little sense and is probably undesirable (it might hide a typo, for example), so in strict mode duplicate argument names are a syntax error: function sum(a, a, c) { // !!!
... two mozilla-specific caveats: first, if your code is javascript 1.7 or greater (for example in chrome code or when using the right <script type="">) and is strict mode code, let and yield have the functionality they've had since those keywords were first introduced.
icons - Web app manifests
for example, they can be used to represent the web application amongst a list of other applications, or to integrate the web application with an os's task switcher and/or system preferences.
... 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 containing space-separated image dimensions.
... purpose defines the purpose of the image, for example if the image is intended to serve some special purpose in the context of the host os (i.e., for better integration).
<mmultiscripts> - MathML
for example, a number is a 0-dimensional array, or a 0th-order tensor.
...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 --> </mmultiscrip...
<mn> - MathML
WebMathMLElementmn
however, it is also allowed to have arbitrary text in it which is actually a numeric quantity, for example "eleven".
...the following values are allowed: normal (default value) ; example bold ; example 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.
Codecs used by WebRTC - Web media technologies
opus, for example, has its own cn capability; as such, using rfc 3389 cn with the opus codec is not recommended.
...for example, to determine the supported codecs for video, you can do this: codeclist = rtcrtpsender.getcapabilities("video").codecs; now codeclist is an array of rtcrtpcodeccapability objects, each describing one codec configuration.
... for example, safari for ios and ipados introduced webrtc with avc as the only supported video codec.
Privacy, permissions, and information security
for example, if a site leaks a list of users' names and zip codes online, a bad actor could almost certainly track down at least some percentage of those users by simply using the corresponding phone books.
... for example, if a web site queries a user's browser for the elapsed time, a comparison of that time to the time as reported by the server might be useful as a factor in fingerprinting.
...for example, in firefox 73, the user permission requests were revised so that when an <iframe> uses the allow keyword to delegate permission to the embeded document, the browser asks the user to grant the parent document permission to use the resource, and that permission is then shared with the embedded content that requested the resource to begin with.
Installing and uninstalling web apps - Progressive web apps (PWAs)
depending on the device and features of the operating system and browser, this can result in what is essentially a fully featured application (for example, using webapk on android) or as a shortcut added to their device’s screen.
... the install user experience we've written a very simple example web site (see our demo live, and also see the source code) that doesn't do much, but was developed with the necessary code to allow it to be installed, as well as a service worker to enable it to be used offline.
... the example displays a series of fox pictures.if you have a web application compatible device available, use it to navigate to our demo at https://mdn.github.io/pwa-examples/a2hs/.
How to make PWAs installable - Progressive web apps (PWAs)
previous overview: progressive next in the last article, we read about how the example application, js13kpwa, works offline thanks to its service worker, but we can go even further and allow users to install the web app on mobile and desktop browers that support doing so.
... { "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.
...in the screen shot above, for example, the app has a tiny firefox icon, indicating that it's a web app that uses the firefox runtime.
stroke-linecap - SVG: Scalable Vector Graphics
example html,body,svg { height:100% } <svg viewbox="0 0 6 4" xmlns="http://www.w3.org/2000/svg"> <!-- effect of the "butt" value --> <path d="m1,1 h4" stroke="black" stroke-linecap="butt" /> <!-- effect of the "butt" value on a zero length path --> <path d="m3,3 h0" stroke="black" stroke-linecap="butt" /> <!-- the following pink lines highlight the position of the ...
... example html,body,svg { height:100% } <svg viewbox="0 0 6 4" xmlns="http://www.w3.org/2000/svg"> <!-- effect of the "round" value --> <path d="m1,1 h4" stroke="black" stroke-linecap="round" /> <!-- effect of the "round" value on a zero length path --> <path d="m3,3 h0" stroke="black" stroke-linecap="round" /> <!-- the following pink lines highlight the position of ...
... example html,body,svg { height:100% } <svg viewbox="0 0 6 4" xmlns="http://www.w3.org/2000/svg"> <!-- effect of the "square" value --> <path d="m1,1 h4" stroke="black" stroke-linecap="square" /> <!-- effect of the "square" value on a zero length path --> <path d="m3,3 h0" stroke="black" stroke-linecap="square" /> <!-- the following pink lines highlight the position...
<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 c...
...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="#bluetrian...
...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.
Fills and Strokes - SVG: Scalable Vector Graphics
in the example above, the path is shown in pink, and the stroke in black.
...so in the above example, the second path fills 5 pixel units, with 5 blank units until the next dash of 5 units.
...the first example specifies three numbers, in which case the renderer loops the numbers twice to create an even pattern.
Filter effects - SVG: Scalable Vector Graphics
drop shadows, to provide a popular example, cannot be created reasonably with a combination of gradients.
... a basic example is to add a blur effect to svg content.
... example filters are defined by <filter> element, which should be put in the <defs> section of your svg file.
Patterns - SVG: Scalable Vector Graphics
WebSVGTutorialPatterns
in the example above, we've defined a width and height attribute on the pattern element to describe how far the pattern should go before it begins repeating itself again.
... to make this work in the example above, we had to consider the size of our box (200 pixels) and the fact that we wanted the pattern to repeat itself 4 times horizontally and vertically.
...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.
Referer header: privacy and security concerns - Web security
for example, consider a "reset password" page with a social media link in a footer.
...this can for example be set to no-referrer to stop the referer header being sent altogether.
... security-conscious server-side frameworks tend to have built in mitigations for such problems, for example: security in django (especially see cross site request forgery (csrf) protection).
Tutorials
also includes a step-by-step guide to creating a basic web page with code examples.
... html challenges use these challenges to hone your html skills (for example, "should i use an <h2> element or a <strong> element?"), focusing on meaningful markup.
... css first steps css (cascading style sheets) is used to style and lay out web pages — for example, to alter the font, color, size, and spacing of your content, split it into multiple columns, or add animations and other decorative features.
JavaScript/XSLT Bindings - XSLT: Extensible Stylesheet Language Transformations
figure 1 : instantiating an xsltprocessor var xsltprocessor = new xsltprocessor(); // load the xsl file using synchronous (third param is set to false) xmlhttprequest var myxmlhttprequest = new xmlhttprequest(); myxmlhttprequest.open("get", "example.xsl", false); myxmlhttprequest.send(null); var xslref = myxmlhttprequest.responsexml; // finally import the .xsl xsltprocessor.importstylesheet(xslref); for the actual transformation, xsltprocessor requires an xml document, which is used in conjunction with the imported xsl file to produce the final result.
...assuming that the dom to be processed is contained by an element with the id example, that dom can be "cloned" using the in-memory xml document's document.importnode() method.
... // importnode is used to clone the nodes we want to process via xslt - true makes it do a deep clone var mynode = document.getelementbyid("example"); var clonednode = xmlref.importnode(mynode, true); // add the cloned dom into the xml document xmlref.appendchild(clonednode); once the stylesheet has been imported, xsltprocessor has to perform two methods for the actual transformation, namely xsltprocessor.transformtodocument() and xsltprocessor.transformtofragment().
Caching compiled WebAssembly modules - WebAssembly
if opening the database failed (for example due to permissions or quota), we fall back to simply fetching and compiling the module and don't try to store the results (since there is no database to store them into).
... const wasmcacheversion = 1; instantiatecachedurl(wasmcacheversion, 'test.wasm').then(instance => console.log("instance says the answer is: " + instance.exports.answer()) ).catch(err => console.error("failure to instantiate: " + err) ); you can find the source code for this example on github as indexeddb-cache.html (see it live also).
... chrome has support implemented behind the webassembly structured cloning support flag, but is yet to turn it on by default because of some concerns (see this discussion, for example).
Converting WebAssembly text format to wasm - WebAssembly
a first look at the text format let’s look at a simple example of this — the following program imports a function called imported_func from a module called imports, and exports a function called exported_func: (module (func $i (import "imports" "imported_func") (param i32)) (func (export "exported_func") i32.const 42 call $i ) ) the webassembly function exported_func is exported for use in our environment (e.g.
... converting the text .wat into a binary .wasm file let’s have a go at converting the above .wat text representation example into .wasm assembly format.
... note: you can also convert the assembly back into the text representation using the wasm2wat tool; for example wasm2wat simple.wasm -o text.wat.
Compiling an Existing C Module to WebAssembly - WebAssembly
as an example, let's compile an encoder for webp to wasm.
...for example, v0.6.1 is encoded as 0x000601 = 1537.
...because functions in c can't have arrays as return types (unless you allocate memory dynamically), this example resorts to a static global array.
Private Properties - Archive of obsolete content
consider the following example: function point(x, y) { this._x = x; this._y = y; } the properties _x and _y are intended to be private, and should only be accessed by member functions.
...using namespaces, the earlier example can be rewritten as: let map = new weakmap(); let internal = function (object) { if (!map.has(object)) map.set(object, {}); return map.get(object); } function point(x, y) { internal(this).x = x; internal(this).y = y; } point.prototype.getx = function () { return internal(this).x; }; point.prototype.setx = function (x) { internal(this).x = x; }; point.prototyp...
clipboard - Archive of obsolete content
examples set and get the contents of the clipboard.
...for example, html data might be available as both a string of html (the html type) and a string of plain text (the text type).
hotkeys - Archive of obsolete content
for example, this add-on defines two hotkey combinations, to show and hide a panel: // define keyboard shortcuts for showing and hiding a custom panel.
...for example, accel-s is typically used to save a file, but if you use it for something completely different, then it would be extremely confusing for users.
indexed-db - Archive of obsolete content
for example: window.indexeddb = window.indexeddb || window.webkitindexeddb || window.mozindexeddb || window.msindexeddb; var request = window.indexeddb.open("mydatabase"); request.onerror = function(event) { console.log("failure"); }; request.onsuccess = function(event) { console.log("success"); }; because your main add-on code can't access the dom, you can't do this.
... example this example uses the action button api, which is only available from firefox 29 onwards.
private-browsing - Archive of obsolete content
for example, here's an add-on that stores the titles of tabs the user loads, and uses isprivate() to exclude the titles of tabs that were loaded into private windows: var simplestorage = require("simple-storage"); if (!simplestorage.storage.titles) simplestorage.storage.titles = []; require("tabs").on("ready", function(tab) { if (!require("sdk/private-browsing").isprivate(tab)) { console.log("stor...
...for example, the "downloads" window might want to display all downloads while there are still some private windows open, then clean out all the private data when all private windows have closed.
io/file - Archive of obsolete content
for example, to specify the file at c:\users\myk, you need to use the string "c:\\users\\myk", not "c:\users\myk".
...for example, basename("/foo/bar/baz") returns "baz".
lang/functional - Archive of obsolete content
in this example, we'll fabricate a function // that takes a string of first and last names that // somehow computes the lineage of that name.
...this could be useful, for example, if we are checking the user's keyboard input, and want to wait until they've paused in their typing before we do so.
remote/child - Archive of obsolete content
events attach triggered when a new content frame is opened (for example, the user opened a new tab).
... at this point you can't access frame's content yet, but you can add event listeners: const { frames } = require("sdk/remote/child"); frames.on("attach", function(frame) { console.log("new frame"); frame.addeventlistener("domcontentloaded", function(e) { console.log(e.target.location.href); }); }); detach triggered when a frame is removed (for example, the user closed a tab).
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 (...
...); var proc = spawn("/bin/cat"); emit(proc.stdin, 'data', "hello from add-on code"); emit(proc.stdin, 'end'); using child_process in non-jpm extensions // import sdk stuff const commonjs_uri = 'resource://gre/modules/commonjs'; const { require } = cu.import(commonjs_uri + '/toolkit/require.js', {}); var child_process = require('sdk/system/child_process'); // use it in the same way as in the example above ...
system/runtime - Archive of obsolete content
for example, .
...this string takes the form <processor>-<compilerabi>, for example: "x86-msvc" or "ppc-gcc3".
system/xul-app - Archive of obsolete content
for example, for firefox this value is "{ec8030f7-c20a-464f-9b0e-13a3a9e97384}".
...for example, ids["firefox"] == "{ec8030f7-c20a-464f-9b0e-13a3a9e97384}".
test/assert - Archive of obsolete content
for example: var a = 1; exports["test value of a"] = function(assert) { assert.ok(a == 1, "test that a is 1"); } require("sdk/test").run(exports); globals constructors assert(logger) create a new assert object.
... to check that the exception thrown contains a specific message, pass a regular expression here: the message property of the exception thrown must match the regular expression for example, suppose we define two different custom exceptions: function myerror(message) { this.name = "myerror"; this.message = message || "default message"; } myerror.prototype = new error(); myerror.prototype.constructor = myerror; function anothererror(message) { this.name = "anothererror"; this.message = message || "default message"; console.log(this.message); } anothererror.prototype =...
cfx to jpm - Archive of obsolete content
for example: addons.mozilla.org uses it to distinguish between new add-ons and updates to existing add-ons, and the simple-storage module uses it to figure out which stored data belongs to which add-on.
... entry point the add-on's entry point is the file that's executed when the add-on needs to initialize itself: for example, when firefox starts, or when the add-on's installed, enabled, or upgraded.
jpmignore - Archive of obsolete content
here is an example: # ignore .ds_store files created by mac .ds_store # ignore any zip or xpi files *.zip *.xpi # ignore specific directory # you can start patterns with a forward slash (/) to avoid recursivity.
...for example: .* * !/data/** !/lib/** !/locale/** !/node_modules/** !/package.json !/icon.png !/icon64.png !/copying !/bootstrap.js !/install.rdf this would include all editor backup files and similar in the whitelisted subdirectories, to avoid that you can append another blacklist after the whitelist.
Creating Reusable Modules - Archive of obsolete content
the documentation for that interface includes an example which we can adapt like this: var {cc, ci} = require("chrome"); function promptforfile() { const nsifilepicker = ci.nsifilepicker; var fp = cc["@mozilla.org/filepicker;1"] .createinstance(nsifilepicker); var window = require("sdk/window/utils").getmostrecentbrowserwindow(); fp.init(window, "select a file", nsifilepicker.modeopen); fp.appendfilters(nsifilepicker.filterall ...
... } return path; } hash function firefox has built-in support for hash functions, exposed via the nsicryptohash xpcom interface the documentation page for that interface includes an example of calculating an md5 hash of a file's contents, given its path.
Getting Started (jpm) - Archive of obsolete content
for example, in ubuntu: jpm run -b /usr/bin/firefox when firefox launches, in the top-right corner of the browser you'll see an icon with the firefox logo.
...for example, we could change the page that gets loaded: var buttons = require('sdk/ui/button/action'); var tabs = require("sdk/tabs"); var button = buttons.actionbutton({ id: "mozilla-link", label: "visit mozilla", icon: { "16": "./icon-16.png", "32": "./icon-32.png", "64": "./icon-64.png" }, onclick: handleclick }); function handleclick(state) { tabs.open("https://developer.mozill...
Add-on SDK - Archive of obsolete content
putting it together walkthrough of the annotator example add-on.
...this guide includes a comparison of the two toolsets and a working example of porting a xul add-on.
Cookies - Archive of obsolete content
reading existing cookies cookies for a given host, represented as nsicookie2 objects, can be enumerated as such: let enum = services.cookies.getcookiesfromhost("example.com"); while (enum.hasmoreelements()) { var cookie = enum.getnext().queryinterface(ci.nsicookie2); dump(cookie.host + ";" + cookie.name + "=" + cookie.value + "\n"); } all cookies, regardless of host, can be enumerated using services.cookies.enumerator rather than getcookiesfromhost().
... services.cookies.add(".host.example.com", "/cookie-path", "cookie_name", "cookie_value", is_secure, is_http_only, is_session, expiry_date); see also document.cookie nsicookie nsicookie2 nsicookieservice nsicookiemanager nsicookiemanager2 http cookies ...
HTML in XUL for rich tooltips - Archive of obsolete content
this example demonstrates the dynamic injection of html into a xul element.
...this example is what the final xul overlay could look like, assuming a javascript overlay titled overlay.js: <?xml version="1.0" encoding="utf-8"?> <overlay id="htmltip-overlay" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" xmlns:html="http://www.w3.org/1999/xhtml"> <script type="application/x-javascript" src="overlay.js"/> <popup id="contentareacontextmenu"> <menuitem id="htmltip1" label="foo1" onmouseover="htmltip.onmousetooltip(event)" tooltip="myhtmltip" /> <menuitem id="htmltip2" label="foo2" onmouseover="htmltip.onmousetooltip(event)" tool...
On page load - Archive of obsolete content
if you need finer control over custom code execution—for example, as documents are loading or when tabs are switched—see progress listeners.
...to attach to the unload event in above example you can use the "pagehide" event like this: appcontent.addeventlistener("pagehide", myextension.onpageunload, false); for appcontent and similarly for messagepane messagepane.addeventlistener("pagehide", myextension.onpageunload, false); and add your code to onpageunload method.
JavaScript timers - Archive of obsolete content
this can be useful, for example, if you want to have your worker thread run code periodically instead of nonstop.
... timer.jsm the timer.jsm javascript code module contains pure-javascript implementations of settimeout and cleartimeout that are compatible with the dom window functions, but that can be used by code that does not have access to a dom window (for example, javascript code modules or content frame scripts).
Tree - Archive of obsolete content
s.getcolumnat(cellindex)); alert(celltext); } getting the tree item from the focused row assuming <tree id="my-tree">, you can use the following to get the tree item: var view = document.getelementbyid("my-tree").view; var sel = view.selection.currentindex; //returns -1 if the tree is not focused var treeitem = view.getitematindex(sel); note that the current index may be unselected (for example, a multi-select tree).
...for example, assuming the given <tree>: <tree id="my-tree" onclick="ontreeclicked(event)"> use the following javascript: function ontreeclicked(event){ var tree = document.getelementbyid("my-tree"); var tbo = tree.treeboxobject; // get the row, col and child element at the point var row = { }, col = { }, child = { }; tbo.getcellat(event.clientx, event.clienty, row, col, child); var celltext = tree.view.getcelltext(row.value, col.value); alert(cel...
Appendix E: DOM Building and Insertion (HTML & XUL) - Archive of obsolete content
ull ] ]; var capturednodes = {}; var toolbox = doc.getelementbyid("navigator-toolbox"); var palette = toolbox.palette; var domfragment = jsontodom(jsontemplatebtn, document, capturednodes); palette.appendchild(domfragment); alert("capturednodes contains any created nodes that have optionally been captured (for later convenient javascript access) by giving them a 'key' attribute; for example: " + capturednodes.mytestbutton123); another example this here is another example of using jsontodom but in the html scope, a complex form is created with ease.
... the demo of this is seen at jsfiddle :: jsontodom example var json = ['html:div', {style:'background-color:springgreen'}, ['html:form', {id:'myfirstform'}, ['html:input', {type:'text', value:'my field'}], ['html:button', {id:'mybtn'}, 'button text content'] ], ['html:form', {id:'mysecondform'}, ['html:input', {type:'text', value:'my field for second form'}], ['html:div', {}, 'sub div with textcontent and siblings', ['html:br', {}], ['html:input', {type:'checkbox', id:'mycheck'}], ['html:label', {for:'mycheck'}, 'here is text of label, click this text will check the box' ] ] ] ]; document.body.appendchild(jsontodom(json, ...
Session store API - Archive of obsolete content
in this example, nsiconsoleservice is used to display a message to the console.
... this section provides a few simple examples of how to make use of the session store api.
Signing an XPI - Archive of obsolete content
this example is using the cygwin bin/zip.exe tool.
...this example is using the cygwin bin/zip.exe tool.
Firefox addons developer guide - Archive of obsolete content
see the xul reference, for example.
... for example, here: https://developer.mozilla.org/en/firefox_addons_developer_guide/let's_build_a_firefox_extension#init_method the text of the paragraph should begin "the <code>init()</code> method is as shown...".
Using the Stylesheet Service - Archive of obsolete content
the examples in this document are all written in javascript using xpcom.
... using the api the string "chrome://myext/content/myext.css" in the examples below is just an example.
DOMSubtreeModified - Archive of obsolete content
example the following code will display the time of last dom change on the title bar of the page.
... this event has been deprecated in favor of the mutation observer api this event can cause infinite loops if you decide to change the dom inside the event handler, hence it has been disabled in a number of browsers (see domattrmodified and domsubtreemodified events are no longer fired when style attribute is changed via cssom for example).
Localizing an extension - Archive of obsolete content
for example, in stockwatcher2.xul, we change this line: <menuitem label="refresh now" oncommand="stockwatcher.refreshinformation()"/> to <menuitem label="&menu_refresh_now.label;" oncommand="stockwatcher.refreshinformation()"/> do this for every string used in each xul file.
...for example, to add a spanish localization, you would add: locale stockwatcher2 es-es chrome/locale/es-es/ then just create a subdirectory chrome/locale/es-es and add the needed dtd files; in this case, options.dtd and stockwatcher2.dtd.
MMgc - Archive of obsolete content
you can qualify references to classes in the library; for example: mmgc::gc, mmgc::gcfinalizedobject.
...the flash player class "nativeinfo" is a good example.
cert_override.txt - Archive of obsolete content
example here is an example for a sha1-256 hash algorithm.
... oid sha1-256: oid.2.16.840.1.101.3.4.2.1 (most used) sha-384: oid.2.16.840.1.101.3.4.2.2 sha-512: oid.2.16.840.1.101.3.4.2.3 certificate fingerprint using previous hash algorithm one or more characters for override type: m : allow mismatches in the hostname u : allow untrusted certs (whether it's self signed cert or a missing or invalid issuer cert) t : allow errors in the validity time, for example, for expired or not yet valid certs certificate's serial number and the issuer name as a base64 encoded string ...
Creating a Web based tone generator - Archive of obsolete content
this example creates a simple tone generator, and plays the resulting tone.
... <!doctype html> <html> <head> <title>javascript audio write example</title> </head> <body> <input type="text" size="4" id="freq" value="440"><label for="hz">hz</label> <button onclick="start()">play</button> <button onclick="stop()">stop</button> <script type="text/javascript"> function audiodatadestination(samplerate, readfn) { // initialize the audio output.
Defining Cross-Browser Tooltips - Archive of obsolete content
the classic example is a "tooltip" of an image; when the user pauses the mouse pointer over an image, the contents of the alt attribute are displayed as a "tooltip." gecko-based browsers such as mozilla, netscape 6+, and compuserve 7 do not support this behavior.
...authors who are faced with the prospect of editing a large collection of legacy documents should be able to convert their documents using a batch find-and-replace operation, for example substituting alt= for title=.
Monitoring WiFi access points - Archive of obsolete content
example this example simply displays a list of the available access points.
... <html> <head> <title>wifi monitor example</title> <script> var count = 0; function test() { } test.prototype = { onchange: function (accesspoints) { netscape.security.privilegemanager.enableprivilege('universalxpconnect'); var d = document.getelementbyid("d"); d.innerhtml = ""; for (var i=0; i<accesspoints.length; i++) { var a = accesspoints[i]; d.innerhtml += "<p>" + a.mac + " " + a.ssid + " " + a.signal + "</p>"; } var c = document.getelementbyid("c"); c.innerhtml = "<p>" + count++ + "</p>"; }, onerror: function (value) { alert("error: " +value); }, queryinterface: function(iid) { netscape.security.privilegemanager.enableprivilege('universalxpconnect'); if (iid.equals(components.interfaces.nsiwifilistener) || ...
No Proxy For configuration - Archive of obsolete content
put this into "no proxy for" ...for example use...
...for example: "https://mycompanyintranet/" formats that are not accepted example domain filters with interior wildcards www.*.com ip address string prefixes 127.
Same-origin policy for file: URIs - Archive of obsolete content
for example, if you have a file foo.html which accesses another file bar.html and you have navigated to it from the file index.html, the load will succeed only if bar.html is either in the same directory as index.html or in a directory contained within the same directory as index.html.
...for example, if the file /home/user/foo.html is a frameset and one of the frames is /home/user/subdir/bar.html, the frame and frameset are considered to share the same origin.
Using content preferences - Archive of obsolete content
example: setting and retrieving preferences this example demonstrates how to save a preference and then retrieve its value.
... var value = prefservice.getpref(uri, "devmo.somesetting"); built-in site-specific preferences preference name menu equivalent values notes browser.content.full-zoom view / zoom example: "1.10000002384186" (rounding variant of "1.1") related about:config preferences: browser.zoom.full boolean, set by the menu item view / zoom / zoom text only.
Visualizing an audio spectrum - Archive of obsolete content
this example calculates and displays fast fourier transform (fft) spectrum data for the playing audio.
... <!doctype html> <html> <head> <title>javascript spectrum example</title> </head> <body> <audio id="audio-element" src="song.ogg" controls="true" style="width: 512px;"> </audio> <div><canvas id="fft" width="512" height="200"></canvas></div> <script> var canvas = document.getelementbyid('fft'), ctx = canvas.getcontext('2d'), channels, rate, framebufferlength, ...
Automated testing tips and tricks - Archive of obsolete content
todo: check example code in to the tree somewhere how to quit the browser on all platforms window.close() of the last open window does not quit the application on mac http://people.mozilla.com/~davel/scripts/ - look at quit.js and quit.xul install manifest file in appdir/chrome to map chrome://tests/content to directory containing quit.js and quit.xul example: content tests file:///users/davel/work/tests/ start app with command line flag -chrome chrome://tests/content/quit.xul how to create a new profile from the command line first, use the -createprofile command line flag to add a profile entry to profiles.ini and populate the new profile directory with a prefs.js file firefox-bin -createprofile "testprofile ${profile_...
...ep 5 after the above command should ensure the profile is created before the next command in the test script is run how to enable dump in a new profile add user_pref("browser.dom.window.dump.enabled", true); to profiledir/user.js how to execute test code with chrome privileges using a chrome doc - see sbtests.xul in http://people.mozilla.com/~davel/scripts/ for an example firefox-bin -p sbtestprofile -chrome chrome://sbtests/content/ above code calls the quit function in quit.js to exit after test is finished how to detect content onload event from chrome use the domcontentloaded event chromewindow.addeventlistener('domcontentloaded',callbackfunction,false); ...
Structure of an installable bundle - Archive of obsolete content
for example: binary-component components/windows/mycomponent.dll abi=winnt_x86-msvc binary-component components/mac/mycomponent.dylib abi=darwin_x86-gcc3 binary-component components/mac/mycomponent64.dylib abi=darwin_x86_64-gcc3 binary-component components/linux/mycomponent.so abi=linux_x86-gcc3 this also means you can no longer have platform-specific preference files in your bundle.
...for example, if a plugin vendor wanted to make a plugin available for consumer computers running linux(of the form: /platform/linux*/), macintosh(of the form: /platform/darwin*/), and windows(of the form: /platform/win*/), it would provide the following files: /platform/linux_x86-gcc3/plugins/libmyplugin.so /platform/winnt_x86-msvc/plugins/myplugin.dll /platform/darwin_ppc-gcc3/plugins/libmyplugin.dylib b...
Dehydra Function Reference - Archive of obsolete content
include example include("map.js") // includes map.js into toplevel var map = {} include("map.js", map) // includes map.js into the map object require({version:, strict:, werror:, gczeal:}) require is used to set runtime execution flags.
... require() example require({strict:true, gczeal:2}) if (require().werror) print("werror is set") warning([code,] msg [, loc]) print a warning message using the gcc warning mechanism.
Using Dehydra - Archive of obsolete content
example: printing the location of type declarations save the following c++ code dumptypes.cc: typedef int myint; struct foo { int i; char *c; }; save the following analysis script dumptypes.js: function process_type(t) { print("type found: " + t.name + " location: " + t.loc); } function input_end() { print("hello, world!"); } compile using the following command: $ g++ -fplugin=~/dehydra/gcc_dehydra.so -fplugin-arg=~/dumptypes.js -o/dev/null -c dumptypes.cc note:for g++4.5 and up use -fplugin-arg-gcc_dehydra-script= rather than -fplugin-arg it should print the following results: type found...
... see documentation for: process_type, input_end, print, .loc property example: using attributes to mark a class as "final" save the following code as final.cc: // this class should not be subclassed!
Drag and Drop - Archive of obsolete content
for example, dragging files to other directories, or dragging an icon to another window to open the document it refers to.
...for example, this will be set to 5 if five bookmarks are being dragged.
Exception logging in JavaScript - Archive of obsolete content
as a result, if, for example, c++ code called a javascript component, which threw an exception, that exception would be logged to the console before control was returned to the c++ caller.
...exception reporting in firefox 3 firefox 3 improves reporting of unhandled exceptions by establishing a set of rules that determines whether or not an exception is worth reporting: any methods on interfaces annotated with the [function] attribute in idl (see, for example, nsidomeventlistener) that throw exceptions always report those exceptions into the error console.
Block and Line Layout Cheat Sheet - Archive of obsolete content
ns_frame_external_reference ns_frame_replaced_element ns_frame_generated_content ns_frame_has_loaded_images ns_frame_out_of_flow ns_frame_selected_content ns_frame_is_dirty ns_frame_is_unflowable an unflowable frame is an error condition; for example, due to system limitations.
... brs_computemaxwidth this flag is set if reflow should recompute a frame's maximum width; for example, during first-pass table reflow.
Content states and the style system - Archive of obsolete content
content states are what gecko uses to implement the various state-dependent in css (examples would be :hover, :active, :focus, :target, :checked).
... for example, say we have the selectors: a:hover a:not(:hover) div:hover and the hover state on some node changes.
Documentation for BiDi Mozilla - Archive of obsolete content
where the system is capable of tasks such as reversing and shaping text, symmetric swapping, numeric translation, etc., no special text rendering is needed, though there may be a call to a native api to set the base text direction (for example settextalign on windows).
...examples of this are in nstextframe::painttextslowly; nstextframe::paintunicodetext when a selection is displayed; nstextframe::getposition; nstextframe::getpointfromoffset.
Style System Overview - Archive of obsolete content
1 matching rule: use value 2+ matching rules: cascade decides which wins: sort by origin (ua, user, author) & weight (!important), then specificity of selector, then order example document source <doc> <title>a few quotes</title> <para class="emph"> franklin said that <quote>"a penny saved is a penny earned."</quote> </para> <para> fdr said <quote>"we have nothing to fear but <span class="emph">fear itself.</span>"</quote> </para> </doc> example document tree doc ↙ ↓ ↘ ...
...title para class="emph" para ↓ ↓ quote quote ↓ span class="emph" example stylesheet doc { display: block; text-indent: 1em; } title { display: block; font-size: 3em; } para { display: block; } [class="emph"] { font-style: italic; } css style rule representation each declaration block is represented by an nscssdeclaration an cssstyleruleimpl contains each selector associated with that declaration, and the declaration, and is the most important implementation of nsistylerule.
JavaScript crypto - Archive of obsolete content
rtcard-insert", onsmartcardchange, false); document.addeventlistener("smartcard-remove", onsmartcardchange, false); } function deregister() { document.removeeventlistener("smartcard-insert", onsmartcardchange, false); document.removeeventlistener("smartcard-remove", onsmartcardchange, false); } document.body.onload = register; document.body.onunload = deregister; </script> with the above example, your web site will automatically reload anytime a smartcard is inserted or removed.
... example of cryptomechanismflags and cipherflags pkcs11mechanismflags = pkcs11_mech_dsa_flag | pkcs11_mech_skipjack_flag | pkcs11_mech_random_flag; pkcs11cipherflags = 0; return values js_ok_add_module = 3 // successfully added a module js_err_other = -1 // errors other than the following js_err_user_cancel_action = -2 // user aborted an action js_err_...
Java in Firefox Extensions - Archive of obsolete content
var aclass = java.lang.class.forname("org.mozilla.developer.helloworld", true, cl); var astaticmethod = aclass.getmethod("getgreeting", []); var greeting = astaticmethod.invoke(null, []); alert(greeting); another, perhaps simpler approach is as follows: var myclass = loader.loadclass('com.example.myclass'); // use the same loader from above var myobj = myclass.newinstance(); var binval = myobj.mymethod(arg1, arg2); // pass whatever arguments you need (they'll be auto-converted to java form, taking into account the liveconnect conversion rules) for more complex cases, in which you need to call a specific constructor with arguments, you will need reflection.
...one example seems to be the fact that the "java" global is not immediately available if the extension operates in a sidebar (using settimeout solved it at least).
Enabling Experimental Jetpack Features - Archive of obsolete content
string here is an example of how to import a feature (the clipboard) from the future.
...this is an example of how to get this array.
Enabling - Archive of obsolete content
string here is an example of how to import a feature (the clipboard) from the future.
...this is an example of how to get this array.
Enabling Experimental Jetpack Features - Archive of obsolete content
ArchiveMozillaJetpackdocsMetaFuture
string here is an example of how to import a feature (the clipboard) from the future.
...this is an example of how to get this array.
Nanojit - Archive of obsolete content
example the following code works with spidermonkey's hacked version of nanojit.
... for example, in an instruction inr x, a guard would check that x doesn't overflow the range for a 32 bit integer.
New Security Model for Web Services - Archive of obsolete content
for example, if the script in question is "http://www.example.com/foo/bar.xml", then the declarations file http://www.example.com/web-scripts-access.xml which contains the "delegate" keyword delegates to http://www.example.com/foo/web-scripts-access.xml.
... for example: <wsa:allow type="soapv" from="http://www.mozilla.org"/> this command allows soap requests with verification headers from scripts loaded from the domain www.mozilla.org.
Hacking wiki - Archive of obsolete content
you can enable them by adding include("extensions/exampleext.php"); to the end of your <tt>localsettings.php</tt>.
... for example: [snip] include("extensions/breadcrumbs.php"); include("extensions/titleoverride.php"); include("extensions/abbr.php"); include("extensions/object.php"); include("extensions/kbd.php"); ?> tbd installing/configuring rss and doxygen extensions - anything special needs to be done?
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 ma...
Table Layout Strategy - Archive of obsolete content
special cases note: the following examples are not shown correctly due to technical constraints on wiki content.
... you can help by editing this page and adding screenshots or links to example pages.
Running Tamarin acceptance tests - Archive of obsolete content
the /android-public/android-vars.sh script has commented-out examples of the environment settings for running tests on the android avm shell.
... testsuite setup example commands: copy avmshell to /data/local/tamarin.
Venkman Internals - Archive of obsolete content
for example, the "open windows" view shows the browser's windows.
...for example, framerecord represents a javascript stack frame.
Binding Implementations - Archive of obsolete content
for example, a binding could override the setattribute method on element or the retrieval of the value property for an htmlinputelement.
... for example, given a binding with an implementation colorpickergrid that derives from an implementation colorpicker where the two implementations both specify the setcolor method, a caller could invoke colorpicker's method with the following syntax: ...
XML in Mozilla - Archive of obsolete content
for example, dom related questions should probably be discussed in the mozilla.dev.tech.dom newsgroup, while style issues should be discussed on mozilla.dev.tech.css and so on.
...there is test case for fixptr links and a scripting example.
dirCreate - Archive of obsolete content
the following simple example demonstrates the use of the dircreate method.
...example f = getfolder("program", "mynewdirectory"); err = file.dircreate(f); ...
diskSpaceAvailable - Archive of obsolete content
description use this function to make sure there is adequate space on the local disk for extracting and installing your files (see example below).
...example var diskamtneeded = 10000; f = getfolder("program"); diskspace = file.diskspaceavailable(f); g = getfolder(f, "myfile.txt"); if (diskspace > diskamtneeded) { err = addfile(..., ...
modDateChanged - Archive of obsolete content
description most often, the date passed in as the second parameter in moddatechanged is the returned value from a moddate on a separate file, as in the following example, in which the dates of two files are compared.
... example filesource1 = getfolder("program", "file1.txt"); filesource2 = getfolder("program", "file2.txt"); err1 = file.moddate(filesource1); // the baseline returned err2 = file.moddatechanged(filesource1, err1); logcomment("file.moddatechanged should return 'false' = " + err2); // the reason it expects false is we're comparing // the return 'time stamp' value for // file1.txt with the actual file1.txt itself.
getFolder - Archive of obsolete content
for example, mydir = getfolder("file:///", "c|/mysoftco/somedir"); note that forward slashes are used, regardless of the platform.
... example to get an object representing the standard plug-ins directory, you would use this call: plugindir = getfolder("plugins"); ...
initInstall - Archive of obsolete content
package the client version registry pathname for the software (for example: plugins/adobe/acrobat or /royalairways/royalpi/).
...example to start installation for the royal airways plug-in, you could use this code: initinstall("royal airways tripplanner","/royalairways/ tripplanner","1.0.0.0"); ...
loadResources - Archive of obsolete content
be aware that the parameter specifies the file within the xpi and not on the file system, as the following example demonstrates.
... example given a xpi with this internal structure: install.js bin/res_eg_2.properties bin/somefile.exe bin/...
refreshPlugins - Archive of obsolete content
when you use this method in an installation script, as the example below demonstrates, you can install new plug-ins and use them to display the requested media in a web page without interrupting the experience of the user.
...example // install dll into plugins // install xpt into components var xpisrc = "npmcult3dp.dll"; var xpisrc2 = "nsic3dpscriptablepeer.xpt"; initinstall( "cult3d plugin file", "@cycore.com/cult3d;version=1.0.0", "1.0.0"); setpackagefolder(getfolder("plugins")); addfile(xpisrc); addfile("",xpisrc2,getfolder("components"),""); var err = getlasterror(); if (err == success) { err = performinstall(); if (err == success) refreshplugins(); } else cancelinstall(err); ...
Install Object - Archive of obsolete content
the following two lines, for example, are equivalent: f = getfolder("program"); f = install.getfolder("program"); an installation script is composed of calls to the install object, and generally takes the following form: initialize the installation call initinstall with the name of the installation and the necessary registry and version information.
... perform installation check that the files have been added successfully (e.g., by checking the error return codes from many of the main installation methods, and go ahead with the install if everything is in order: performorcancel(); function performorcancel() { if (0 == getlasterror()) performinstall(); else cancelinstall(); } for complete script examples, see script examples.
popupalign - Archive of obsolete content
noneno aligntopleftalign to the top left cornertoprightalign to the top right cornerbottomleftalign to the bottom left cornerbottomrightalign to the bottom right cornersyntax<element popupalign="none | topleft | topright | bottomleft | bottomright"/> example<element id="edit-context" popup="editor-popup" popupanchor="topleft" popupalign="bottomright"/> notesthe popupalign attribute can be used to specify which corner of the popup content is tied to the originating point.
...the example below shows how to create the traditional buttons with attached left mouse menus that exist in the 4.x communicator product.
width - Archive of obsolete content
in this example, the preferred width of the inner hbox will be displayed at 40 pixels.
... <hbox> <hbox width="40" style="background-color: red;"> <label value="40"/> </hbox> </hbox> however, in the following example, despite that the preferred width of the box is 30 pixels, the displayed size of the box will be larger to accommodate the larger label.
Building accessible custom components in XUL - Archive of obsolete content
this will become clearer with some concrete examples: the grid element is the container for the entire control; it gets a role of "wairole:spreadsheet".
...this would allow xul developers to add a single spreadsheet element to their xul applications (for example), with rowheader, columnheader, and cell elements as children, without requiring them to manage the accessibility support for each spreadsheet control.
close - Archive of obsolete content
if an event handler is placed on the window element, it can be prevented to close (see example below).
... example window.addeventlistener("close", function( event ) { // make the close button ineffective event.preventdefault(); }, false); ...
command - Archive of obsolete content
ArchiveMozillaXULEventscommand
for example, a button can be activated by clicking on it with the mouse or by pressing space while it has the focus.
... example menuitem.oncommand = function() { console.log("the menu item has been activated"); }; ...
IO - Archive of obsolete content
ArchiveMozillaXULFileGuideIO
the following example will retrieve a reference to a file located in the profile directory named sample.txt.
...for instance, in the following example, a subdirectory is retrieved.
How to implement a custom XUL query processor component - Archive of obsolete content
in this example, we will create a simple javascript xpcom component.
... here is an example of what our xul might look like when using a custom query processor: <?xml version="1.0"?> <?xml-stylesheet href="chrome://global/skin/" type="text/css"?> <window xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <grid> <columns> <column flex="1"/> <column flex="3"/> <column flex="2"/> <column flex="1"/> </columns> <rows datasources="dummy" ref="." querytype="simpledata"> <template> <row uri="?"> <label value="?name"/> <label value="?age"/> <label value="?h...
Floating Panels - Archive of obsolete content
a floating panel can be created using the panel element with at least two additional attributes as in the following example: <panel id="tools-panel" noautohide="true" titlebar="normal"> <label control="name" value="name:"/> <textbox id="name"/> </panel> the noautohide attribute is used to indicate that the panel is not temporary.
...a label for the titlebar may be set using the label attribute, as in the following example: <panel id="info-panel" noautohide="true" titlebar="normal" label="image properties"> closing a floating panel unlike other panels, a floating panel does not close when clicking outside of it.
MoveResize - Archive of obsolete content
for instance, the following example will move a popup to the upper left corner of the screen: popup.moveto(0, 0); the position may be shifted so as not to cover user interface elements provided by the operating system, such as the menu bar or the task bar.
... void sizeto(in long width, in long height); here is an example which resizes a popup to be 200 pixels wide and 300 pixels high: popup.sizeto(200, 300); ...
Special per-platform menu considerations - Archive of obsolete content
here is an example: <menubar> <menu label="tools"> <menupopup> <menuitem label="spell check"/> <menuitem id="menu_preferences" label="preferences" oncommand="window.opendialog('options.xul', '_new', 'chrome');"/> </menupopup> </menu> </menubar> this menu item will be placed on the application menu on the macintosh but left in the tools menu on other platforms.
... for example, using document.getelementbyid() for the quit menu item returns the hidden item that still sits in the file menu.
Popup Guide - Archive of obsolete content
for example, a popup search field could be used to allow searching and will disappear when a search term has been entered.
...for example, an extension might wish to add a new command on the tools menu to open a dialog specific to the extension.
currentIndex - Archive of obsolete content
if the caret isn't present for any row (for example, because the tree has never been focused), the value will be -1.
... example // one way of retrieving the text of a cell.
Additional Template Attributes - Archive of obsolete content
the generated content is always inserted into the root node, in this example the listbox, not inside the template.
... <hbox datasources="template-guide-photos5.rdf" ref="http://www.xulplanet.com/rdf/myphotos"> <template container="?start" member="?photo"> <rule> <image uri="?photo" src="?photo"/> </rule> </template> </hbox> in this example, the ?photo variable can be used instead of 'rdf:*' (although you can use either even if you specify the member variable).
Namespaces - Archive of obsolete content
for example using the following xml document containing a list of people: <people xmlns="www.example.com/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> <listbox datasources="people.xml" ref="*" querytype="xml"> <template xmlns:ns="www.example.com/people"> <query expr="ns:person"/> <action> <listitem uri="?" label="?ns:name"/> </action> </template> </listbox> once added to the template element the namespaces can then be referenced inside temple rul...
...<listbox datasources="people.xml" ref="*" querytype="xml"> <template xmlns:ns="www.example.com/people"> <query expr="ns:person"/> <rule ns:gender="male"> <label uri="?" label="?ns:name"/> </action> </template> </listbox> ...
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.
Using Multiple Queries to Generate More Results - Archive of obsolete content
<triple subject="?start" predicate="http://www.xulplanet.com/rdf/people" object="?people"/> <member container="?people" child="?item"/> </query> <rule> <binding subject="?item" predicate="http://purl.org/dc/elements/1.1/title" object="?title"/> <action> <label uri="?item" value="?title"/> </action> </rule> </queryset> </template> you can view the example.
...here is an example which generates two sets of results and shows them together.
Things I've tried to do with XUL - Archive of obsolete content
enn: percentages won't have any effect in these examples though, since the actual height of the container isn't known, and 30% of an unknown number is still an unknown number.
...vlad: the boxobject width/height are the actual width and height of the box, regardless of the actual visible portion of the box (clipped by the window borders, for example).
Toolbar customization events - Archive of obsolete content
beforecustomization this event is delivered when the user starts the toolbar customization process; for example, by right-clicking on a toolbar and choosing "customize".
...example in this example, we watch for toolbar changes.
Numeric Controls - Archive of obsolete content
for instance, the following example steps in multiples of 10.
...<textbox type="number" decimalplaces="2"/> in this example, two digits right of the decimal point are shown.
Progress Meters - Archive of obsolete content
the find files example let's add a progress meter to our find file dialog.
... xmlns:html="http://www.w3.org/1999/xhtml" the example so far.
Scroll Bars - Archive of obsolete content
the example given in the syntax above will create a scroll bar that can range from a value of 0 to 100.
...the initial value in this example is 20.
Scrolling Menus - Archive of obsolete content
example - scrolling list of buttons the following example shows how to create a scrolling list of buttons (you will need to resize the window to see the arrow buttons): example 1 : source view <arrowscrollbox orient="vertical" flex="1"> <button label="red"/> <button label="blue"/> <button label="green"/> <button label="yellow"/> <button label="orange"/> <button label="silver"/> <button labe...
...l="lavender"/> <button label="gold"/> <button label="turquoise"/> <button label="peach"/> <button label="maroon"/> <button label="black"/> </arrowscrollbox> if you try this example, it will first open at full size.
Simple Menu Bars - Archive of obsolete content
example of a simple menu bar example 1 : source view <toolbox flex="1"> <menubar id="sample-menubar"> <menu id="file-menu" label="file"> <menupopup id="file-popup"> <menuitem label="new"/> <menuitem label="open"/> <menuitem label="save"/> <menuseparator/> <menuitem label="exit"/> </menupopup> </menu> <menu id="edit-menu" label="edit"> ...
...the image here shows what the earlier example would look like without the menu bar.
XUL Tutorial - Archive of obsolete content
toolbars and menus toolbars simple menu bars more menu features popup menus scrolling menus events and scripts adding event handlers more event handlers keyboard shortcuts focus and selection commands updating commands broadcasters and observers document object model document object model modifying a xul interface manipulating lists box objects xpcom interfaces xpcom examples trees trees more tree features tree selection custom tree views tree view details tree box objects rdf and templates introduction to rdf templates trees and templates rdf datasources advanced rules persistent data skins and locales adding style sheets styling a tree modifying the default skin creating a skin skinning xul files by hand localization property files ...
...bindings introduction to xbl anonymous content xbl attribute inheritance adding properties adding methods adding event handlers xbl inheritance creating reusable content using css and xbl xbl example specialized window types features of a window creating dialogs open and save dialogs creating a wizard more wizards overlays cross package overlays installation creating an installer install scripts additional install features this xul tutorial was originally created by neil deakin.
Urlbar-icons - Archive of obsolete content
« xul reference home [ examples | attributes | properties | methods | related ] the location of ui elements like the bookmarks, feed and go buttons.
... (the url bar is also known as the address bar and the navigation bar.) example the default contents of browser.xul: <hbox id="urlbar-icons"> <button be="" chromedir="ltr" class="urlbar-icon" click="" for="" id="safebrowsing-urlbar-icon" img="" level="safe" might="" onclick="godocommand('safebrowsing-show-warning');" page="" style="-moz-user-focus:" tooltiptext="this" type="menu"> <img class="urlbar-icon" id="star-button" onclick="placesstarbutton.onclick(event);" /> <img address="" chromedir="ltr" class="urlbar-icon" id="go-button" in="" location="" onclick="handleurlbarcommand(event);" p="" the="" to="" tooltiptext="go" /> </button> </hbox> ...
Using the Editor from XUL - Archive of obsolete content
note: these callbacks also fire for every subdocument that loads as a result of the parent document load, for example with frameset documents, or html documents with their own embedded <iframe>s.
...html, for example), it is handled entirely by the rules code, in the willdoaction()call.
XUL Coding Style Guidelines - Archive of obsolete content
for example: <!-- localization note homebtn.label : do not translate the entity value "home".
...some files live in the tree but aren't really part of the build; they're just there as programming examples or a kind of source documentation.
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, p...
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
ArchiveMozillaXULbbox
« 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, , , , , collaps...
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, sortreso...
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
ArchiveMozillaXULbox
« 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, ...
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.
column - Archive of obsolete content
« xul reference home [ examples | attributes | properties | methods | related ] a single column in a columns element.
... example see grid for an example.
columns - Archive of obsolete content
« xul reference home [ examples | attributes | properties | methods | related ] defines the columns of a grid.
... example see grid for an example.
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...
content - Archive of obsolete content
« xul reference home [ examples | attributes | properties | methods | related ] Éste elemento debería pertenecer a query ("consulta").
...for example, by using a value of treechildren, the condition will only match when placing elements directly inside a treechildren tag.
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
ArchiveMozillaXULdeck
« 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.
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="c...
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...
grid - Archive of obsolete content
ArchiveMozillaXULgrid
« xul reference home [ examples | attributes | properties | methods | related ] a grid is a layout type that arranges elements in rows and columns.
... example <!-- groupbox containing a grid.
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, d...
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, fla...
hbox - Archive of obsolete content
ArchiveMozillaXULhbox
« xul reference home [ examples | attributes | properties | methods | related ] a container element which can contain any number of child elements.
... example <!-- two button on the right --> <hbox> <spacer flex="1"/> <button label="connect"/> <button label="ping"/> </hbox> 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, too...
image - Archive of obsolete content
ArchiveMozillaXULimage
« 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.
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 ty...
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, minhei...
listcols - Archive of obsolete content
« xul reference home [ examples | attributes | properties | methods | related ] a container for the columns of a listbox, each of which are created with the listcol element.
... example <!-- creates a two column listbox --> <listbox> <listcols> <listcol flex="1"/> <listcol flex="1"/> </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, minheight, minwidth, mousethrough, observes, ordinal, ori...
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.
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 lab...
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.
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
ArchiveMozillaXULpage
« 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, removee...
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
ArchiveMozillaXULquery
« 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.
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" styl...
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.
row - Archive of obsolete content
ArchiveMozillaXULrow
« xul reference home [ examples | attributes | properties | methods | related ] a single row in a rows element.
... example see grid for an example.
rows - Archive of obsolete content
ArchiveMozillaXULrows
« xul reference home [ examples | attributes | properties | methods | related ] defines the rows of a grid.
... example see grid for an example.
rule - Archive of obsolete content
ArchiveMozillaXULrule
« 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
ArchiveMozillaXULscale
« 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.
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, re...
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, sortres...
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,...
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, , b...
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
ArchiveMozillaXULtabs
« 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.
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 ...
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, co...
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, statustex...
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> <toolb...
treechildren - Archive of obsolete content
« xul reference home [ examples | attributes | properties | methods | related ] this element is the body of the tree.
...ributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata example <tree flex="1"> <treecols> <treecol id="sender" label="sender" flex="1"/> <treecol id="subject" label="subject" flex="2"/> </treecols> <treechildren> <treeitem> <treerow> <treecell label="joe@somewhere.com"/> <treecell label="top secret plans"/> </treerow> </treeitem> <treeitem> <treerow> <treecell label="mel@whereever.com"/> ...
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.
vbox - Archive of obsolete content
ArchiveMozillaXULvbox
« xul reference home [ examples | attributes | properties | methods | related ] a container element which can contain any number of child elements.
... example <!-- two labels at bottom --> <vbox> <spacer flex="1"/> <label value="one"/> <label value="two"/> </vbox> 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, ...
where - Archive of obsolete content
ArchiveMozillaXULwhere
« 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.
Building XULRunner with Python - Archive of obsolete content
for example def onload(): btntest = document.getelementbyid("btntest") btntest.addeventlistener('command', ontest, false) def ontest(): window.alert('button activated') window.addeventlistener('load', onload, false) one possible gotcha is that the default python path used to find modules that areimported explicitly includes the xulrunner executable directory and the directory that is current...
...the jsconsole can also be open and used from code, for example (in javascript) function openjavascriptconsole() { var wwatch = components.classes["@mozilla.org/embedcomp/window-watcher;1"] .getservice(components.interfaces.nsiwindowwatcher); wwatch.openwindow(null, "chrome://global/content/console.xul", "_blank", "chrome,dialog=no,all", null); } // dump to the js console (xulrunner -jsconsole) function js...
Creating a Windows Inno Setup installer for XULRunner applications - Archive of obsolete content
the tutorial here uses the my app example from the article getting started with xulrunner.
...my app's example follows.
XULRunner FAQ - Archive of obsolete content
you can use xulrunner to make a browser (mybrowser example or firefox), but there is no such thing as "the xulrunner browser".
...xulrunner can be used to make development tools (the ajax toolkit framework, for example).
Getting started with XULRunner - Archive of obsolete content
in all systems you should unzip the omni.ja file into some example directory and take a look at all the awesome!
...you can download the sample application from https://github.com/matthewkastor/xulrunner-examples.
toolkit.singletonWindowType - Archive of obsolete content
preference type: string specified by: default prefs of xulrunner applications default: none example: pref("toolkit.singletonwindowtype", "xulmine"); by default, the toolkit.defaultchromeuri preference will cause xulrunner to open a new main application window each time an application is invoked.
...<window windowtype="xulmine"> in our example).
application/http-index-format specification - Archive of obsolete content
example "rw-" means read and write permission, but not execute.
... example 100: this is a comment!
2006-11-03 - Archive of obsolete content
there are some code example given and also further discussion on lastmodifieddate.
... suggestion made for e-mail popup it suggested that the e-mail popup duration should depends on number of messages and examples of this idea is provided.
Monitoring plugins - Archive of obsolete content
here is an example that shows the runtime in an alert box to the user if the runtime exceeds half a second in length: observe: function(subject, topic, data) { if (topic == "experimental-notify-plugin-call" ) { if (data > 0.500) { alert("runtime is: " + data); } } } note: this is just a simplified example and the use of alert() is discouraged as the component can send hundreds of no...
... also note that in the example above an if statement first checks to see that the arriving notification's topic is the correct one.
XEmbed Extension for Mozilla Plugins - Archive of obsolete content
this is an incomplete example of what a piece of code might look like that tries to check for the proper mozilla version.
...xembed sample plugin for a complete working sample of a plugin using in-process xembed, see the diamondx xembed example plugin.
SAX - Archive of obsolete content
an example implementation of the most commonly used content handler: function print(s) { dump(s + "\n"); } xmlreader.contenthandler = { // nsisaxcontenthandler startdocument: function() { print("startdocument"); }, enddocument: function() { print("enddocument"); }, startelement: function(uri, localname, qname, /*nsisaxattributes*/ attributes) { var attrs = []; for(var i=0; ...
...below is an example of parsing from a string: xmlreader.parsefromstring("<f:a xmlns:f='g' d='1'><bbq/></f:a>", "text/xml"); this call results in the following output (assuming the content handler from the example above is used): startdocument startelement: namespace='g', localname='a', qname='f:a', attributes={d='1'} startelement: namespace='', localname='bbq', qname='bbq', attributes={} endelement: namespace=''...
Encryption and Decryption - Archive of obsolete content
for example, 128-bit keys for use with the rc4 symmetric-key cipher supported by ssl provide significantly better cryptographic protection than 40-bit keys for use with the same cipher.
...the rsa cipher used for public-key encryption, for example, can use only a subset of all possible values for a key of a given length, due to the nature of the mathematical problem on which it is based.
Introduction to SSL - Archive of obsolete content
this confirmation might be important if the user, for example, is sending a credit card number over the network and wants to check the receiving server's identity.
...this confirmation might be important if the server, for example, is a bank sending confidential financial information to a customer and wants to check the recipient's identity.
Table Reflow Internals - Archive of obsolete content
table reflow example <table width=300> <tr> <td>foo</td> <td>bar zap</td> </tr> </table> key: r = reflow reason, 0 (initial), 2 (resize) a = avail w, h c = computed w, h d = desired w, h me = max elem w debugging frame reflow gives instructions for turning this on: tblo 030176cc r=0 a=8940,uc c=0,0 cnt=429 tbl 030178c4 r=0 a=8940,uc c=4470,uc cnt=430 rowg 03017a7c r=0 ...
...ecial height reflow when there is a % height frame inside a cell without a computed height the frame will never get a chance to size based on the final cell height in paginated mode when there is a height on the table, the table doesn't allocate extra height to rows until after it does a pass 2 reflow and then it is too late this can be fixed by doing a special 3rd pass reflow special reflow example <table border=2 width=300> <tr> <td> this cell's width is constrained by the table and image widths.
The Basics of Web Services - Archive of obsolete content
examples of web services in action as said before, rss and atom feeds are a simple example of how a web service works, most commonly, xml-rpc or soap are also used to communicate between a server and a client.
...an example is, it is easier to send a multi-dimensional array with soap rather then with xml-rpc.
Theme changes in Firefox 4 - Archive of obsolete content
examples the default windows theme wants to force small icons on the navigation bar regardless of the user preference.
...ookmarks toolbar when the related user preference is set: #navigator-toolbox[iconsize="large"] > #personaltoolbar { counter-reset: largeicons; } to use large icons everywhere, including the menu bar, regardless of the user preference: #navigator-toolbox > toolbar, #addon-bar { counter-reset: largeicons; } creating a theme that works for firefox 4 on mac os x create a new directory (for example, my_theme).
Using IO Timeout And Interrupt On NT - Archive of obsolete content
for example, suppose thread a and thread b call <tt>pr_accept()</tt> on the same socket, and they time out at the same time.
...suppose the file descriptor is intended to be used for the life time of the process, for example, the logging file, this is really not acceptable.
Using workers in extensions - Archive of obsolete content
if you haven't already created an extension, or would like to refresh your memory, take a look at the previous articles in this series: creating a status bar extension creating a dynamic status bar extension adding preferences to an extension localizing an extension updating an extension to support multiple mozilla applications download the sample you may download the complete example: download the example.
... the worker the worker thread's job in this example is to issue the xmlhttprequest calls that fetch the updated stock information.
-moz-binding - Archive of obsolete content
syntax /* <url> value */ -moz-binding: url(http://www.example.org/xbl/htmlbindings.xml#checkbox); /* global values */ -moz-binding: inherited; -moz-binding: initial; -moz-binding: unset; values <url> the url for the xbl binding (including the fragment identifier).
... 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.
-moz-stack-sizing - Archive of obsolete content
for example, moving a child of the stack far to the right will widen the stack so the child remains visible.
... formal syntax ignore | stretch-to-fit examples .mainsheet { -moz-stack-sizing: ignore; } ...
-ms-scroll-snap-x - Archive of obsolete content
formal syntax <'-ms-scroll-snap-type'> <'-ms-scroll-snap-points-x'> examples the -ms-scroll-snap-x property is a shorthand property.
... the two selectors in the following example have the same effect.
-ms-scroll-snap-y - Archive of obsolete content
formal syntax <'-ms-scroll-snap-type'> <'-ms-scroll-snap-points-y'> examples the -ms-scroll-snap-y property is a shorthand property.
... the two selectors in the following example have the same effect.
-ms-scrollbar-3dlight-color - Archive of obsolete content
)where <alpha-value> = <number> | <percentage><hue> = <number> | <angle> examples the following example shows how to create a style rule that sets the -ms-scrollbar-3dlight-color property for a <textarea> element.
... code example: http://samples.msdn.microsoft.com/workshop/samples/author/dhtml/refs/scrollbarcolor.htm <!doctype html> <html> <head> <title>scrollbar-3dlight-color</title> <style> .blue3dlight { -ms-scrollbar-3dlight-color: blue; scrollbar-3dlight-color: blue; /* use the standard when available.
-ms-scrollbar-darkshadow-color - Archive of obsolete content
)where <alpha-value> = <number> | <percentage><hue> = <number> | <angle> examples the following example shows how to create a style rule that sets the -ms-scrollbar-darkshadow-color property for a <textarea> element.
... code example: http://samples.msdn.microsoft.com/workshop/samples/author/dhtml/refs/scrollbarcolor.htm <!doctype html> <html> <head> <title>scrollbar-darkshadow-color</title> <style> .blueshadow { scrollbar-darkshadow-color: blue; } </style> </head> <body> <textarea class="blueshadow">the gutter elements in the scroll bar for this element will be blue.</textarea> </body> </html> specifications not part of any specification.
::-ms-check - Archive of obsolete content
tyle border-top-width box-shadow box-sizing color cursor display (values block, inline-block, none) @font-face font-size font-style font-weight height margin-bottom margin-left margin-right margin-top opacity outline-color outline-style outline-width padding-bottom padding-left padding-right padding-top transform transform-origin visibility width syntax ::-ms-check example html <form> <label for="redbutton">red</label> <input type="radio" id="redbutton"><br> <label for="greencheckbox">green</label> <input type="checkbox" id="greencheckbox"> </form> css input, label { display: inline; } input[type=radio]::-ms-check { border-color: red; /* this will make the border red when the button is checked.
...*/ } result below is an example for you to try.
display-outside - Archive of obsolete content
for example, a table-row box requires its parent to be a table row group box and its children to be table-cell boxes.
...for example, a table-caption box must have a table parent, but can establish any kind of formatting context for its children.
The global XML object - Archive of obsolete content
the following example defines the foocount() method, which returns the amount of <foo> elements in the xml: xml.prototype.function::foocount = function foocount() { return this..foo.length(); }; <foobar><foo/><foo/><foo/></foobar>.foocount() // returns 3 ignorecomments true by default.
...for example var element = <foo> <?process x="true"?> <bar/> <?process x="false"?> </foo>; element.toxmlstring(); // returns <foo><bar/></foo> xml.ignoreprocessinginstructions = false; var element = <foo> <?process x="true"?> <bar/> <?process x="false"?> </foo>; element.toxmlstring(); ...
Array comprehensions - Archive of obsolete content
new variables (such as i in the example) are treated as if they had been declared using let.
... 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], ...
Date.prototype.toLocaleFormat() - Archive of obsolete content
examples using tolocaleformat() var today = new date(); var date = today.tolocaleformat('%a, %b %e, %y'); in this example, tolocaleformat() returns a string such as "wednesday, october 3, 2007".
... note that the format string in this example is not properly localized, which will result in the problems described above.
Debug.write - Archive of obsolete content
example this example uses the debug.write function to display the value of the variable in the immediate window of the script debugger.
... note: to run this example, you must have a script debugger installed and the script must run in debug mode.
Debug.writeln - Archive of obsolete content
example this example uses the debug.writeln function to display the value of the variable in the immediate window of the microsoft script debugger.
... note: to run this example, you must have a script debugger installed and the script must run in debug mode.
Error.number - Archive of obsolete content
example the following example causes an exception to be thrown and displays the error code that is derived from the error number.
... var x = y; } catch(e) { document.write ("error code: "); document.write (e.number & 0xffff) document.write ("<br />"); document.write ("facility code: ") document.write(e.number>>16 & 0x1fff) document.write ("<br />"); document.write ("error message: ") document.write (e.message) } example the output of this code is as follows.
VBArray.dimensions - Archive of obsolete content
example the dimensions method provides a way to retrieve the number of dimensions in a specified vbarray.
... the following example consists of three parts.
VBArray.toArray - Archive of obsolete content
for example, a vbarray with three dimensions and three elements in each dimension is converted into a javascript array as follows: suppose the vbarray contains: (1, 2, 3), (4, 5, 6), (7, 8, 9).
... example the following example consists of three parts.
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.
Packages - Archive of obsolete content
for example, you can access a constructor of the frame class as follows: var theframe = new packages.java.awt.frame(); for convenience, javascript provides the top-level netscape, sun, and java objects that are synonyms for the packages properties with the same names.
... 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).
... here is an example: var incompletehandler = {get:function(myproxy, name){ alert('property ' + name + ' accessed.'); return 1; } }; var p = proxy.create(incompletehandler); var q = p.blabla; // alerts 'property blabla accessed' and 1 is assigned to q p.azerty = "trying to set a property"; // throws an error since neither the set trap or the fundamental trap used in the set trap are implemented no-op forwarding proxy in this example, we are using a native javascript object to which our proxy will forward all operations that are applied to it.
Styling the Amazing Netscape Fish Cam Page - Archive of obsolete content
here's a typical (and short) example.
...with just the few elements i had available in this example, there were any number of possibilities for design effects, and i think you'll find the same to be true for your own designs if you just give this sort of approach a try.
Mozilla XForms Specials - Archive of obsolete content
instead you will have to use the following normal classes instead: xf-value xf-repeat-item xf-repeat-index for example, to target the value element of an input control use: @namespace xf url("http://www.w3.org/2002/xforms"); xf|input .xf-value { ...
...if you are wondering why we have this restriction, here is a simple example of why: <xforms:model> <xforms:instance src="http://intranetserver/addrbook.xml"/> <xforms:submission id="sub" action="http://megaspammer.com/gather" method="post"/> <xforms:send submission="sub" ev:event="xforms-ready"/> </xforms:model> this imaginary would fetch something that is only accessible for you (f.x.
RFE to the XForms API - Archive of obsolete content
ArchiveWebXFormsRFEXForms API
for example, every visual xforms element exposes the nsixformsdelegate interface.
...as an example, the nsixformsaccessors interface which allows a user to get/set the value of an instance node and get the state of an instance node, is exposed by the nsixformsdelegate interface using the accessors property.
XForms Input Element - Archive of obsolete content
for example, the value --01 means the month of january.
...for example, the value ---03 means the third day of the month.
XForms Output Element - Archive of obsolete content
to see how they work you can try an xhtml example or a xul example.
...characteristics the bound instance node is of type xsd:anyuri, xsd:base64binary or a type derived from it either the mediatype attribute is present and contains the image's mimetype or the output element contains a mediatype element which specifies the image's mimetype (for example, image/*).
XForms Repeat Element - Archive of obsolete content
example <model> <instance> <my:lines> <my:line name="a"> <my:price>3.00</my:price> </my:line> <my:line name="b"> <my:price>32.25</my:price> </my:line> </my:lines> </instance> </model> <repeat id="lineset" nodeset="/my:lines/my:line"> <input ref="my:price"> <label>line item</label> </input> <input ref="@name"> <label>name</label> </inpu...
... example <xforms:model id="i_model"> <xforms:instance xmlns=""> <data xmlns:html="http://www.w3.org/1999/xhtml" xmlns=""> <val id="1"> <nest>nest 1.1</nest> <nest>nest 1.2</nest> </val> <val id="2"> <nest>nest 2.1</nest> <nest>nest 2.2</nest> </val> </data> </xforms:instance> </xforms:model> <div xforms:repeat-nodeset="val"> this is t...
Correctly Using Titles With External Stylesheets - Archive of obsolete content
here are two examples: <link type="text/css" rel="stylesheet" title="basic styles" href="basic.css" /> <link type="text/css" rel="stylesheet" title="fish and boats" href="ocean.css" /> according to the html 4.01 specification, only one of the preferred stylesheets can be used at a time.
... therefore, given the above example, only one of the two preferred stylesheets will be applied to the document.
Describing microformats in JavaScript - Archive of obsolete content
custom custom data a simple example the hcard microformat for defining contact information makes use of the adr microformat to define an address.
...this allows an address to be marked as being, for example, a work address for receiving parcels.
Displaying a graphic with audio samples - Archive of obsolete content
the following example shows how to take samples from an audio stream and display them behind an image (in this case, the mozilla logo), giving the impression that the image is built from the samples.
... <!doctype html> <html> <head> <title>javascript spectrum example</title> </head> <body> <audio id="audio-element" src="revolve.ogg" controls="true" style="width: 512px;"> </audio> <div><canvas id="fft" width="512" height="200"></canvas></div> <img id="mozlogo" style="display:none" src="mozilla2.png"></img> <script> var canvas = document.getelementbyid('fft'), ctx = canvas.getcontext('2d'), channels, rate, framebufferlength, fft; function loadedmetadata() { channels = audio.mozchannels; rate = audio.mozsamplerate; framebufferlength = audio.mozframebufferlength; fft = new fft(framebufferlength / channels, rat...
Fixing Table Inheritance in Quirks Mode - Archive of obsolete content
if the author had set a font size on the body element, for example, the font size of text within a table would match the user's default, not the body style.
...for example, if an author writes: <style type="text/css"> body {font-size: 11px;} </style> ...then the text inside table cells should also be 11 pixels in size.
Issues Arising From Arbitrary-Element hover - Archive of obsolete content
for example: :hover {color: red;} this is equivalent to the css2 rule: *:hover {color: red;} ..which translates as "any element that is being hovered should have its foreground colored red." thus, hovering over paragraphs, tables, headings, and any other element in a document will cause text to become red.
...for example: <a name="pagetop"> <h2>my page</h2> without a </a>, this name will effectively enclose the rest of the document.
RDF in Fifty Words or Less - Archive of obsolete content
let's look at an example:bookmarks.
... let's go back to our bookmark example.
Building up a basic demo with the PlayCanvas engine - Game development
the first <script> element includes the playcanvas library in the page; we will write our example code in the second one.
... conclusion here's the final code listing, along with a viewable live example: you can also see it on github and fork the repository if you want to play with it yourself locally.
Desktop gamepad controls - Game development
you could also create a helper function that would assign proper names to the listed buttons, so for example istead of checking out if gamepadbuttonpressedhandler(3) is pressed, you could do a more descriptive check: gamepadbuttonpressedhandler('dpad-right').
... the buttons variable contains the layout of a given controller (for example which buttons are where, because an xbox 360 layout may be different to a generic one), the cache containing the information about the buttons from the previous frame and the status containing the information from the current frame.
Implementing game control mechanisms - Game development
case study we'll be using the captain rogers: battle at andromeda demo as an example.
... for example, you can define a button in the create() function: create: function() { // ...
Physics - Game development
fun with physics you can do much more with physics, for example by adding ball.body.gravity.y = 100; you will set the vertical gravity of the ball.
...check out the official physics documentation and see the huge collection of examples using the arcade and p2 physics systems.
Game development
port native games to the web if you are a native developer (for example writing games in c++), and you are interested in how you can port your games over to the web, you should learn more about our emscripten tool — this is an llvm to javascript compiler, which takes llvm bytecode (e.g.
... examples for a list of web game examples, see our examples page.
Block - MDN Web Docs Glossary: Definitions of Web-related terms
for example, <p> is by default a block-level element, whereas <a> is an inline element — you can put several links next to one another in your html source and they will sit on the same line as one another in the rendered output.
...for example, you can put a block of statements after an if (condition) block, indicating that the interpreter should run the code inside the block if the condition is true, or skip the whole block if the condition is false.
Block cipher mode of operation - MDN Web Docs Glossary: Definitions of Web-related terms
the size of each block is fixed and determined by the algorithm: for example aes uses 16-byte blocks.
...for example, aes is a cipher, while ctr, cbc, and gcm are all modes.
Callback function - MDN Web Docs Glossary: Definitions of Web-related terms
here is a quick example: function greeting(name) { alert('hello ' + name); } function processuserinput(callback) { var name = prompt('please enter your name.'); callback(name); } processuserinput(greeting); the above example is a synchronous callback, as it is executed immediately.
...a good example is the callback functions executed inside a .then() block chained onto the end of a promise after that promise fulfills or rejects.
Constant - MDN Web Docs Glossary: Definitions of Web-related terms
a constant is a value that the programmer cannot change, for example numbers (1, 2, 42).
...for example, the identifier pi could be bound to the value 3.14...
Control flow - MDN Web Docs Glossary: Definitions of Web-related terms
for example, imagine a script used to validate user data from a webpage form.
... for example, the above excerpt might be inside a function that runs when the user clicks the submit button for the form.
Delta - MDN Web Docs Glossary: Definitions of Web-related terms
for example, when describing how far an object on the screen moves left-to-right, one might use the term delta x or Δx.
...ise, given the new value of x and its old value, you might compute the delta like this: let deltax = newx - oldx; more commonly, you receive the delta and use it to update a saved previous condition: let newx = oldx + deltax; learn more technical reference mouse wheel events (wheelevent offer the amount the wheel moved since the last event in its deltax, deltay, and deltaz properties, for example.
Empty element - MDN Web Docs Glossary: Definitions of Web-related terms
many combinations have no semantic meaning, for example an <audio> element nested inside an <hr> element.
...for example, <input type="text"></input> is invalid html.
Entity - MDN Web Docs Glossary: Definitions of Web-related terms
for example, the entity for the copyright symbol (©) is &copy;.
...for example, if you use the less-than (<) sign, the browser interprets any text that follows as a tag.
Global object - MDN Web Docs Glossary: Definitions of Web-related terms
for example: in a web browser, any code which the script doesn't specifically start up as a background task has a window as its global object.
... explanation: the global variable foo was stored in the window object, like this: foo: "foobar" access global functions function greeting() { console.log("hi!"); } window.greeting(); // it is the same as the normal invoking: greeting(); the example above explains how global functions are stored as properties in the window object.
Graceful degradation - MDN Web Docs Glossary: Definitions of Web-related terms
polyfills can be used to build in missing features with javascript, but acceptable alternatives to features like styling and layout should be provided where possible, for example by using the css cascade, or html fallback behaviour.
... some good examples can be found in handling common html and css problems.
Grid Areas - MDN Web Docs Glossary: Definitions of Web-related terms
grid areas must be rectangular in nature; it is not possible to create, for example, a t- or l-shaped grid area.
... in the example below i have a grid container with two grid items.
MVC - MDN Web Docs Glossary: Definitions of Web-related terms
model view controller example imagine a simple shopping list app.
... so for example, our shopping list could have input forms and buttons that allow us to add or delete items.
Object - MDN Web Docs Glossary: Definitions of Web-related terms
objects sometimes refer to real-world things, for example a car or map object in a racing game.
... javascript, java, c++, python, and ruby are examples of object-oriented programming languages.
Prefetch - MDN Web Docs Glossary: Definitions of Web-related terms
<link rel="dns-prefetch" href="https://example.com/"> link prefetching link prefetching is a performance optimization technique that works by assuming which links the user is likely to click, then downloading the content of those links.
... <link rel="prefetch" href="https://www.example.com/solutions" /> ...
Preflight request - MDN Web Docs Glossary: Definitions of Web-related terms
for example, a client might be asking a server if it would allow a delete request, before sending a delete request, by using a preflight request: options /resource/foo access-control-request-method: delete access-control-request-headers: origin, x-requested-with origin: https://foo.bar.org if the server allows it, then it will respond to the preflight request with an access-control-allow-methods response h...
...eader, which lists delete: http/1.1 204 no content connection: keep-alive access-control-allow-origin: https://foo.bar.org access-control-allow-methods: post, get, options, delete access-control-max-age: 86400 the preflight response can be optionally cached for the requests created in the same url using access-control-max-age header like in the above example.
Primitive - MDN Web Docs Glossary: Definitions of Web-related terms
example this example will help you understand that primitive values are immutable.
... another example [ step-by-step ] the following example will help you go through how javascript deals with primitives.
Request header - MDN Web Docs Glossary: Definitions of Web-related terms
for example, the content-length appearing in a post request is actually an entity header referring to the size of the body of the request message.
...xhtml+xml,application/xml;q=0.9,*/*;q=0.8 accept-language: en-us,en;q=0.5 accept-encoding: gzip, deflate, br referer: https://developer.mozilla.org/testpage.html connection: keep-alive upgrade-insecure-requests: 1 if-modified-since: mon, 18 jul 2016 02:36:04 gmt if-none-match: "c561c68d0ba92bbeb8b0fff2a9199f722e3a621a" cache-control: max-age=0 strictly speaking, the content-length header in this example is not a request header like the others, but an entity header: post /myform.html http/1.1 host: developer.mozilla.org user-agent: mozilla/5.0 (macintosh; intel mac os x 10.9; rv:50.0) gecko/20100101 firefox/50.0 content-length: 128 learn more technical knowledge list of all http headers ...
Round Trip Time (RTT) - MDN Web Docs Glossary: Definitions of Web-related terms
$ ping example.com ping example.com (216.58.194.174): 56 data bytes 64 bytes from 216.58.194.174: icmp_seq=0 ttl=55 time=25.050 ms 64 bytes from 216.58.194.174: icmp_seq=1 ttl=55 time=23.781 ms 64 bytes from 216.58.194.174: icmp_seq=2 ttl=55 time=24.287 ms 64 bytes from 216.58.194.174: icmp_seq=3 ttl=55 time=34.904 ms 64 bytes from 216.58.194.174: icmp_seq=4 ttl=55 time=26.119 ms --- google.com ping statistics --- 5 packets transmitted, 5 packets received, 0.0% packet loss round-trip min/avg/max/stddev = 23.781/26.828/...
...34.904/4.114 ms in the above example, the average round trip time is shown on the final line as 26.8ms.
Scope - MDN Web Docs Glossary: Definitions of Web-related terms
a function serves as a closure in javascript, and thus creates a scope, so that (for example) a variable defined exclusively within the function cannot be accessed from outside the function or within other functions.
... for instance, the following is invalid: function examplefunction() { var x = "declared inside function"; // x can only be used in examplefunction console.log("inside function"); console.log(x); } console.log(x); // causes error however, the following code is valid due to the variable being declared outside the function, making it global: var x = "declared outside function"; examplefunction(); function examplefunction() { console.log("inside function"); console.log(x); } console.log("outside function"); console.log(x); learn more general knowledge scope (computer science) on wikipedia ...
Symmetric-key cryptography - MDN Web Docs Glossary: Definitions of Web-related terms
the size of each block is fixed and determined by the algorithm: for example aes uses 16-byte blocks.
...for example, aes is a cipher, while ctr, cbc, and gcm are all modes.
Synchronous - MDN Web Docs Glossary: Definitions of Web-related terms
a human example is the telephone — during a telephone call you tend to respond to another person immediately.
... many programming commands are also synchronous — for example when you type in a calculation, the environment will return the result to you instantly, unless you program it not to.
Type - MDN Web Docs Glossary: Definitions of Web-related terms
for example, a boolean data type can hold only a true or false value at any given time, whereas a string has the ability to hold a string or a sequence of characters, a number can hold numerical values of any kind, and so on.
...for example, a value of type number can be multiplied by another number, but not by a string - even if that string contains only a number, such as the string "2".
Cacheable - MDN Web Docs Glossary: Definitions of Web-related terms
(for example, firefox does not support it per https://bugzilla.mozilla.org/show_bug.cgi?id=109553.) other methods, like put or delete are not cacheable and their result cannot be cached.
...for example, a put to pagex.html will invalidate all cached get or head requests to the same uri.
markup - MDN Web Docs Glossary: Definitions of Web-related terms
html (hypertext markup language), is an example of a markup language.
...for example, the html <td> defines a cell in a html table.
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.ex...
...ample.com different hosts http://example.com http://example.com:8080 different ports specifications specification status comment html living standardthe definition of 'origin' in that specification.
Assessment: Accessibility troubleshooting - Learn web development
starting point to get this assessment started, you should go and grab the zip containing the files that comprise the example.
... a link to the example you want assessed or need help with, in an online shareable editor (as mentioned in step 1 above).
A cool-looking box - Learn web development
example the following screenshot shows an example of what the finished design could look like: assessment or further help if you would like your work assessed, or are stuck and want to ask for help: put your work into an online shareable editor such as codepen, jsfiddle, or glitch.
... a link to the example you want assessed or need help with, in an online shareable editor (as mentioned in step 1 above).
Creating fancy letterheaded paper - Learn web development
example the following screenshot shows an example of what the finished design could look like: assessment or further help if you would like your work assessed, or are stuck and want to ask for help: put your work into an online shareable editor such as codepen, jsfiddle, or glitch.
... a link to the example you want assessed or need help with, in an online shareable editor (as mentioned in step 1 above).
Styling tables - Learn web development
well, i say typical — most html table examples are about shoes, or the weather, or employees; we decided to make things more interesting by making it about famous punk bands from the uk.
... styling our table let's work through styling our table example together.
Test your skills: tables - Learn web development
assessment or further help you can practice these examples in the interactive editors mentioned above.
... a link to the example you want assessed or need help with, in an online shareable editor (as mentioned in step 1 above).
Test Your Skills: Fundamental layout comprehension - Learn web development
assessment or further help you can practice these examples in the interactive editors mentioned above.
... a link to the example you want assessed or need help with, in an online shareable editor (as mentioned in step 1 above).
Test your skills: Media Queries and Responsive Design - Learn web development
assessment or further help you can practice these examples in the interactive editors mentioned above.
... a link to the example you want assessed or need help with, in an online shareable editor (as mentioned in step 1 above).
Typesetting a community school homepage - Learn web development
example the following screenshot shows an example of what the finished design could look like: assessment or further help if you would like your work assessed, or are stuck and want to ask for help: put your work into an online shareable editor such as codepen, jsfiddle, or glitch.
... a link to the example you want assessed or need help with, in an online shareable editor (as mentioned in step 1 above).
Learn to style HTML using CSS - Learn web development
for example, you can use css to alter the font, color, size, and spacing of your content, split it into multiple columns, or add animations and other decorative features.
... css first steps css (cascading style sheets) is used to style and lay out web pages — for example, to alter the font, color, size, and spacing of your content, split it into multiple columns, or add animations and other decorative features.
How can we design for all types of users? - Learn web development
for example, visually impaired users rely on a screen reader, which can only handle text.
...please refer to the w3c's image description extension (longdesc) for the full explanation and thorough examples.
What HTML features promote accessibility? - Learn web development
<ul> <li><a href="here.html" tabindex="1">here</a></li> <li><a href="there.html" tabindex="3">there</a></li> <li><a href="anywhere.html" tabindex="2">anywhere</a></li> </ul> in this example (which is used purely as a demonstration—do not do this), tabbing would jump from “here” to “anywhere” to “there”.
...you might want to allow someone to jump over a plethora of navigation links, for example, so they can just read a page’s main content rather than cycle through all of the links.
What is the difference between webpage, website, web server, and search engine? - Learn web development
for example, if you hear someone say, "my website is not responding", it actually means that the web server is not responding and therefore the website is not available.
...in our previous example, if we said, "my web server is not responding", it means that multiple websites on that web server are not available.
What is a Domain Name? - Learn web development
for example: local tlds such as .us, .fr, or .se can require the service to be provided in a given language or hosted in a certain country — they are supposed to indicate a resource in a particular language or country.
...a, 97, and hello-strange-person-16-how-are-you are all examples of valid labels.
Test your skills: Form structure - Learn web development
assessment or further help you can practice this example in the interactive editor above.
... a link to the example you want assessed or need help with, in an online shareable editor (as mentioned in step 1 above).
Test your skills: Styling basics - Learn web development
assessment or further help you can practice these examples in the interactive editors above.
... a link to the example you want assessed or need help with, in an online shareable editor (as mentioned in step 1 above).
How the Web works - Learn web development
a simplified diagram of how they interact might look like this: clients are the typical web user's internet-connected devices (for example, your computer connected to your wi-fi, or your phone connected to your mobile network) and web-accessing software available on those devices (usually a web browser like firefox or chrome).
...in our example, this is like a car or a bike (or however else you might get around).
Tips for authoring fast-loading HTML pages - Learn web development
for example, html tidy can remove whitespace and optional ending tags; however, it will refuse to run on a page with serious markup errors.
... example page structure · <html> · <head> · <link> ...
Using data attributes - Learn web development
for example to show the parent data on the article you can use generated content in css with the attr() function: article::before { content: attr(data-parent); } you can also use the attribute selectors in css to change styles according to the data: article[data-columns='3'] { width: 400px; } article[data-columns='4'] { width: 600px; } you can see all this working together in this jsbin example.
...see this screencast for an example using generated content and css transitions (jsbin example).
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.
... marking up a letter we all learn to write a letter sooner or later; it is also a useful example to test out text formatting skills.
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.
Adding features to our bouncing balls demo - Learn web development
the following screenshot gives you an idea of what the finished program should look like: to give you more of an idea, have a look at the finished example (no peeking at the source code!) steps to complete the following sections describe what you need to do.
... a link to the example you want assessed or need help with, in an online shareable editor (as mentioned in step 1 above).
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.
... for example, a web site oriented for web developers might wish to send certain example html documents as either text/html or text/plain in order to have the documents either processed and displayed as html or as source code.
Getting started with React - Learn web development
for example: const heading = <h1>mozilla developer network</h1>; this heading constant is known as a jsx expression.
...for example, class in html translates to classname in jsx.
React interactivity: Events and state - Learn web development
for example: const btn = document.queryselector('button'); btn.addeventlistener('click', () => { alert("hi!"); }); in react, we write event handlers directly on the elements in our jsx, like this: <button type="button" onclick={() => alert("hi!")} > say hi!
... in the above example, we're adding an onclick attribute to the <button> element.
Deployment and next steps - Learn web development
let's look at a couple of examples.
... you can also consult the svelte api docs and the available examples.
Dynamic behavior in Svelte: working with variables and props - Learn web development
for example, if you specify on:click={removetodo(todo)}, it will execute removetodo(todo) and the result will be passed as a handler, which is not what we had in mind.
...this is another example in which svelte takes advantage of valid javascript syntax and gives it a new purpose — in this case to to mean "re-run this code whenever any of the referenced values change".
Adding a new todo form: Vue events, methods, and models - Learn web development
you should see the value you entered logged to your console, for example: label value: my value changing v-model behavior with modifiers in a similar fashion to event modifiers, we can also add modifiers to change the behavior of v-model.
...try for example, submitting a value with whitespace at each end.
Understanding client-side JavaScript frameworks - Learn web development
in this article, we'll look at a little bit of vue background, learn how to install it and create a new project, study the high-level structure of the whole project and an individual component, see how to run the project locally, and get it prepared to start building our example.
...starting our svelte todo list app now that we have a basic understanding of how things work in svelte, we can start building our example app: a todo list.
Understanding client-side web development tools - Learn web development
we finish up by providing a complete toolchain example showing you how to get productive.
...deploying our app in the final article in our series, we take the example toolchain we built up in the previous article and add to it so that we can deploy our sample app.
Tools and testing - Learn web development
for example, you'll need to know the fundamentals of these languages before you start debugging problems in complex web code, making effective use of javascript frameworks, or writing tests and running them against your code using test runners.
...we finish up by providing a complete toolchain example showing you how to get productive.
Accessibility API cross-reference
oes not require immediacy alert_medium n/a n/a aria-live=polite low-priority info such as a tip or hint alert_low n/a n/a n/a this object is changing or moving rapidly animated n/a n/a n/a indicates that the user input is currently directed to that object and it is "armed for selection." example: a highlighted menu item or a pressed push button.
...for example, could be used with higher level containers.
Mozilla’s UAAG evaluation report
look to the "techniques" document for real-world implementation examples of each checkpoint.
...ht selected images we do not have the ability to show a border around the text selection we have the following focus appearance prefs that are not exposed in the ui, but can be manually inserted in the user's prefs.js file: setboolpref("browser.display.use_focus_colors", usefocuscolors); /* true or false */ setcharpref("browser.display.focus_background_color", colorstring); /* for example #ffeedd or the name of a color */ setcharpref("browser.display.focus_text_color", colorstring); setcharpref("browser.display.focus_ring_width", numpixels); /* integer 0-4 */ 10.3 distinct default highlight styles.
Benchmarking
this setting reduces build times significantly but comes with a serious hit to runtime performance for any rust code (for example stylo and webrender).
... some example tools include instruments on osx (part of xcode), rotateright zoom on linux (uses perf underneath), and intel vtune on windows or linux.
Browser chrome tests
for example, to run the tests in browser/base/content/test the command would be: ./mach mochitest -f browser browser/base/content/test/ or without mach test_path=<path_to_the_tests> make -c <objdir> mochitest-browser-chrome to run tests in debugger the following should work ./mach mochitest -f browser --debugger gdb browser/base/content/test/ run ./mach help mochitest-browser for more options.
... you are adding the first tests in a directory, make sure to also include any head.js you added to support-files, and additionally, ensure that your browser.ini is referenced by a moz.build file somewhere, such as: browser_chrome_manifests += [ 'test/functional/mochitest/browser.ini' ] support-files once added to support-file section of browser.ini support files may be referenced as https://example.com/browser/[path_to_file] or chrome://mochitests/content/browser/[path_to_file].
Creating MozSearch plugins
example: searching yahoo!
... example: searching mdc this plugin lets you easily search the mozilla developer center web site.
Creating Sandboxed HTTP Connections
below is an example: // global channel var gchannel; // init the channel // the io service var ioservice = components.classes["@mozilla.org/network/io-service;1"] .getservice(components.interfaces.nsiioservice); // create an nsiuri var uri = ioservice.newuri(myurlstring, null, null); // get a channel for that nsiuri gchannel = ioservice.newchannelfromuri(uri); // get an listener var l...
... for example, this means that if the user was logged into an webmail account, another account on the same domain could be checked without changing the user's cookies.
Debugging on Windows
you can also redirect the console output to a file (by adding "> filename.txt" for example, without the quotes).
... for example, to print curent javascript stack to stdout, evaluate this in quickwatch window: {,,xul}dumpjsstack() note: visual c++ will show you something in the quick watch window, but not the stack, you have to look in the os console for the output.
Simple Instantbird build
for example, to create a debug build instead of a release build, that file would contain: ac_add_options --enable-debug for more on configuration options, see the page configuring build options.
...for example, a mac user may get an object directory name of obj-x86_64-apple-darwin10.7.3/.
Creating Custom Events That Can Pass Data
for example, if you want firefox to perform an action whenever something happens (i.e., something other than the standard mouse/keyboard events) and, depending on the data passed along with this event, you want firefox to react differently.
... example tbp note for extension developers in order for your event to work the way it is described here it must be derived from nsdomevent.
Tracking Protection
for example, if your site includes a callback that runs when content from a tracking site is loaded, then the callback will not execute.
... for example, you should not use google analytics in the following way: <a href="http://www.example.com" onclick="tracklink('http://www.example.com', event);"> visit example.com </a> <script> function tracklink(url,event) { event.preventdefault(); ga('send', 'event', 'outbound', 'click', url, { 'transport': 'beacon', 'hitcallback': function() { document.location = url; } }); } </script> instead, you should account for the case when google analytics is missing by checking to see if the ga object has initialized: <a href="http://www.example.com" onclick="tracklink('http://www.example.com', event);"> visit example.com </a> <script> function tracklink(url,event) { event.preventdefault(); if (window.ga && ga.loaded) { ga('send', 'event', 'out...
mozbrowsercontextmenu
for example, if the user clicked on an image nested in an <a> tag, two menus are available — one with information related to the image, and one for the link.
... example var browser = document.queryselector("iframe"); browser.addeventlistener("mozbrowsercontextmenu", function(event) { console.log("asking for menu:" + json.stringify(event.details)); }); related events mozbrowserasyncscroll mozbrowserclose mozbrowsererror mozbrowsericonchange mozbrowserloadend mozbrowserloadstart mozbrowserlocationchange mozbrowseropenwindow mozbrowsersecuritychange...
mozbrowseropentab
the mozbrowseropentab event is fired when a new tab is opened within a browser <iframe> as a result of the user issuing a command to open a link target in a new tab (for example ctrl/cmd + click.) general info specification non standard interface customevent bubbles yes cancelable yes target <iframe> default action none properties property type description target read only eventtarget the browser iframe type read only domstring the type of event.
... example var browser = document.queryselector("iframe"); browser.addeventlistener("mozbrowseropentab", function( event ) { console.log("a new document has opened containing the content at " + event.details.url + "."); }); related events mozbrowserasyncscroll mozbrowserclose mozbrowsercontextmenu mozbrowsererror mozbrowsericonchange mozbrowserloadend mozbrowserloadstart mozbrowserlocationcha...
mozbrowserscrollareachanged
this can occur on resize and when the page size changes (while loading for example.) general info specification non standard interface customevent bubbles yes cancelable yes target <iframe> default action none properties property type description target read only eventtarget the browser iframe type read only domstring the type of event.
... example var browser = document.queryselector("iframe"); browser.addeventlistener("mozbrowserscrollareachanged", function( event ) { console.log("the new scroll area is " + event.details.width + " x " + event.details.height + "."); }); related events mozbrowserasyncscroll mozbrowserclose mozbrowsercontextmenu mozbrowsererror mozbrowsericonchange mozbrowserloadend mozbrowserload...
mozbrowservisibilitychange
the mozbrowservisibilitychange event is fired when the visibility state of the current browser iframe <iframe> changes, for example due to a call to setvisible().
... example var browser = document.queryselector("iframe"); browser.addeventlistener("mozbrowservisibilitychange", function( event ) { if(event.details.visible) { console.log("the browser is visible."); } else { console.log("the browser is hidden."); } }); related events mozbrowserasyncscroll mozbrowserclose mozbrowsercontextmenu mozbrowsererror mozbrowsericonchange mozbrowserloadend...
HTMLIFrameElement.sendMouseEvent()
modifiers a number representing a key pressed at the same time the mouse button was clicked: 1 : alt 2 : ctrl 4 : shift 8 : meta 16 : alt gr 32 : caps lock 64 : fn 128 : num lock 256 : scroll 512 : symbol lock 1024 : win note: you can specify multiple key modifiers separated by a pipe symbol, for example 1 | 1014.
... 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()
modifiers a number representing a key pressed at the same time the mouse button was clicked: 1 : alt 2 : ctrl 4 : shift 8 : meta 16 : alt gr 32 : caps lock 64 : fn 128 : num lock 256 : scroll 512 : symbol lock 1024 : win note: you can specify multiple key modifiers separated by a pipe symbol, for example 1 | 1014.
... 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()
as an example, if the content of a browser <iframe> uses the window.requestanimationframe method and if the visible state is set to true, window.requestanimationframe will be called as often as necessary.
... examples var browser = document.queryselector('iframe'); browser.setvisible(true); specification not part of any specification.
HTMLIFrameElement.zoom()
MozillaGeckoChromeAPIBrowser APIzoom
it acts like a percentage, so for example 1.1 would zoom in by 10%, whereas 0.9 would zoom out by 10%.
... 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.
MozBeforePaint
example this example performs a simple animation, moving a box a short distance after a short period of time.
... you may take a look at this example live if you like.
Getting from Content to Layout
to give a trivial example of when this might be necessary, consider: "<span>foo <div></div> bar</span>".
... examples of this type of code are in wipecontainingblock.
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.
How Mozilla determines MIME Types
this means that, for example, if mozilla encounters a <link type="text/css" rel="stylesheet" href="..."> element, a type of text/css will be assumed.
...(for this specific example, the server override only happens in standards-compliant mode.
IPDL Best Practices
a good example of this problem is the amount of memory management bugs that we have had with using surfacedescriptor directly everywhere.
... use a flag and the generated actordestroy function to control when ipdl functions can be called; see phttpchannelparent/child for an example.
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** a...
...iter, 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.
Add-on Manager
for example: components.utils.import("resource://gre/modules/addonmanager.jsm"); addonmanager.getalladdons(function(aaddons) { // here aaddons is an array of addon objects }); // this code will execute before the code inside the callback notifications about changes to installed add-ons are dispatched to any registered addonlisteners.
... for example, to take a look at the add-ons that were disabled at startup: components.utils.import("resource://gre/modules/addonmanager.jsm"); let addonids = addonmanager.getstartupchanges(addonmanager.startup_change_disabled); if (addonids.length > 0) { // addonids is now an array of the add-on ids that have been disabled alert("note: " + addonids.length + " add-ons have been disabled."); } open add-on...
Dict.jsm
examples creating and populating a dictionary this example creates a new dictionary and adds some key/value pairs to it.
... var mydict = new dict(); mydict.set("name", "john smith"); mydict.set("email", "jsmith@example.com"); mydict.set("phone", "650-555-1234"); working with existing keys you can then check to see if a given key exists: if (mydict.has("email")) { /* an "email" key exists on the object */ } ...
Download
contenttype string the mime type of the download, for example "text/plain", or null if the mime type is not available.
...you should use the individual state properties (for example, the succeeded property) instead.
NetUtil.jsm
example this example writes a string to a file; it comes from the test suite for the netutil module.
... example this example shows the basic code consumers would need to implement to be correct.
OS.File.Info
using os.file.info example: determining if a file is a regular file the following snippet uses the main thread api to determine (asynchronously) whether some path is a regular file, or a directory, or a symbolic link: let promise = os.file.stat(somepath); promise.then( function onsuccess(info) { // |info| is an instance of |os.file.info| if (info.isdir) { // |somepath| represents a directory } else if (in...
...fo.issymlink) { // |somepath| represents a symbolic link } else { // |somepath| represents a regular file } }, function onfailure(reason) { if (reason instanceof os.file.error && reason.becausenosuchfile) { // |somepath| does not represent anything } else { // some other error } } ) example: determining the owner of a file let promise = os.file.stat() promise.then( function onsuccess(info) { if ("unixowner" in info) { // info.unixowner holds the owner of the file } else { // information is not available on this platform } } ); evolution of this example bug 802534 will introduce the ability to check whether field unixowner appears in os.file.info.prototype, which will make it possible to write faster code.
Deferred
for example, the equivalent of var deferred = promise.defer(); dosomething(function cb(good) { if (good) deferred.resolve(); else deferred.reject(); }); return deferred.promise; would be return new promise(function(resolve, reject) { dosomething(function cb(good) { if (good) resolve(); else reject(); }); }); method overview void resolve([optional] avalue); void rej...
... function deferred() { // update 062115 for typeof if (typeof(promise) != 'undefined' && promise.defer) { //need import of promise.jsm for example: cu.import('resource:/gree/modules/promise.jsm'); return promise.defer(); } else if (typeof(promiseutils) != 'undefined' && promiseutils.defer) { //need import of promiseutils.jsm for example: cu.import('resource:/gree/modules/promiseutils.jsm'); return promiseutils.defer(); } else { /* a method to resolve the associated promise with the value passed.
Timer.jsm
the timer.jsm javascript code module contains pure-javascript implementations of settimeout, cleartimeout, setinterval, and clearinterval that are compatible with the dom window functions, but that can be used by code that does not have access to a dom window (for example, javascript code modules or content frame scripts).
... to use timer.jsm, first import it: components.utils.import("resource://gre/modules/timer.jsm"); then call settimeout and cleartimeout just as you would in a dom window, for example: let timeoutid = settimeout(function() { console.log("hello!"); }, 500); cleartimeout(timeoutid); similarly, you can use setinterval and clearinterval like so: let intervalid = setinterval(function() { console.log("happening every 500ms!"); }, 500); clearinterval(intervalid); ...
JavaScript code modules
for example, a module could be used by firefox itself as well as by extensions, in order to avoid code duplication.
... code snippets: modules examples of how to use code modules.
Bootstrapping a new locale
untrusted connection in the example above), like so (example for polish): <!entity certerror.pagetitle "niezaufane połączenie"> once you have translated all the <!entity> strings in this file, you should save your work and open the next .dtd or .property file.
...this is why you need to do hg push, which sends the already made commits to the remote repository (http://bitbucket.org/mozillal10n/ab-cd/ in the example above).
Release phase
here's how that's done: run this command to see recent commits in your local clone: $ hg log -l 3 you should a list of the most recent commits, similar to this one: changeset: 0:7c543e8f3a6a tag: tip user: your name <email@example.com> date: mon nov 23 18:08:25 2009 +0100 summary: added search bar strings now run the hg outgoing command to compare the local repository on your machine with the remote repository on hg.mozilla.org.
...the output will look something like this: comparing with ssh://hg.mozilla.org/releases/l10n-central/x-testing searching for changes changeset: 0:7c543e8f3a6a tag: tip user: your name <email@example.com> date: mon nov 23 18:08:25 2009 +0100 summary: added search bar strings make sure this output is accurate before continuing.
MathML3Testsuite
this exception also holds for obsolete features (such as macro, mode etc) or for other undefined behaviors (attribute href for example).
... characters blocks symbols variants entitynames numericrefs utf8 general clipboard genattribs math presentation css dynamicexpressions generallayout scriptsandlimits tablesandmatrices tokenelements topics accents bidi elementarymathexamples 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 Demo: <mfrac> - fractions
inline, styles auto, display and text 1 2 - 1 2 + 1.23456 7890 , the rendering should be script-size, normal-size and script-size in this example.
... and this is an example where the bevelled attribute is set inside the radical y 2 - t 2 1 ( 1 + | y 2 - t 2 | 2 ) and this shows a combination with a background image at a desired opacity mathml background image html content <div class="background"></div> <math display="block"> <mrow> <msub> <mi>z</mi> <mi>&alpha;</mi> </msub> <mrow> <mo>(</mo> <mi>f</mi> ...
MathML Demo: <mmultiscripts> - attach prescripts and tensor indices to a base
for example m c d a b .
...for example m c d a b the scripts come in pairs, with <mprescripts/> used to indicate prescripts and <none/> used to hold an empty position as in f b a there are some variations possible: <mmultiscripts> a a b c d nested <msubsup>s a a b c d or &invisiblecomma; a a ⁣ c b ⁣ d ...
TimerFirings logging
the above example shows only timers from c++ within gecko.
... it is sometimes useful to pre-process the output by stripping out certain parts of each line before doing this aggregation step, for example, by inserting one or more of the following commands into the command pipeline.
powermetrics
the following is example output from such an invocation: *** sampled system activity (fri sep 4 17:15:14 2015 +1000) (5009.63ms elapsed) *** *** running tasks *** name id cpu ms/s user% deadlines (<2 ms, 2-5 ms) wakeups (intr, pkg idle) gpu ms/s com.apple.terminal 293 447.66 274.83 120.35 221.74 firefox ...
...for example, firing a single sub-2ms deadline can also cause a package idle exit wakeup.
A brief guide to Mozilla preferences
preference conflicts are resolved in favor of the last entry; for example, user.js takes precedence over prefs.js .
...for example, let's assume that nightly has a preference "some.preference" which defaults to true while developeredition defaults the same preference to false and the user desires the preference to have the value true in both channels.
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"...
...example: var features = "chrome,titlebar,toolbar,centerscreen,modal"; window.opendialog(url, "preferences", features); bugzilla the component for bugs in the preferences bindings (but not in firefox/thunderbird options ui) is toolkit:preferences (file a bug list open bugs) ...
Profile Manager
to use profile manager with an application other than firefox, you need to launch it using the application's name as an argument, for example: profilemanager-bin seamonkey profiles and application versions profile manager manages two different lists: one of user profiles, and the other of application versions that can be used with the profiles.
... for example, profilea might be linked with a copy of firefox 3.6.10, while profileb might be linked with a copy of firefox 3.5.3.
Midas editor module security preferences
for example: user_pref("capability.policy.allowclipboard.sites", "http://www-archive.mozilla.org") is not the same as: user_pref("capability.policy.allowclipboard.sites", "https://www-archive.mozilla.org") this is because the first uses http while the second uses https.
...for example: user_pref("capability.policy.allowclipboard.sites", "https://www-archive.mozilla.org https://developer.mozilla.org") again, keep in mind the security risks involved here and be sure to remove permission to access the clipboard once you no longer need it enabled.
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.
...an example of the differences is that the "bold" command will generate <b> if the stylewithcss command is false and generate css style attribute if the stylewithcss command is true.
NSPR build instructions
build the libraries build the test programs for example, # check out the source tree from mercurial hg clone https://hg.mozilla.org/projects/nspr # create a build directory mkdir target.debug cd target.debug # run the configure script ../nspr/configure [optional configure options] # build the libraries gmake # build the test programs cd pr/tests gmake on mac os x, use make, which is gnu make.
... if the os vendor provides a compiler (for example, sun and hp), nspr uses that compiler instead of gcc by default.
Anonymous Shared Memory
see the examples below.
...in the examples, the server creates the file-mapped shared memory, the client attaches to it.
Logging
conditional compilation and execution log types and variables logging functions and macros use example conditional compilation and execution nspr's logging facility is conditionally compiled in and enabled for applications using it.
... the behavior of logging at execution time: nspr_log_modules nspr_log_file logging functions and macros the functions and macros for logging are: pr_newlogmodule pr_setlogfile pr_setlogbuffering pr_logprint pr_logflush pr_log_test pr_log pr_assert pr_assert pr_static_assert (new in nspr 4.6.6xxx this hasn't been released yet; the number is a logical guess) pr_not_reached use example the following sample code fragment demonstrates use of the logging and debugging aids.
PRTimeParameters
for example, the us pacific time zone has both a standard time zone (pacific standard time, or pst) and a daylight time zone (pacific daylight time, or pdt).
... a second example is japan, which is 9 hours ahead of gmt.
Function_Name
avoid describing the return until the next section, for example: this function looks in the nsscryptocontext and the nsstrustdomain to find the certificate that matches the der-encoded certificate.
... returns full description of the return value, for example: a pointer to a certcertificate representing the certificate in the database that matched the dercert, or null if none was found.
CERT_FindCertByIssuerAndSN
syntax #include <cert.h> certcertificate *cert_findcertbyissuerandsn ( certcertdbhandle *handle, certissuerandsn *issuerandsn ); parameters handle in pointer to a certcertdbhandle representing the certificate database to look in issuerandsn in pointer to a certissuerandsn that must be properly formed to contain the issuer name and the serial number (see [example]) description this function creates a certificate key using the issuerandsn and it then uses the key to find the matching certificate in the database.
... example certissuerandsn issuersn; issuersn.derissuer.data = caname->data; issuersn.derissuer.len = caname->len; issuersn.serialnumber.data = authoritykeyid->authcertserialnumber.data; issuersn.serialnumber.len = authoritykeyid->authcertserialnumber.len; issuercert = cert_findcertbyissuerandsn(cert->dbhandle, &issuersn); if ( issuercert == null ) { port_seterror (sec_error_unknown_issuer); } see also occurrences of cert_findcertbyissuerandsn in the current nss source code (generated by lxr).
JSS FAQ
MozillaProjectsNSSJSSJSS FAQ
jss example code is essentially developer test code; with that understanding, the best directory to look for sample code is in the org/mozilla/jss/tests directory: http://lxr.mozilla.org/mozilla/source/security/jss/org/mozilla/jss/tests org/mozilla/jss/tests/closedbs.java org/mozilla/jss/tests/keyfactorytest.java org/mozilla/jss/tests/digesttest.java org/mozilla/jss/tests/jcasigtest...
... 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/...
Using JSS
MozillaProjectsNSSJSSUsing JSS
for example, the nspr library is called nspr4.dll or libnspr4.dll on windows and libnspr4.so on solaris.
...for example, although jss 4.2 was tested with nss 3.11.
NSS Sample Code Sample_2_Initialization of NSS
nss sample code 2: initializing nss this example program demonstrates how to initialize the nss database.
...pw(slot, oldpw, newpw) != secsuccess) { pr_fprintf(pr_stderr, "failed to change password.\n"); return secfailure; } port_memset(oldpw, 0, pl_strlen(oldpw)); port_free(oldpw); pr_fprintf(pr_stdout, "password changed successfully.\n"); } port_memset(newpw, 0, pl_strlen(newpw)); port_free(newpw); return secsuccess; } /* * this example illustrates initialization of the nss database.
NSS Sample Code Sample_3_Basic Encryption and MACing
nss sample code 3: basic encryption and macing this example program demonstrates how to encrypt and mac a file.
... goto cleanup; } } cleanup: if (infile) { pr_close(infile); } if (headerfile) { pr_close(headerfile); } if (encfile) { pr_close(encfile); } if (slot) { pk11_freeslot(slot); } if (enckey) { pk11_freesymkey(enckey); } if (mackey) { pk11_freesymkey(mackey); } return rv; } /* * this example illustrates basic encryption/decryption and macing.
NSS Sample Code sample5
nss sample code 5: pki encryption with a raw public & private key in der format /* example code to illustrate pki crypto ops (encrypt with public key, * decrypt with private key) * * no nss db needed.
... * * there is no attempt to link the public & private key together * * this example does not do any padding.
EncDecMAC using token object - sample 3
encdecmac using token object example: <h2 id="nss_sample_code_3_hashing.">nss sample code 3: enc/dec/mac using token object id.</h2> <p class="summary">computes the hash of a file and saves it to another file, illustrates the use of nss message apis.</p> <pre class="brush: cpp"> /* this source code form is subject to the terms of the mozilla public * license, v.
...key, ivitem.data, ivitem.len, ascii); if (rv != secsuccess) { pr_fprintf(pr_stderr, "failed : macing and encryption\n"); goto cleanup; } } cleanup: if (infile) { pr_close(infile); } if (headerfile) { pr_close(headerfile); } if (encfile) { pr_close(encfile); } if (slot) { pk11_freeslot(slot); } if (enckey) { pk11_freesymkey(enckey); } if (mackey) { pk11_freesymkey(mackey); } return rv; } /* * this example illustrates basic encryption/decryption and macing * generates the encryption/mac keys and uses token for storing.
NSS sources building testing
however, all these tools are good examples of how to write software that makes use of the nss library.
...in other environments (for example in home networks), you could set the host and domsuf (for domain suffix) environment variables to tell the nss suite which hostname to use.
nss tech note6
if your build process modifies nss libraries in any way (for example, to strip the symbols), it should consider not doing so for the reasons cited above.
... for example, on 32-bit solaris sparc for nss 3.11, say shlibsign -v -i libsoftokn3.so shlibsign -v -i libfreebl_32int64_3.so shlibsign -v -i libfreebl_32fpu_3.soshlibsign -v -i libfreebl_32int_3.so (you need to set ld_library_path appropriately and specify the correct pathnames of the libraries.) option 1 is simpler and highly preferred.
nss tech note7
for example, if you just need to generate or verify a signature, you can use the sgn_ and vfy_ functions in cryptohi.h.
...for example, 0x00123456 is equal to 0x123456.
Overview of NSS
rsa standard that governs password-based cryptography, for example to encrypt private keys for storage.
...rsa standard that governs the application of cryptography to data, for example digital signatures and digital envelopes.
FC_GetInfo
libraryversion: pkcs #11 library version number, for example, 3.11 (major=0x03, minor=0x0b).
... examples note the use of the %.32s format string to print the manufacturerid and librarydescription members of the ck_info structure.
FC_GetTokenInfo
ulsessioncount: number of sessions that this application currently has open with the token ulrwsessioncount: number of read/write sessions that this application currently has open with the token hardwareversion: hardware version number, for example, 8.3 (major=0x08, minor=0x03), which are the version numbers of the certificate and key databases, respectively.
... examples note the use of the %.32s format string to print the label and manufacturerid members of the ck_token_info structure.
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_init...
NSS tools : crlutil
-p dbprefix specify the prefix used on the nss security database files (for example, my_cert8.db and my_key3.db).
...for example: 20050204153000z * add an extension to a crl or a crl certificate entry: addext extension-name critical/non-critical [arg1[arg2 ...]] where: extension-name: string value of a name of known extensions.
gtstd.html
a pkcs #11 module always has one or more slots, which may be implemented as physical hardware slots in some form of physical reader (for example, for smart cards) or as conceptual slots in software.
... for complete information about the command-line options used in the examples that follow, see using the certificate database tool.
pkfnc.html
for example, communicator uses the parameter to pass information about which window is associated with the modal dialog box requesting the password from the user.
... see also for examples of password callback functions, see the samples in the samples directory.
sslerr.html
ssl_error_no_certificate -12285 "unable to find the certificate or key necessary for authentication." this error has many potential causes; for example: certificate or key not found in database.
...for example, a server received a message from another server.
NSS tools : crlutil
MozillaProjectsNSStoolscrlutil
-p dbprefix specify the prefix used on the nss security database files (for example, my_cert8.db and my_key3.db).
...for example: 20050204153000z * add an extension to a crl or a crl certificate entry: addext extension-name critical/non-critical [arg1[arg2 ...]] where: extension-name: string value of a name of known extensions.
Necko Architecture
for example, the http protocol handler registers itself as the protocol handler for "http." the http protocol handler creates http channels for http urls.
...please use existing protocol handler's for reference (the data: protocol handler is the simplest handler necko provides, http is a fairly complex (uses many classes) implementation utilizing asynchronous i/o, and ftp provides an example of a protocol implementation that creates an extra thread which uses synchronous i/o).
Rhino overview
see the enum.js example for more information.
... array.prototype.tostring and object.prototype.tostring version 1.2 only returns array or object literal notation ("[1]" or "{a:1, b:2}" for example).
Rebranding SpiderMonkey (1.8.5)
for example the default brand for spidermonkey 1.8.5 is 'mozjs185'.
...for example: ../configure --enable-ctypes --with-system-nspr note: your desired configuration may be different.
Garbage collection
for example, fields of type jsobject* need a write barrier, so there is a function jsobject::writebarrierpre(jsobject* old).
...in this example, if the private field is overwritten, the jsobject pointers could be 'lost', so a write barrier must be invoked to mark them.
Self-hosted builtins in SpiderMonkey
you can not, for example, use function.prototype.apply directly.
...example: js_self_hosted_fn("foreach", "arrayforeach", 1,0) this causes the self-hosted function arrayforeach to be installed as the host object's method foreach.
JS::Add*Root
(for example, it must not be an uninitialized local variable.
... needs the example for typical usage of the name parameter.
JSObjectPrincipalsFinder
for example, when a watchpoint triggers, the engine calls the callback, passing the watchpoint handler, to ensure that watchpoint handlers are invoked only when the watcher is permitted to watch the currently executing script.
... another example: when the function constructor is called, the javascript engine calls the object principals finder callback to obtain principals for the local scope object, to check that the caller has access to that object.
JSPropertyDescriptor
examples the following example demonstrates how to use the object.defineproperty() function to create a property under an object in a javascript via a descriptor.
... var language = {}; // define an empty object language object.defineproperty(language, 'log', { // define the log attribute under the language object value : ['cn','en'], writable : true, enumerable : true, configurable : true }) in the above example we defined a writable, deletable enumerable property.this is the same as the javascript directly defined property.
JSPropertyOp
getters and setters when a jsapi application creates a property on an object (for example, using js_defineproperty or js_defineproperties) it can specify getter and setter callbacks for the new property.
...this ecmascript incompatibility is observable when assigning to the length property of an array, for example.
JS_DefinePropertyWithTinyId
for example, if a property named "color" is defined with tiny id 10, then the javascript expressions obj[10] and obj.color will both result in int_to_jsval(10) being passed to jsclass.getproperty as the id parameter.
... per-property getters and setters do not suffer from this confusion: in the above example, obj.color would cause the javascript engine to call the getter for the color property, but obj[10] wouldn't.
JS_DumpNamedRoots
example static void dumproot(const char *name, void *addr, void *data) { /* the application may use `data` for anything.
... in this example, we use it to pass the desired output file.
JS_FS
for example, use js_sym_fn(iterator, ...) to define an @@iterator method.
... (in builds without es6 symbols, it defines a method with the string id "@@iterator".) see an example in the jsapi user guide.
JS_InitClass
so, for example, if this object is js_getglobalobject(cx), then javascript code will be able to see the new class as a global name.
...this inconsistency can cause problems; for example, if the finalizer calls js_getprivate(), expecting that the constructor called js_setprivate(), it may find that the private data is null.
JS_THREADSAFE
for each thread that is in a request: almost any call into the jsapi may trigger garbage collection; but garbage collection does not happen at any other time (such as, for example, at the moment before the return value of js_newobject is assigned to a rooted variable).
...for example: many worker threads need to share a "pool" of reusable contexts, to avoid the performance cost of constantly creating and destroying contexts.
SavedFrame
for example, if this frame’s children are calls to handlers for a promise this frame created, this frame’s asynccause would be "promise".
... asyncparent if this stack frame was called as a result of an asynchronous operation, for example if the function referenced by this frame is a promise handler, this property points to the stack frame responsible for the asynchronous call, for example where the promise was created.
TPS Pref Lists
for example: var prefs1 = [ { name: "browser.startup.homepage", value: "http://www.getfirefox.com" }, { name: "browser.urlbar.maxrichresults", value: 20 }, { name: "browser.tabs.autohide", value: true } ]; pref lists and phase actions the only actions supported for preference asset lists are modify and verify: prefs.modify prefs.verify sync only syncs certain preferences.
... for a more detailed test example, see the tps prefs unit test.
TPS Tab Lists
for example: var tabs1 = [ { uri: "http://hg.mozilla.org/automation/crossweave/raw-file/2d9aca9585b6/pages/page1.html", title: "crossweave test page 1", profile: "profile1" }, { uri: "data:text/html,<html><head><title>hello</title></head><body>hello</body></html>", title: "hello", profile: "profile1" } ]; tab lists and phase actions tabs cannot be modified or deleted, only added or verified with the following functions: tabs.add - opens the specified tabs in the browser window.
... example see the tps tabs unit test: http://hg.mozilla.org/services/tps/f...s/test_tabs.js ...
Setting up an update server
for example, if you want the nightly mar from 2019-09-17 for a 64 bit windows machine, you probably want the mar located at https://archive.mozilla.org/pub/firefox/nightly/2019/09/2019-09-17-09-36-29-mozilla-central/firefox-71.0a1.en-us.win64.complete.mar.
...here is an example of an appropriate mar file to use: https://archive.mozilla.org/pub/firefox/releases/69.0b9/update/win64/firefox-69.0b9.complete.mar.
Frecency algorithm
examples of invalid places are "place:" queries, and unvisited livemark feed entries.
...points for each sampled visit = (bonus / 100.0) * weight final frecency score for visited uri = ceiling(total visit count * sum of points for sampled visits / number of sampled visits) example this is an example of a frecency calculation for a uri that is bookmarked and has been visited twice recently (once yesterday, and once last week by clicking a link), and two other times more than 90 days ago: 0 default score +140 100 * (140/100.0) - first bucket weight and bookmarked bonus +84 70 * (120/100.0) - second bucket weight and followed-link bonus ...
Places utilities for JavaScript
for example, given a uri, the traditional code to get all its annotations would be: var annotationservice = components.classes["@mozilla.org/browser/annotation-service;1"] .getservice(components.interfaces.nsiannotationservice); try { var names = annotationservice.getpageannotationnames(uri); } catch(e) { // no annotations } var annotations = new array(); for(var i in names) { try { a...
...it also gives you more information that my hastily written (and probably incorrect) example up above.
Using the Places history service
when the user starts browsing (for example, by typing in a link or following a bookmark), a new session id is created.
... advanced querying see querying places for more detailed examples on how to used the advanced querying functionality of navhistory.
Using the Places keywords API
placesutils.keywords.insert({ keyword: "my_keyword", url: "http://www.example.com/" postdata: "post+data=1&test=2" }).then(() => { /* success */ }, e => { /* failure */ }); note that setting an already existing keyword to a different url, will silently update the existing keyword to the new url.
... placesutils.keywords.fetch({ url: "http://www.example.com/" }, entry => { /* invoked for each found keyword entry */ }) .then(oneentry => { /* oneentry is either null, or one of the keyword entries */ }, e => { /* failure */}); removing a keyword the remove() method accepts a keyword string.
Aggregating the In-Memory Datasource
for example, while writing the bookmarks datasource, i wanted to be able to trap assert() to enforce the bookmarks datasource would only accept "bookmarks related" assertions.
...for example: ns_imethodimp myclass::dosomething() { nscomptr<nsirdfdatasopurce> ds = do_queryinterface(minner); rv = ds->assert(/* something useful here */); // etc...
Creating a Python XPCOM component
for example: xpidl.exe -m typelib -w -v -i c:\source\mozilla\obj-i686-pc-mingw32\dist\idl foo.idl xpidl will then create nsipysimple.xpt, which should be placed correctly (e.g., in the 'components' directory).
...for example: % cd c:\mozilla\bin\python\xpcom % python xpt.py nsisample class nsisample: _com_interfaces_ = xpcom.components.interfaces.nsisample # if this object needs to be registered, the following 2 are also needed.
Generic factory
examples class nsicomponent : public nsisupports { public: ns_imethod dosomething() = 0; }; class mycomponent : public nsicomponent { public: mycomponent(); virtual ~mycomponent(); static ns_method create(nsisupports *aouter, refnsiid aiid, void **aresult); ns_impl_isupports ns_imethod dosomething(); }; to create a factory for this class, simply write the following: nsifactory* newcom...
...ponentfactory(nsirepository* repository) { nsigenericfactory* factory = null; nscid kgenericfactorycid = ns_genericfactory_cid; nsresult res = repository->createinstance(kgenericfactorycid, null, nsigenericfactory::iid(), &factory); if (res == ns_ok) { factory->setconstructor(&mycomponent::create); } return factory; } this example assumes that the xpcom repository is available as an interface (which it soon will be).
Making cross-thread calls using runnables
for example, let's say we have a function, calculatepi(int digits), which will calculate π to an arbitrary number of digits: void calculatepi(int digits, nscstring& result); // this is synchronous this can take a while, so we don't want to run this on the main thread.
...in our example, we actually need two runnables: one dispatched to the worker thread, and one to hand us back the result.
Inheriting from implementation classes
example problem you have interfaces a and b, b inherits from a, and you have implementation classes for both a and b, and you want the implementation class for b to inherit from the implementation class for a.
...} example solution a.h, as usual: class a : public ia { ...
Receiving startup notifications
sometimes it's necessary for xpcom components to receive notifications as to the progress of the application's startup process, so they can start new services at appropriate times, for example.
...for example: category profile-after-change mycomponent @foobar/mycomponent;1 important: in the past, the contract id of the category entry started with "service," if the component was implemented as a service.
How to build a binary XPCOM component using Visual Studio
for example, xulrunner 1.8.0.4 which has a pre-built sdk at gecko-sdk-win32-msvc-1.8.0.4.zip.
...ok then, on with the basic, oversimplified example.
Components.utils.createObjectIn
for example, to create a new object in the compartment identified by contentwindow: var newobject = new contentwindow.object(); but it is really needeed from firefox 30 onwards when trying to manipulate the dom window.
... example to create a new object in the scope of a specified dom window, you can simply do: function genpropdesc(value) { return { enumerable: true, configurable: true, writable: true, value: value }; } var myobject = components.utils.createobjectin(mywindow); var proplist = { name: genpropdesc("name"), date: genpropdesc("date"), id: genpropdesc("id"), func: genpropdesc(function() { ale...
Components.utils.isXrayWrapper
for example, privileged code using an xray to a dom object sees only the original, native version of the dom object.
...example var isxray = components.utils.isxraywrapper(gbrowser.contentwindow); // true var waived = components.utils.waivexrays(gbrowser.contentwindow); isxray = components.utils.isxraywrapper(waived); // false ...
Components.utils.unwaiveXrays
for example, if privileged code accesses a dom object belonging to web content, it will by default see it using xray vision, meaning that among other things expando properties added to the object by content are not visible.
...example suppose a page script adds an expando to its global window: // page script foo = "i'm an expando"; by default, chrome code won't see foo, because it sees the content window with xray vision, but the chrome code can waive xray protection.
PyXPCOM
pyxpcom is actively used in activestate komodo products, for example.
... creating a python xpcom component an example of how to create a simple xpcom component with python.
XPConnect wrappers
note: wrappers can appear in the console log; for example "[object xraywrapper [object blah]]".
...for example, if you've implemented some component with an interface nsifoo and you pass your javascript object into a c++ function taking an nsifoo, an xpcwrappedjs is created around your object.
NS_NewLocalFile
example code // create a local file that references c:\foo.txt nsresult rv; nscomptr<nsilocalfile> file; rv = ns_newlocalfile(nsembedstring(l"c:\\foo.txt"), pr_false, getter_addrefs(file)); if (ns_failed(rv)) return rv; note: gcc requires the -fshort-wchar option to compile this example since prunichar is an unsigned short.
... this example should compile by default under msvc.
RefPtr
for example, we have template classes such as owningnullptr that can contain a refptr to an xpcom interface.
... note: in the above example, "nscomptr<nsfoo>" might compile and work ok (it won't if your xpcom class multiply-inherits nsisupports).
IAccessible2
an example of when this value is useful is if the at wants to build a cache.
...another use of this value by an at is to identify when a grouping object has changed, for example when moving from a radio button in one group to a radio button in a different group.
nsIAccessNode
language domstring the language for the current dom node, for example en, de, and so on.
... propertyname retrieve the computed style value for this property name, for example "border-bottom".
nsIAccessible
relations many accessibles are linked with each other, for example, if one accessible gives the accessible name for another accessible (for example, html:label and html control) then these accessibles are related, please refer to relations documentation for more information.
...actions you can prepare actions on some accessibles (for example on button accessible).
nsIAccessibleEvent
this includes for example most of the attributes available via the iaccessiblecomponent interface.
... example to listen to in-process accessibility invents, make your object an nsiobserver, and listen for accessible-event by using code something like this: nscomptr<nsiobserverservice> observerservice = do_getservice("@mozilla.org/observer-service;1", &rv); if (ns_succeeded(rv)) { rv = observerservice->addobserver(this, "accessible-event", pr_true); } ...
nsIAccessibleProvider
for example now it is used by <xul:iframe>, <xul:browser> and <xul:editor>.
...for example, a select1 in a xhtml document may be represented by the native html control html:select.
nsIAccessibleTable
for example, html:caption element of html:table element.
...for example, @summary attribute on html:table element.
nsIAppStartup
this can be used, for example, when doing performance testing of the startup process to discount numbers for tests that were interrupted by a user prompt.
... example this example logs startup time information to the console.
nsIAuthModule
void getnexttoken( [const] in voidptr aintoken, in unsigned long aintokenlength, out voidptr aouttoken, out unsigned long aouttokenlength ); parameters aintoken a buffer containing the input token (for example a challenge from a server).
...void init( in string aservicename, in unsigned long aserviceflags, in wstring adomain, in wstring ausername, in wstring apassword ); parameters aservicename the service name, which may be null if not applicable (for example, for ntlm, this parameter should be null).
nsICachingChannel
for example a http form submission.
...for example, expiration time.
nsICommandLine
some flags may take parameters; for example: "-url <param>" or "-install-xpi <param>".
... preventdefault boolean there may be a command-line handler which performs a default action if there was no explicit action on the command line (open a default browser window, for example).
nsICompositionStringSynthesizer
to create an instance for this: var domwindowutils = window.windowutils; var compositionstringsynthesizer = domwindowutils.createcompositionstringsynthesizer(); for example, when you create a composition whose composing string is "foo-bar-buzz" and "bar" is selected to convert, then, first, you need to start composition: domwindowutils.sendcompositionevent("compositionstart", "", ""); next, dispatch composition string with crause information and caret information (optional): // set new composition string with .setstring().
...for example, if the "bar" is converted to "bar": compositionstringsynthesizer.setstring("foo-bar-buzz"); compositionstringsynthesizer.appendclause("foo-".length, compositionstringsynthesizer.attr_convertedtext); compositionstringsynthesizer.appendclause("bar".length, compositionstringsynthesizer.attr_selectedconvertedtext); compositionstringsynthesizer.appendclause("-buzz".length, compositionstringsynthe...
nsIDOMEvent
for example, mouse events are retargeted to their parent node when they happen over text nodes (bug 185889), and in that case .target will show the parent and .explicitoriginaltarget will show the text node.
...examples of epoch time are the time of the system start or 0:0:0 utc 1st january 1970.
nsIDOMHTMLSourceElement
example <video controls> <source src="foo.webm" type="video/webm; codecs=&quot;vp9, opus&quot;"> your browser does not support the <code>video</code> element.
... </video> this example specifies that a video object with playback controls should be drawn, playing the file "foo.ogg".
nsIDOMMozNetworkStatsManager
you can test for the presence of the service as follows, for example: if ("moznetworkstats" in navigator) { /* networkstats is available */ } else { alert("i'm sorry, but networkstats services are not supported."); } method overview nsidomdomrequest getsamples(in nsisupports network, in jsval start, in jsval end, [optional] in jsval options /* networkst...
... for example, this object might be { appmanifesturl : manifesturl }.
nsIDownloadManager
useful if, for example, you want the window to select a certain download.
... startbatchupdate() obsolete since gecko 1.9.1 (firefox 3.5 / thunderbird 3.0 / seamonkey 2.0) indicate that a batch update (for example mass removal) is about to start.
nsIDownloadProgressListener
onsecuritychange() called when the level of security being used while downloading changes; for example, if the initial request is made via https but the download switches to http, this function gets called to notify you of that transition.
... example var dm = components.classes["@mozilla.org/download-manager;1"] .getservice(components.interfaces.nsidownloadmanager); dm.addlistener({ onsecuritychange : function(prog, req, state, dl) { }, onprogresschange : function(prog, req, prog, progmax, tprog, tprogmax, dl) { }, onstatechange : function(prog, req, flags, status, dl) { }, ondownloadstatechange : function(state, dl) { } })...
nsIFileView
setfilter() set the filter to be applied to the file list, for example "*.jpg" would only return jpg files.
... example <?xml version="1.0" ?> <?xml-stylesheet href="chrome://global/skin/" type="text/css" ?> <window id="test" title="test" width="640" height="480" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <tree flex="1" id="ftree"> <treecols> <-- the default column type is size unless an appropriate id is passed, nsifileview relies on the treecols section --> <treecol id="filenamecolumn" label=...
nsIIdleService
example example 1 var idleservice = components.classes["@mozilla.org/widget/idleservice;1"] .getservice(components.interfaces.nsiidleservice) settimeout(function() { alert(idleservice.idletime) }, 1000) // if you don't use the mouse or the keyboard after running this snippet, // you'll see a number around 1000 alerted.
... example 2 var idleservice = components.classes["@mozilla.org/widget/idleservice;1"] .getservice(components.interfaces.nsiidleservice) var idleobserver = { observe: function(subject, topic, data) { alert("topic: " + topic + "\ndata: " + data); } }; idleservice.addidleobserver(idleobserver, 60); // one minute // ...
nsIInstallLocation
getstagefile() returns the most recently staged package (for example the last xpi or jar in a directory) for an item and removes items that do not qualify.
...for example, items linked to by text links are managed by the user, and items linked to from registry install locations are usually managed by other applications or installers.
nsILoginInfo
for logins obtained from html forms, this field is the action attribute from the form element, with the path removed (for example, "https://www.site.com").
... hostname astring the origin, not hostname, to which the login applies (for example, "https://www.site.com").
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:<...
.../label> <input type="password" name="pword"> </form> creating a site authentication login var authlogininfo = new nslogininfo( 'http://www.example.com', null, 'exampleco login', 'alice', 'secret321', "", "" ); this would correspond to a login on http://www.example.com when the server sends a reply such as: http/1.0 401 authorization required server: apache/1.3.27 www-authenticate: basic realm="exampleco login" creating a local extension login var extlogininfo = new nslogininfo( 'chrome://firefoo', null, 'user registration', 'bob', '123secret', "", "" ); from a component creating a new info block is done slightly differently: var nslogininfo = new constructor("@org/manager/ci.init"); var extlogininfo = new aformsubmiturl, ausername, ausernamefield, ...
nsIMsgIncomingServer
constructedprettyname astring helper function to construct the pretty name in a server type specific way - for example, mail for foo@test.com, news on news.mozilla.org.
...please look at mozilla/mailnews/base/ispdata/aol.rdf for usage example.
nsINavBookmarksService
for example, if i bookmark "mozilla.org" by manually typing it in, and follow the bookmark, i will get redirected to "www.mozilla.org".
...use this when a lot of things are about to change, for example adding or deleting a large number of bookmark items.
nsINavHistoryContainerResultNode
when the container is closed, the result is an exact answer if the node can be populated easily (for example, for bookmark folders).
... if it can't be populated easily (for complex history queries, for example), the result is always true.
nsINavHistoryResultObserver
this is especially useful when updating user interfaces, to avoid flicker or continuous selection changes, which may result in performance degradation (for example, if updating a view for each update).
...for trees, for example, this would update the column headers to reflect the sorting.
nsINavHistoryResultTreeViewer
treeindexfornode() returns the row index corresponding to the specified node within the tree, or index_invisible if the tree is unattached or the node is not visible (if, for example, its parent container is collapsed).
... return value the row index of the node specified by anode, or index_invisible for nodes that are hidden (by their parents being collapsed, for example) or if there is no attached tree.
nsIPlacesView
for example, the representation of selection differs between trees, menus, and other such lists.
...see displaying places information using views for examples.
nsIPluginHost
for example "proxy 111.111.111.111;proxy 112.112.112.112", "proxy 111.111.111.111;socks 112.112.112.112"....
...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.
nsIPrefService
for example, if the root browser.startup.
...for example, if the root browser.startup.
nsIPrintingPrompt
you can use it as an example.
...for example, some platforms may implement an "apply" button.
nsIProtocolProxyService
this method may be useful in conjunction with nsisockettransportservice.createtransport() for creating, for example, a socks connection.
...a proxy is disallowed, for example, if it is a http proxy and the nsiprotocolhandler for the queried uri does not permit proxying via http.
nsIPushSubscription
example const { classes: cc, interfaces: ci, utils: cu } = components; const scriptsecuritymanager = cc["@mozilla.org/scriptsecuritymanager;1"] .getservice(ci.nsiscriptsecuritymanager); const pushservice = cc["@mozilla.org/push/service;1"] .getservice(ci.nsipushservice); function sendsubscriptiontoserver(subscription) { let request = cc["@mozilla...
....org/xmlextras/xmlhttprequest;1"] .createinstance(ci.nsixmlhttprequest); request.open("post", "https://example.com/register-for-push", true); request.addeventlistener("error", () => { cu.reporterror("error sending subscription to server"); }); request.send(json.stringify({ endpoint: subscription.endpoint, // base64-encode the key and authentication secret.
nsIResumableChannel
netwerk/base/public/nsiresumablechannel.idlscriptable this interface is meant to be implemented by the channels that support resuming broken downloads (for example necko's html and ftp channels).
...during onstartrequest, this channel will have a status of ns_error_not_resumable if the file cannot be resumed, for example because the server doesn't support this.
nsIScreen
for example, this would exclude the area occupied by the menu bar and dock on mac os x.
... example var screenman = components.classes["@mozilla.org/gfx/screenmanager;1"] .getservice(components.interfaces.nsiscreenmanager); var left = {}, top = {}, width = {}, height = {}; screenman.primaryscreen.getrect(left, top, width, height); print([left.value, top.value, width.value, height.value]); see also nsiscreenmanager working with out parameters ...
nsISecurityCheckedComponent
two examples: code that has the "universalxpconnect" capability is allowed to access all of xpcom.
... for example, this capability allows code to set the value of <input type="file"> and access an arbitrary file on disk.
nsISessionStore
this outermost or root window can also be obtained from the list returned by nsiwindowmediator; see example #3 in working_with_windows_in_chrome_code.
...if you just hold a reference to some content document in the overlay's chrome window, here is how you find its corresponding tab: function tabfromdoc(doc) { var no = gbrowser.getbrowserindexfordocument(doc); return gbrowser.tabcontainer.childnodes[no]; } // example use: cc['@mozilla.org/browser/sessionstore;1'] .getservice(ci.nsisessionstore) .settabvalue(tabfromdoc(mycontentdoc), 'mykey', 'myvalue'); see also the session store api article.
nsISocketProvider
for example, an ssl connection would not send any client-certificates if this flag is set.
...for example, ssl via a socks proxy.
nsISocketTransport
for example, an ssl connection would not send any client-certificates if this flag is set.
...the implementation may truncate timeout values to a smaller range of values (for example, 0 to 0xffff).
nsIStackFrame
for example, standard language errors would generally have the same location as their top stack entry.
... example to output the stack at a particular location: var s = components.stack; while(s) { console.log(s.name); s = s.caller; } methods tostring() a generic formatter - make it suitable to print, and so forth.
nsITraceableChannel
example this example can be copied and pasted into a javascript interpreter and run.
... this example uses promise syntax that is available in firefox 30 and onwards.
nsIURIFixup
fixup_flags_make_alternate_uri 2 tell the fixup to make an alternate uri from the input uri, for example to turn foo into www.foo.com.
... methods createexposableuri() converts an internal uri (for example a wysiwyg uri) into one which we can expose to the user, for example on the url bar.
nsIUUIDGenerator
exceptions thrown ns_error_failure if a uuid cannot be generated (for example if an underlying source of randomness is not available) native code only!generateuuidinplace obtain a new uuid like the generateuuid() method, but place it in the provided nsid pointer instead of allocating a new nsid.
... exceptions thrown ns_error_failure if a uuid cannot be generated (for example if an underlying source of randomness is not available) example generating a uuid var uuidgenerator = components.classes["@mozilla.org/uuid-generator;1"] .getservice(components.interfaces.nsiuuidgenerator); var uuid = uuidgenerator.generateuuid(); var uuidstring = uuid.tostring(); ...
nsIUpdate
toolkit/mozapps/update/nsiupdateservice.idlscriptable an interface that describes an object representing an available update to the current application - this update may have several available patches from which one must be selected to download and install, for example we might select a binary difference patch first and attempt to apply that, then if the application process fails fall back to downloading a complete file-replace patch.
...this lets the system differentiate between several nightly builds with the same version, for example.
nsIVersionComparator
return value if a and b are two version being compared, and the return value is smaller than 0, then a < b equals 0 then version, then a==b is bigger than 0, then a > b example function compareversions(a,b) { var x = services.vc.compare(a,b); if(x == 0) return a + "==" + b; else if(x > 0) return a + ">" + b; return a + "<" + b; } dump(compareversions("1.0pre", "1.0")); example - compare current browser version this example here uses nsixulappinfo component to get the version of the browser that the code is running in.
... see here: nsixulappinfo components.utils.import("resource://gre/modules/services.jsm"); var curentbrowserversion = services.appinfo.platformversion; //example: '31.*' var comparetothisversion = '25.*'; var compareresult = services.vc.compare(curentbrowserversion, comparetothisversion); if (compareresult == -1) { //currentbrowserversion is less than '25.*' (comparetothisversion) } else if (compareresult == 0) { //currentbrowserversion is '25.*' (comparetothisversion) } else if (compareresult == 1) { //currentbrowserversion is greater than '25.*' (comparetothisversion) } else { //will never get here as services.vc.compare only returns -1, 0, or 1 } see also toolkit version format ...
nsIWebContentHandlerRegistrar
examples register a webmail service as mailto handler the following code aims to add "outlook.com live mail" to list of webservice handlers.
...must have a content window to pass to registerprotocolhandler as it prompts the user for permission'); } nsiwchr.registerprotocolhandler("mailto", registeruri, "outlook.com live mail", htmlcontentwindow); in this example the services.wm.getenumerator was used to find a window that had the same host name (contentwindow.location.hostname) as the uri (uri.host) we are trying to add.
nsIWebSocketChannel
this is used in the case of a redirect or uri "resolution" (for example resolving a resource: uri to a file: uri) so that the original pre-redirect uri can still be obtained.
... 1003 close_unsupported the connection is being terminated because the endpoint received data of a type it cannot accept (for example, a text-only endpoint received binary data).
nsIWinTaskbar
for example, if the vendor is configured to "foobar systems", the application's name is "squashweb", and the application's version is 1.0, the defaultgroupid attribute would be "foobar systems.squashweb.1.0".
...example netscape.security.privilegemanager.enableprivilege("universalxpconnect"); var taskbar = components.classes["@mozilla.org/windows-taskbar;1"].getservice(components.interfaces.nsiwintaskbar); // get the docshell for the browser var navigator2 = top.queryinterface(components.interfaces.nsiinterfacerequestor).getinterface(components.interfaces.nsiwebnavigation); var docshell = navigator2.queryinter...
nsIXULRuntime
the result takes the form <processor>-<compilerabi>, for example: x86-msvc ppc-gcc3.
... example display the user's operating system in an alert box: var xulruntime = components.classes["@mozilla.org/xre/app-info;1"] .getservice(components.interfaces.nsixulruntime); alert(xulruntime.os); see also nsixulappinfo - a related interface providing information about the host application, it's also implemented by xre/app-info.
nsIXULTemplateBuilder
as an example, for an xml data source the initial reference point would be a specific node in the dom tree and a template might generate a list of all child nodes.
...for a tree builder, for example, the content within the action body is used to create the tree rows instead.
XPCOM
if the component uses only "frozen" xpcom interfaces, there is a good chance the same binary component will work with different versions of gecko (version 1.8 and 1.9, for example).
...this can create a difficult situation for extension developers trying to support multiple gecko versions (firefox 2 and 3, for example).creating a python xpcom componentcreating applications with mozilla already provides a tutorial for making a simple javascript or c++ component (implementing the nsisimple interface).
XPIDL
some examples are in the xpcom/base and xpcom/ds directories of the mozilla tree.
...for example, the method '[binaryname(foo)] void bar();' becomes 'nsresult foo()' in native code (note that capitalization is still applied).
nsIMsgCloudFileProvider
refreshuserinfo() refreshes the data for this user account - for example, the storage quota, or the amount of storage being used.
... providerurlforerror() for an error code, for example uploadwouldexceedquota, a provider might have a url with information on how to deal with that error.
Adding items to the Folder Pane
level in the tree to display the item at open (rw, attribute) whether or not this container is open children (attribute) an array of child items also conforming to this spec getproperties (function) a call from getrowproperties or getcellproperties for this item will be passed into this function command (function) this function will be called when the item is double-clicked for our example extension, two different types of folder-tree-items will be defined.
...however, the complete example file includes code to display the number selected in thunderbird's main viewing pane, when such a number is selected in the folder pane.
Creating a Custom Column
getting started in this example we will be developing a small extension that will be adding a column that will display the "reply-to:" field of an email (if it exists, it if often not set).
...function doonceloaded() { var observerservice = components.classes["@mozilla.org/observer-service;1"].getservice(components.interfaces.nsiobserverservice); observerservice.addobserver(createdbobserver, "msgcreatedbview", false); } var createdbobserver = { // components.interfaces.nsiobserver observe: function(amsgfolder, atopic, adata) { addcustomcolumnhandler(); } } in this example we have a function addcustomcolumnhandler() that is called whenever the event is fired.
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.
... note: if our extension supports more mozilla applications (for example mozilla firefox and mozilla thunderbird) we need also specify application flag.
Filter Incoming Mail
by example, to modify the mail subject : var newmaillistener = { msgadded: function(amsghdr) { if( !amsghdr.isread ) { // here we are, a new mail has popped // let get a javascript string object from the subject property // querying mime conversion interface var mimeconvert = components.classes["@mozilla.org/messenger/mimeconverter;1"] .getservice(components.interfaces.nsimimeconverter); var subject = mimeconvert.decodemimeheader(amsghdr.subject, null, false, true); // here with have a string to modify with javascript.
... by example, setting it to lower case subject = subject.tolocalelowercase(); // then we rebuild a subject objet by rencoding the string // and assign it to the message headers and we're done amsghdr.subject = mimeconvert.encodemimepartiistr_utf8(subject, false, "utf-8", 0, 72); } } }; function init() { var notificationservice = components.classes["@mozilla.org/messenger/msgnotificationservice;1"] .getservice(components.interfaces.nsimsgfoldernotificationservice); notificationservice.addlistener(newmaillistener, notificationservice.msgadded); } addeventlistener("load", init, true); have a look to nsimsgdbhdr to get the full list of properties to be modified.
Styling the Folder Pane
for example, imap servers are "imap".
...for example, if the inbox flag is set, this will be "inbox".
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 sa...
... examples 1.-1 < 1 == 1.
Using the Mozilla symbol server
in the examples below, a local cache directory is used to avoid repeatedly fetching the pdb from the server.
...the rest of values are based on the contents of the application.ini file under the [app] heading: for example, the thunderbird 3.1b2 release with name=thunderbird, version=3.1b2, buildid=20100430125415 would have a filename of "thunderbird-3.1b2-linux-20100430125415-symbols.txt" under the thunderbird directory at symbols.mozilla.org.
Using C struct and pointers
in this example, we show how to use c structs and pointers with js-ctypes.
... references this example is based on code found here.
Declaring and Using Callbacks
examples example 1 this callback that returns bool and has two arguments.
...ar myfunctypedeclaration = ctypes.functiontype(ctypes.default_abi, ctypes.bool, [ctypes.int, ctypes.voidptr_t]); function myjscallback(cint, cptr) { return true; // as the return of the functiontype was ctypes.bool we must make our javascript callback return bool otherwise js-ctypes will throw error saying unexpected type return } var myccallback = myfunctypedeclaration.ptr(myjscallback); example 2 this callback that returns void and no arguments.
CData
assed, then assumption is not made, at the known_len position in array we will see a null char // i tried getting known_len from stringptr but its not possible, it has be known, i tried this: //"stringptr.contents.tostring()" "95" //"stringptr.tostring()" "ctypes.unsigned_char.ptr(ctypes.uint64("0x7f73d5c87650"))" // so as we see neither of these is 77, this is for the example of "_scratchpad/entehandle.js at master · noitidart/_scratchpad mdnfirefox" // tries to do read string on stringptr, if it fails then it falls to read as jschar var readjscharstring = function() { var assumption_max_len = known_len ?
...xpect spaces even null terminator is a chineese character console.info('ptrasarr.length:', ptrasarr.length); //console.log('debug-msg :: datacasted:', datacasted, uneval(datacasted), datacasted.tostring()); var charcode = []; var fromcharcode = [] for (var i=0; i<ptrasarr.length; i++) { //if known_len is correct, then will not hit null terminator so like in example of "_scratchpad/entehandle.js at master · noitidart/_scratchpad mdnfirefox" if you pass length of 77, then null term will not get hit by this loop as null term is at pos 77 and we go till `< known_len` var thisunsignedcharcode = ptrasarr.addressofelement(i).contents; if (thisunsignedcharcode == 0) { // reached null terminator, break console...
Library
the first being the same as in the above example, name, which is the name of the symbol to export.
...for example, from the objective-c library we can export the symbol which holds the address to an external block.
PKCS #11 Netscape Trust Objects - Network Security Services
examples of trust assertions are certificate authority root certificates.
...examples of purposes are: email, code signing, authenticating a server.
Memory - Plugins
you need to use npn_memflush only when it is not possible to call npn_memalloc, for example, when calling system methods that allocate memory indirectly.
... for example, suppose that the plug-in calls newgworld, and that the call fails because of insufficient memory.
Version, UI, and Status Information - Plugins
for example, plug-in api version 6.03 has a major version number of 6 and a point release number of 3.
... detecting windowless support on ms windows and mac os x in this example, the has_windowless method finds out whether the current version of the api supports windowless plug-ins.
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"...
...example: var features = "chrome,titlebar,toolbar,centerscreen,modal"; window.opendialog(url, "preferences", features); bugzilla the component for bugs in the preferences bindings (but not in firefox/thunderbird options ui) is toolkit:preferences (file a bug list open bugs) ...
Introduction to DOM Inspector - Firefox Developer Tools
for example, you can enter http://www.mozilla.org in the address bar and see the dom structure of the mozilla.org home page.
...(note that there are bugs which prevent the flasher from dom inspector apis from working correctly on certain platforms.) if you inspect the main browser window, for example, and select nodes in the dom nodes viewer (other than the elements which have no visible ui as is the case with the endless list of script elements that are loaded into browser.xul), you will see the various parts of the browser interface being highlighted with a blinking red border.
Use a source map - Firefox Developer Tools
for example: sources are often combined and minified to make delivering them from the server more efficient.
...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.
UI Tour - Firefox Developer Tools
for example, the logpoint at line 85 logs the value of the tablerow variable to the console and the conditional breakpoint at line 100 breaks if the contents of the todolist is undefined.
... enable framework grouping collects items belonging to a framework into a collapsible group (for example, jquery in the screenshot above).
Using the Debugger map scopes feature - Firefox Developer Tools
if you want to follow along, use this example.
... open the example page and then open the debugger using tools > web developer > debugger (or press ctrl + i and then select the debugger).
Debugger - Firefox Developer Tools
for example, an uncaught exception hook may have access to browser-level features like the alert function, which this api’s implementation does not, making it possible to present debugger errors to the developer in a way suited to the context.) debugger handler functions each debugger instance inherits accessor properties with which you can store handler functions for spidermonkey to call when given e...
...thus, for example, a debugger.object referring to a second debugger.object which refers to a global does not designate that global for the purposes of this function.) the global designated byglobal must be in a different compartment than this debugger instance itself.
Tutorial: Set a breakpoint - Firefox Developer Tools
our example code is long enough that the best way to run it is to use the scratchpad panel, which is not enabled by default.
...the debugger api tries to interact with garbage collection as transparently as possible; for example, if both a debugger.object instance and its referent are not reachable, they will both be collected, even while the debugger instance to which the shadow belonged continues to exist.
Memory - Firefox Developer Tools
concepts dominators example pages examples used in the memory tool documentation.
... monster example dom allocation example ...
Network Monitor - Firefox Developer Tools
the network monitor shows you all the network requests firefox makes (for example, when it loads a page, or due to xmlhttprequests), how long each request takes, and details of each request.
...this means you can start debugging a page in, for example, the web console, then switch to the network monitor to see network activity without having to reload the page.
Allocations - Firefox Developer Tools
so in the example above: 8904 samples were taken in signallater(), which is 28.57% of the total number of samples taken those samples allocated 1102888 bytes, which is 30.01% of the total memory allocated in all samples next to each function name is a disclosure arrow.
...for example: can you allocate memory lazily, when it is actually needed, instead of up front?
Sorting algorithms comparison - Firefox Developer Tools
this article describes a simple example program that we use in two of the performance guides: the guide to the call tree and the guide to the flame chart.
... you can try out the example program here and clone the code here (be sure to check out the gh-pages branch).
Flame Chart - Firefox Developer Tools
an example to see how the flame chart can reveal the behavior of your program, we'll look at a simple example.
... we'll use the same example as in the call tree page: a program that compares three different sorting algorithms.
Frame rate - Firefox Developer Tools
for example, if moving the mouse over some page element triggers some javascript that changes the element's appearance, and that triggers a reflow and a repaint, then all this work needs to be completed in that frame.
...for example, here's a screenshot of a performance profile: you can see that the average frame rate is reasonably healthy, but there are three spots where frame rate collapses for tens of milliseconds.
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.
... an example: margin versus transform in this section we'll see how the waterfall can highlight the difference between animating using margin and animating using transform.
Shader Editor - Firefox Developer Tools
you can edit these programs and see the results the next time the webgl context redraws (for example, in the next animation frame).
... for example, you can modify the colors: the editor highlights syntax errors in your code: if you hover over the cross shown next to a line containing an error, you'll see more details about the problem: ...
Cookies - Firefox Developer Tools
for example, if you select "delete all from test8.example.com" only cookies from that domain will be deleted.
... cookies from "test13.example.com" will not be deleted.
Style Editor - Firefox Developer Tools
this means that if you use, for example, sass, then the style editor will show you, and allow you to edit, sass files, rather than the css that is generated from them: for this to work, you must: use a css preprocessor that understands the source map revision 3 proposal.
... actually instruct the preprocessor to generate a source map, for example by passing the --source-map argument to the lass command-line tool, but in some preprocessors like sass, source maps are generated by default and you don't need to do anything.
Toolbox - Firefox Developer Tools
there are a few different ways to open the toolbox: select "toggle tools" from the web developer menu (under "tools" on os x and linux, or "firefox" on windows) click the wrench icon (), which is in the main toolbar or under the hamburger menu (), then select "toggle tools" activate any tool hosted in the toolbox (for example, the javascript debugger or the page inspector) press ctrl + shift + i on windows and linux, or cmd + opt + i on os x.
...the array may include the following tools: web console javascript debugger page inspector style editor profiler network monitor note that not all the hosted tools are always listed here: only the tools actually available in this context are shown (for example, not all tools support remote debugging yet, so if the debugging target is not the firefox instance that launched the window, not all the hosted tools will be shown).
View Source - Firefox Developer Tools
for example view-source:https://www.mozilla.org/#line100 view selection source if you select part of a web page and conext-click, you'll see a context menu item labeled "view selection source", that behaves just like "view page source", except you only see the source for the selection.
...for example, putting a <div> element as a child of a <ul> element isn't a parse error, but it is not valid html.
Web Audio Editor - Firefox Developer Tools
for example, the gainnode has a single gain property, while the oscillatornode has frequency and detune properties.
...for example, here's what the oscillatornode looks like: with the violent theremin demo, the frequency parameter is modified as the user moves the mouse left and right, and you can see this reflected in the node inspector.
AbortController.AbortController() - Web APIs
examples in the following snippet, we aim to download a video using the fetch api.
... you can find a full working example on github — see abort-api (see it running live also).
AbortController.abort() - Web APIs
examples in the following snippet, we aim to download a video using the fetch api.
... you can find a full working example on github — see abort-api (see it running live also).
AbortController.signal - Web APIs
examples in the following snippet, we aim to download a video using the fetch api.
... you can find a full working example on github — see abort-api (see it running live also).
AbortController - Web APIs
examples in the following snippet, we aim to download a video using the fetch api.
... you can find a full working example on github — see abort-api (see it running live also).
AbortSignal - Web APIs
examples in the following snippet, we aim to download a video using the fetch api.
... current version of firefox rejects the promise with a domexception you can find a full working example on github — see abort-api (see it running live also).
AbsoluteOrientationSensor - Web APIs
examples basic example the following example, which is loosely based on intel's orientation phone demo, instantiates an absoluteorientationsensor with a frequency of 60 times a second.
... model.quaternion.fromarray(sensor.quaternion).inverse(); }); sensor.addeventlistener('error', error => { if (event.error.name == 'notreadableerror') { console.log("sensor is not available."); } }); sensor.start(); permissions example using orientation sensors requires requesting permissions for multiple device sensors.
Accelerometer.x - Web APIs
WebAPIAccelerometerx
example acceleration is typically read in the sensor.onreading event callback.
... in the example below this occurs sixty times a second.
Accelerometer.y - Web APIs
WebAPIAccelerometery
example acceleration is typically read in the sensor.onreading event callback.
... in the example below this occurs sixty times a second.
Accelerometer.z - Web APIs
WebAPIAccelerometerz
example acceleration is typically read in the sensor.onreading event callback.
... in the example below this occurs sixty times a second.
Accelerometer - Web APIs
example acceleration is typically read in the sensor.onreading event callback.
... in the example below this occurs sixty times a second.
AesCbcParams - Web APIs
however, it need not be secret (for example, it may be transmitted unencrypted along with the ciphertext).
... examples see the examples for subtlecrypto.encrypt() and subtlecrypto.decrypt().
AesCtrParams - Web APIs
for example, if length is set to 64, then the first half of counter is the nonce and the second half is used for the counter.
... examples see the examples for subtlecrypto.encrypt() and subtlecrypto.decrypt().
AesGcmParams - Web APIs
note that the iv does not have to be secret, just unique: so it is ok, for example, to transmit it in the clear alongside the encrypted message.
... examples see the examples for subtlecrypto.encrypt() and subtlecrypto.decrypt().
Ambient Light Events - Web APIs
it allows them to react to such a change, for example by changing the color contrast of the user interface (ui) or by changing the exposure necessary to take a picture.
... example if ('ondevicelight' in window) { window.addeventlistener('devicelight', function(event) { var body = document.queryselector('body'); if (event.value < 50) { body.classlist.add('darklight'); body.classlist.remove('brightlight'); } else { body.classlist.add('brightlight'); body.classlist.remove('darklight'); } }); } else { console.log('devicelight even...
AnalyserNode.fftSize - Web APIs
example the following example shows basic usage of an audiocontext to create an analysernode, then requestanimationframe and <canvas> to collect time domain data repeatedly and draw an "oscilloscope style" output of the current audio input.
... for more complete applied examples/information, check out our voice-change-o-matic demo (see app.js lines 128–205 for relevant code).
AnalyserNode.frequencyBinCount - Web APIs
example the following example shows basic usage of an audiocontext to create an analysernode, then requestanimationframe and <canvas> to collect frequency data repeatedly and draw a "winamp bargraph style" output of the current audio input.
... for more complete applied examples/information, check out our voice-change-o-matic demo (see app.js lines 128–205 for relevant code).
AnalyserNode.getByteTimeDomainData() - Web APIs
return value void | none example the following example shows basic usage of an audiocontext to create an analysernode, then requestanimationframe and <canvas> to collect time domain data repeatedly and draw an "oscilloscope style" output of the current audio input.
... for more complete applied examples/information, check out our voice-change-o-matic demo (see app.js lines 128–205 for relevant code).
AnalyserNode.getFloatTimeDomainData() - Web APIs
example the following example shows basic usage of an audiocontext to create an analysernode, then requestanimationframe and <canvas> to collect time domain data repeatedly and draw an "oscilloscope style" output of the current audio input.
... for more complete applied examples/information, check out our voice-change-o-matic-float-data demo (see the source code too).
AnalyserNode.maxDecibels - Web APIs
example the following example shows basic usage of an audiocontext to create an analysernode, then requestanimationframe and <canvas> to collect frequency data repeatedly and draw a "winamp bargraph style" output of the current audio input.
... for more complete applied examples/information, check out our voice-change-o-matic demo (see app.js lines 128–205 for relevant code).
AnalyserNode.minDecibels - Web APIs
example the following example shows basic usage of an audiocontext to create an analysernode, then requestanimationframe and <canvas> to collect frequency data repeatedly and draw a "winamp bargraph style" output of the current audio input.
... 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
currently the only timeline type available is documenttimeline, but in the future there my be timelines associated with gestures or scrolling, for example.
... 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.finish() - Web APIs
WebAPIAnimationfinish
examples the following example shows how to use the finish() method and catch an invalidstate error.
... interfaceelement.addeventlistener("mousedown", function() { try { player.finish(); } catch(e if e instanceof invalidstate) { console.log("finish() called on paused or finished animation."); } catch(e); logmyerrors(e); //pass exception object to error handler } }); the following example finishes all the animations on a single element, regardless of their direction of playback.
Animation.pause() - Web APIs
WebAPIAnimationpause
exceptions invalidstateerror the animation's currenttime is unresolved (for example, if it's never been played or isn't currently playing) and the end time of the animation is positive infinity.
... example animation.pause() is used many times in the alice in web animations api land growing/shrinking alice game, largely because animations created with the element.animate() method immediately start playing and must be paused manually if you want to avoid that: // animation of the cupcake slowly getting eaten up var nommingcake = document.getelementbyid('eat-me_sprite').animate( [ { transform: 'translatey(0)' }, { transform: 'translatey(-80%)' } ], { fill: 'forwards', easing: 'steps(4, end)', duration: alicechange.effect.timing.duration / 2 }); // doesn't actually need to be eaten until a click event, so pau...
Attr.localName - Web APIs
WebAPIAttrlocalName
example the following example shows "id" in an alert dialog.
... html content <button id="example">click me</button> javascript content const element = document.queryselector("#example"); element.addeventlistener("click", function() { const attribute = element.attributes[0]; alert(attribute.localname); }); notes the local name of an attribute is the part of the attribute's qualified name that comes after the colon.
Attr.prefix - Web APIs
WebAPIAttrprefix
syntax string = attribute.prefix examples the following logs "x" to the console.
... <div x:id="example" onclick="console.log(this.attributes[0].prefix)"/> notes this will only work when a namespace-aware parser is used, i.e.
AudioBuffer - Web APIs
example the following simple example shows how to create an audiobuffer and fill it with random white noise.
... you can find the full source code at our webaudio-examples repository; a running live version is also available.
AudioBufferSourceNode.detune - Web APIs
for example, values of +100 and -100 detune the source up or down by one semitone, while +1200 and -1200 detune it up or down by one octave.
... example const audioctx = new audiocontext(); const channelcount = 2; const framecount = audioctx.samplerate * 2.0; // 2 seconds const myarraybuffer = audioctx.createbuffer(channelcount, framecount, audioctx.samplerate); for (let channel = 0; channel < channelcount; channel++) { const nowbuffering = myarraybuffer.getchanneldata(channel); for (let i = 0; i < framecount; i++) { nowbuffering[i] = math.random() * 2 - 1; } } const source = audioctx.createbuffersource(); source.buffer = myarraybuffer; source.connect(aud...
AudioBufferSourceNode.loop - Web APIs
when the time specified by the loopend property is reached, playback continues at the time specified by loopstart example in this example, the audiocontext.decodeaudiodata function is used to decode an audio track and put it into an audiobuffersourcenode.
... you can run the full example live (or view the source.) function getdata() { source = audioctx.createbuffersource(); request = new xmlhttprequest(); request.open('get', 'viper.ogg', true); request.responsetype = 'arraybuffer'; request.onload = function() { var audiodata = request.response; audioctx.decodeaudiodata(audiodata, function(buffer) { mybuffer = buffer; source.buffer = mybuffer; source.playbackrate.value = playbackcontrol.value; source.connect(audioctx.destination); source.loop = true; }, function(e){"error with decoding audio data" + ...
AudioBufferSourceNode.playbackRate - Web APIs
example in this example, the audiocontext.decodeaudiodata() function is used to decode an audio track, and put it into an audiobuffersourcenode.
... you can run the example live (or view the source.) play the song and alter the playback rate for some fun results.
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.
...// this is the audionode to use when we want to play an audiobuffer var source = audioctx.createbuffersource(); // set the buffer in the audiobuffersourcenode source.buffer = myarraybuffer; // connect the audiobuffersourcenode to the // destination so we can hear the sound source.connect(audioctx.destination); // start the source playing source.start(); for a decodeaudiodata() example, see the audiocontext.decodeaudiodata() page.
AudioContext.close() - Web APIs
example the following snippet is taken from our audiocontext states demo (see it running live.) when the stop button is clicked, close() is called.
... when the promise resolves, the example is reset to its beginning state.
AudioContext.createMediaElementSource() - Web APIs
example this simple example creates a source from an <audio> element using createmediaelementsource(), then passes the audio through a gainnode before feeding it into the audiodestinationnode for playback.
... note: you can also view this example running live, or view the source.
AudioContext.createMediaStreamSource() - Web APIs
example in this example, we grab a media (audio + video) stream from navigator.getusermedia, feed the media into a <video> element to play then mute the audio, but then also feed the audio into a mediastreamaudiosourcenode.
... note: you can see this example running live, or view the source.
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.
... you can see full code of this example at output-timestamp (see it live also).
AudioDestinationNode - Web APIs
example there is no complex set up for using an audiodestinationnode — by default, this simply represents the output of the user's system (e.g.
... 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.
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.
... this is pretty useful for fade in/fade out effects: // create audio context var audiocontext = window.audiocontext || window.webkitaudiocontext; var audioctx = new audiocontext(); // set basic variables for example var myaudio = document.queryselector('audio'); var pre = document.queryselector('pre'); var myscript = document.queryselector('script'); pre.innerhtml = myscript.innerhtml; var exprampplus = document.queryselector('.exp-ramp-plus'); var exprampminus = document.queryselector('.exp-ramp-minus'); // create a mediaelementaudiosourcenode // feed the htmlmediaelement into it var source = audioctx.createmediaelementsource(myaudio); // create a gain node and set its gain value to 0.5 var gainnode = audioctx.creategain(); // connect the audiobuffersourcenode to the gainnode // and the g...
AudioParam.linearRampToValueAtTime() - Web APIs
example 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, linearramptovalueattime() is used to fade the gain value up to 1.0, and down to 0, respectively.
... // create audio context var audiocontext = window.audiocontext || window.webkitaudiocontext; var audioctx = new audiocontext(); // set basic variables for example var myaudio = document.queryselector('audio'); var pre = document.queryselector('pre'); var myscript = document.queryselector('script'); pre.innerhtml = myscript.innerhtml; var linearrampplus = document.queryselector('.linear-ramp-plus'); var linearrampminus = document.queryselector('.linear-ramp-minus'); // create a mediaelementaudiosourcenode // feed the htmlmediaelement into it var source = audioctx.createmediaelementsource(myaudio); // create a gain node and set it's gain value to 0.5 ...
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.
... // create audio context var audiocontext = window.audiocontext || window.webkitaudiocontext; var audioctx = new audiocontext(); // set basic variables for example var myaudio = document.queryselector('audio'); var pre = document.queryselector('pre'); var myscript = document.queryselector('script'); pre.innerhtml = myscript.innerhtml; var attimeplus = document.queryselector('.at-time-plus'); var attimeminus = document.queryselector('.at-time-minus'); // create a mediaelementaudiosourcenode // feed the htmlmediaelement into it var source = audioctx.createmediaelementsource(myaudio); // create a gain node and set it's gain value to 0.5 var gainnode = audioctx.creategain(); gainnode.gain.value = 0.5; var currgain = gainnode.gain.value; // connect the audiobuffersourcenode to the gainnode // a...
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).
... when the buttons are pressed, the currgain variable is incremented/decremented by 0.25, then the setvalueattime() method is used to set the gain value equal to currgain, one second from now (audioctx.currenttime + 1.) // create audio context var audiocontext = window.audiocontext || window.webkitaudiocontext; var audioctx = new audiocontext(); // set basic variables for example var myaudio = document.queryselector('audio'); var pre = document.queryselector('pre'); var myscript = document.queryselector('script'); pre.innerhtml = myscript.innerhtml; var targetattimeplus = document.queryselector('.set-target-at-time-plus'); var targetattimeminus = document.queryselector('.set-target-at-time-minus'); // create a mediaelementaudiosourcenode // feed the htmlmediaelement into it var source = audio...
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 audioc...
...ontext(); // set basic variables for example var myaudio = document.queryselector('audio'); var pre = document.queryselector('pre'); var myscript = document.queryselector('script'); pre.innerhtml = myscript.innerhtml; var valuecurve = document.queryselector('.value-curve'); // create a mediaelementaudiosourcenode // feed the htmlmediaelement into it var source = audioctx.createmediaelementsource(myaudio); // create a gain node and set it's gain value to 0.5 var gainnode = audioctx.creategain(); gainnode.gain.value = 0.5; var currgain = gainnode.gain.value; // connect the audiobuffersourcenode to the gainnode // and the gainnode to the destination source.connect(gainnode); gainnode.connect(audioctx.destination); // set button to do something onclick var wavearray = new float32array(9); wav...
AudioParam.value - Web APIs
WebAPIAudioParamvalue
consider this example: const source = new audiobuffersourcenode(...); const rate = 5.3; source.playbackrate.value = rate; console.log(source.playbackrate.value === rate); the log output will be false, because the playback rate parameter, rate, was converted to the 32-bit floating-point number closest to 5.3, which yields 5.300000190734863.
... example this example instantly changes the volume of a gainnode to 40%.
AudioProcessingEvent - Web APIs
example 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.
... note: for a full working example, see our script-processor-node github repo (also view the source code.) var myscript = document.queryselector('script'); var mypre = document.queryselector('pre'); var playbutton = document.queryselector('button'); // create audiocontext and buffer source var audioctx = new audiocontext(); source = audioctx.createbuffersource(); // create a scriptprocessornode with a buffersize of 4096 and a single input and output channel var scriptnode...
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.getelementbyi...
...d("startbutton").disabled = false; } for an example of the ended event in use, see our audio-buffer example on github.
AudioScheduledSourceNode.onended - Web APIs
this is the case, for example, when using an audiobuffersourcenode with its loop property set to true.
... 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.
AudioTrack.enabled - Web APIs
example this example switches between the main and commentary audio tracks of a media element.
... note: this example assumes that there is only one of each kind of track in the video, but this is not necessarily the case.
AudioTrack.label - Web APIs
WebAPIAudioTracklabel
for example, a track whose kind is "commentary" might have a label such as "commentary with director mark markmarkimark and star donna donnalidon".
... example this example returns an array of track kinds and labels for potential use in a user interface to select audio tracks for a specified media element.
AudioTrackList: change event - Web APIs
the change event is fired when an audio track is enabled or disabled, for example by changing the track's enabled property.
... 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.queryselector('video'); videoelement.audiotracks.onchange = (event) => { console.log(`'${event.type}' event fired`); };...
AudioTrackList.onchange - Web APIs
example this snippet establishes a handler for the change event that looks at each of the tracks in the list, calling a function to update the state of a user interface control that indicates the current state of the track.
... var tracklist = document.queryselector("video").audiotracks; tracklist.onchange = function(event) { tracklist.foreach(function(track) { updatetrackenabledbutton(track.id, track.enabled); }); }; the updatetrackenabledbutton(), in this example, should be a function that finds a user interface control using the track's id (perhaps the app uses the track id as the control element's id) and the track's enabled flag to determine which state the control should be in now.
AudioWorkletGlobalScope - Web APIs
examples in this example we output all global properties into the console in the constructor of a custom audioworkletprocessor.
...od is required - simply output silence, // which the outputs are already filled with process (inputs, outputs, parameters) { return true } } // the sample rate is not going to change ever, // because it's a read-only property of a baseaudiocontext // and is set only during its instantiation console.log(samplerate) // you can declare any variables and use them in your processors // for example it may be an arraybuffer with a wavetable const usefulvariable = 42 console.log(usefulvariable) registerprocessor('test-processor', testprocessor) next, in our main scripts file we'll load the processor, create an instance of audioworkletnode — passing the name of the processor to it — and connect the node to an audio graph.
AudioWorkletNode() - Web APIs
for example, outputchannelcount: [n, m] specifies the number of channels in the first output to be n and the second output to be m.
... example for a complete example demonstrating user-defined audio processing, see the audioworkletnode page.
AudioWorkletNodeOptions - Web APIs
for example, outputchannelcount: [n, m] specifies the number of channels in the first output to be n and the second output to be m.
... examples // fill in example snippet specifications specification status comment web audio apithe definition of 'audioworkletnodeoptions' in that specification.
AudioWorkletProcessor() - Web APIs
for example, outputchannelcount: [n, m] specifies the number of channels in the first output to be n and the second output to be m.
... example in this example we pass custom options to the audioworkletnode constructor and observe how a structured clone of them gets passed to our audioworkletprocessor constructor.
AudioWorkletProcessor - Web APIs
processing audio an example algorithm of creating a custom audio processing mechanism is: create a separate file; in the file: extend the audioworkletprocessor class (see "deriving classes" section) and supply your own process() method in it; register the processor using audioworkletglobalscope.registerprocessor() method; load the file using addmodule() method on your audio context's audioworklet property...
... examples in the example below we create a custom audioworkletnode that outputs white noise.
AuthenticatorAssertionResponse.signature - Web APIs
note: this property may only be used in top-level contexts and will not be available in an <iframe> for example.
... 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(function (err) { console.er...
AuthenticatorAssertionResponse.userHandle - Web APIs
note: this property may only be used in top-level contexts and will not be available in an <iframe> for example.
...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(function (err) { console.error(err); }); specifications specification status comment ...
AuthenticatorAttestationResponse.attestationObject - Web APIs
the public key that corresponds to the private key that has created the attestation signature is well known; however, there are various well known attestation public key chains for different ecosystems (for example, android or tpm attestations).
... 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 ...
AuthenticatorAttestationResponse.getTransports() - Web APIs
note: this method may only be used in top-level contexts and will not be available in an <iframe> for example.
... 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 ...
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 }).cat...
...ch(function (err) { console.error(err); }); getting an authenticatorattestationresponse 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 attestationresponse = newcredentialinfo.response; }).catch(function (err) { console.error(err); }); specifications specification status comment web authentication: an api for accessing public key credentials level 1the definition of 'authenticatorresponse interface' in that...
BaseAudioContext.createAnalyser() - Web APIs
example the following example shows basic usage of an audiocontext to create an analyser node, then use requestanimationframe() to collect time domain data repeatedly and draw an "oscilloscope style" output of the current audio input.
... for more complete applied examples/information, check out our voice-change-o-matic demo (see app.js lines 128–205 for relevant code).
BaseAudioContext.createBiquadFilter() - Web APIs
example the following example shows basic usage of an audiocontext to create a biquad filter node.
... for a complete working example, check out our voice-change-o-matic demo (look at the source code too).
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 ...
... now let's look at a more complex createbuffer() example, in which we create a three second buffer, fill it with white noise, and then play it via an audiobuffersourcenode.
BaseAudioContext.createDynamicsCompressor() - Web APIs
example the below code demonstrates a simple usage of createdynamicscompressor() to add compression to an audio track.
... for a more complete example, have a look at our basic compressor example (view the source code).
BaseAudioContext.createGain() - Web APIs
example the following example shows basic usage of an audiocontext to create a gainnode, which is then used to mute and unmute the audio when a mute button is clicked by changing the gain property value.
... the below snippet wouldn't work as is — for a complete working example, check out our voice-change-o-matic demo (view source.) <div> <button class="mute">mute button</button> </div> var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); var gainnode = audioctx.creategain(); var mute = document.queryselector('.mute'); var source; if (navigator.mediadevices.getusermedia) { navigator.mediadevices.getusermedia ( // constraints - only audio needed for this app { audio: true }, // success callback function(stream) { source = audioctx.createmediastreamsource(stream); }, // error callback function(err) { console.log('the following gum error occured: ' + err); } ); } else { console.log('getusermedia not supported on your browser...
BaseAudioContext.createOscillator() - Web APIs
example the following example shows basic usage of an audiocontext to create an oscillator node.
... for applied examples/information, check out our violent theremin demo (see app.js for relevant code); also see our oscillatornode page for more information.
BaseAudioContext.createScriptProcessor() - Web APIs
example 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.
... note: for a full working example, see our script-processor-node github repo (also view the source code.) var myscript = document.queryselector('script'); var mypre = document.queryselector('pre'); var playbutton = document.queryselector('button'); // create audiocontext and buffer source var audioctx = new audiocontext(); source = audioctx.createbuffersource(); // create a scriptprocessornode with a buffersize of 4096 and a single input and output channel var scriptnode...
BaseAudioContext.createWaveShaper() - Web APIs
example the following example shows basic usage of an audiocontext to create a wave shaper node.
... for applied examples/information, check out our voice-change-o-matic demo (see app.js for relevant code).
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...
... the first of these three (supportedinstruments in the example below) contains a data property that has to conform to the structure defined by the basiccardrequest dictionary.
Battery Status API - Web APIs
example in this example, we watch for changes both to the charging status (whether or not we're plugged in and charging) and for changes to the battery level and timing.
...); function updatecharginginfo(){ console.log("battery charging time: " + battery.chargingtime + " seconds"); } battery.addeventlistener('dischargingtimechange', function(){ updatedischarginginfo(); }); function updatedischarginginfo(){ console.log("battery discharging time: " + battery.dischargingtime + " seconds"); } }); see also the example in the specification.
BeforeInstallPromptEvent - Web APIs
this is provided for user agents that want to present a choice of versions to the user such as, for example, "web" or "play" which would allow the user to chose between a web version or an android version.
... example window.addeventlistener("beforeinstallprompt", function(e) { // log the platforms provided as options in an install prompt console.log(e.platforms); // e.g., ["web", "android", "windows"] e.userchoice.then(function(choiceresult) { console.log(choiceresult.outcome); // either "accepted" or "dismissed" }, handleerror); }); ...
BiquadFilterNode.Q - Web APIs
example the following example shows basic usage of an audiocontext to create a biquad filter node.
... for a complete working example, check out our voice-change-o-matic demo (look at the source code too).
BiquadFilterNode.detune - Web APIs
example the following example shows basic usage of an audiocontext to create a biquad filter node.
... for a complete working example, check out our voice-change-o-matic demo (look at the source code too).
BiquadFilterNode.frequency - Web APIs
example the following example shows basic usage of an audiocontext to create a biquad filter node.
... for a complete working example, check out our voice-change-o-matic demo (look at the source code too).
BiquadFilterNode.gain - Web APIs
example the following example shows basic usage of an audiocontext to create a biquad filter node.
... for a complete working example, check out our voice-change-o-matic demo (look at the source code too).
BiquadFilterNode.type - Web APIs
not used example the following example shows basic usage of an audiocontext to create a biquad filter node.
... for a complete working example, check out our voice-change-o-matic demo (look at the source code too).
BiquadFilterNode - Web APIs
example the following example shows basic usage of an audiocontext to create a biquad filter node.
... for a complete working example, check out our voice-change-o-matic demo (look at the source code too).
Blob.slice() - Web APIs
WebAPIBlobslice
for example, -10 would be the 10th from last byte in the blob.
...for example, -10 would be the 10th from last byte in the blob.
Body.formData() - Web APIs
WebAPIBodyformData
if a user submits a form and a service worker intercepts the request, you could for example call formdata() on it to obtain a key-value map, modify some fields, then send the form onwards to the server (or use it locally).
... example tbd.
CSSMathValue.operator - Web APIs
for example, if the current cssmathvalue subtype is cssmathsum, this property will return the string "sum".
... 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.
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.
CSSPositionValue.CSSPositionValue() - Web APIs
the csspositionvalue constructor creates a new csspositionvalue object which represents values for properties that take a position, for example object-position.
... examples the following example positions a container <div> 5 pixels from the top and 10 pixels from the left of the page.
CSSPositionValue - Web APIs
the csspositionvalue interface of the the css typed object model api represents values for properties that take a position, for example object-position.
... examples the following example positions a container <div> 5 pixels from the top and 10 pixels from the left of the page.
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.
... (a style rule may be needed to add quotation marks in older browsers.) the example below demonstrates the basic properties of the csspseudoelement object representing the opening quotation mark.
CSSRule - Web APIs
WebAPICSSRule
the value of "font-size" in the example) use the properties on the specialized interface for the rule's type.
...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).
...in each case, this is done with the setproperty() method, for example boxpararule.style.setproperty('border', newborder); html <div class="controls"> <button class="border">border</button> <button class="bgcolor">background</button> <button class="color">text</button> </div> <div class="box"> <p>box</p> </div> css html { background: orange; font-family: sans-serif; height: 100%; } body { height: inherit; width: 80%; min-width: 500px; max-...
CSSStyleDeclaration - Web APIs
for example, document.stylesheets[0].cssrules[0].style returns a cssstyledeclaration object on the first css rule in the document's first stylesheet.
... example var styleobj = document.stylesheets[0].cssrules[0].style; console.log(styleobj.csstext); for (var i = styleobj.length; i--;) { var namestring = styleobj[i]; styleobj.removeproperty(namestring); } console.log(styleobj.csstext); specifications specification status comment css object model (cssom)the definition of 'cssstyledeclaration' in that specification.
CSSStyleSheet.insertRule() - Web APIs
examples inserting a new rule this snippet pushes a new rule onto the top of my stylesheet.
... * @param {array} rules accepts an array of json-encoded declarations * @example addstylesheetrules([ ['h2', // also accepts a second argument as an array of arrays instead ['color', 'red'], ['background-color', 'green', true] // 'true' for !important rules ], ['.myclass', ['background-color', 'yellow'] ] ]); */ function addstylesheetrules (rules) { var styleel = document.createelement('style'); // append <style> element to <head> document.head.appe...
CSSUnitValue.CSSUnitValue() - Web APIs
for example, "42px" would be represented by a cssnumericvalue.
... examples the following shows a method of creating a csspositionvalue from individual cssunitvalue constructors.
CSSUnitValue - Web APIs
for example, "42px" would be represented by a cssnumericvalue.
... examples the following shows a method of creating a csspositionvalue from individual cssunitvalue constructors.
Determining the dimensions of elements - Web APIs
as an example, if the element has width: 100px; and transform: scale(0.5); the getboundingclientrect() will return 50 as the width, while offsetwidth will return 100.
... for example, if a 600x400 pixel element is being displayed inside a 300x300 pixel scrollbox, scrollwidth will return 600 while scrollheight will return 400.
Using the CSS properties and values API - Web APIs
in this example, the custom property --registered has been registered using the syntax <color> and then used in a linear gradient.
....unregistered:hover, .unregistered:focus { --unregistered: #b4d455; } button { height: 40vh; display: block; width: 100%; font-size: 3vw; } window.css.registerproperty({ name: '--registered', syntax: '<color>', inherits: false, initialvalue: 'red', }); while not functionally accurate, a good way to think about the difference between the unregistered property in the above example and the registered property is the difference between a <custom-ident> and a number when trying to animate height.
CacheStorage.match() - Web APIs
for example, if set to true, the ?value=bar part of http://foo.com/?value=bar would be ignored when performing a match.
... examples this example is from the mdn sw-test example (see sw-test running live).
CanvasRenderingContext2D.addHitRegion() - Web APIs
id the id for this hit region to reference it for later use in events, for example.
... examples using the addhitregion method this example demonstrates the addhitregion() method.
CanvasRenderingContext2D.arc() - Web APIs
examples drawing a full circle this example draws a complete circle with the arc() method.
... const canvas = document.queryselector('canvas'); const ctx = canvas.getcontext('2d'); ctx.beginpath(); ctx.arc(100, 75, 50, 0, 2 * math.pi); ctx.stroke(); result different shapes demonstrated this example draws various shapes to show what is possible with arc().
CanvasRenderingContext2D.clearRect() - Web APIs
examples erasing the whole canvas this code snippet erases the entire canvas.
... const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); ctx.clearrect(0, 0, canvas.width, canvas.height); erasing part of a canvas this example draws a blue triangle on top of a yellowish background.
CanvasRenderingContext2D.clip() - Web APIs
examples a simple clipping region this example uses the clip() method to create a clipping region according to the shape of a circular arc.
...st canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); // create circular clipping region ctx.beginpath(); ctx.arc(100, 75, 50, 0, math.pi * 2); ctx.clip(); // draw stuff that gets clipped ctx.fillstyle = 'blue'; ctx.fillrect(0, 0, canvas.width, canvas.height); ctx.fillstyle = 'orange'; ctx.fillrect(0, 0, 100, 100); result specifying a path and a fillrule this example saves two rectangles to a path2d object, which is then made the current clipping region using the clip() method.
CanvasRenderingContext2D.closePath() - Web APIs
syntax void ctx.closepath(); examples closing a triangle this example creates the first two (diagonal) sides of a triangle using the lineto() method.
... const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); ctx.beginpath(); ctx.moveto(20, 140); // move pen to bottom-left corner ctx.lineto(120, 10); // line to top corner ctx.lineto(220, 140); // line to bottom-right corner ctx.closepath(); // line to bottom-left corner ctx.stroke(); result closing just one sub-path this example draws a smiley face consisting of three disconnected sub-paths.
CanvasRenderingContext2D.createPattern() - Web APIs
examples creating a pattern from an image this example uses the createpattern() method to create a canvaspattern with a repeating source image.
...0" height="300"></canvas> javascript var canvas = document.getelementbyid('canvas'); var ctx = canvas.getcontext('2d'); var img = new image(); img.src = 'https://udn.realityripple.com/samples/04/aaeaf9aac4.png'; img.onload = function() { var pattern = ctx.createpattern(img, 'repeat'); ctx.fillstyle = pattern; ctx.fillrect(0, 0, 300, 300); }; creating a pattern from a canvas in this example we create a pattern from the contents of an offscreen canvas.
CanvasRenderingContext2D.drawImage() - Web APIs
examples drawing an image to the canvas this example draws an image to the canvas using the drawimage() method.
... for example, if you load an image and specify the optional size parameters in its constructor, you will have to use the naturalwidth and naturalheight properties of the created instance to properly calculate things like crop and scale regions, rather than element.width and element.height.
CanvasRenderingContext2D.ellipse() - Web APIs
examples drawing a full ellipse this example draws an ellipse at an angle of π/4 radians (45°).
...anvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); // draw the ellipse ctx.beginpath(); ctx.ellipse(100, 100, 50, 75, math.pi / 4, 0, 2 * math.pi); ctx.stroke(); // draw the ellipse's line of reflection ctx.beginpath(); ctx.setlinedash([5, 5]); ctx.moveto(0, 200); ctx.lineto(200, 0); ctx.stroke(); result various elliptical arcs this example creates three elliptical paths with varying properties.
CanvasRenderingContext2D.fill() - Web APIs
examples filling a rectangle this example fills a rectangle with the fill() method.
... html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); ctx.rect(10, 10, 150, 100); ctx.fill(); result specifying a path and a fillrule this example saves some intersecting lines to a path2d object.
CanvasRenderingContext2D.getLineDash() - Web APIs
for example, setting the line dash to [5, 15, 25] will result in getting back [5, 15, 25, 5, 15, 25].
... examples getting the current line dash setting this example demonstrates the getlinedash() method.
CanvasRenderingContext2D.globalAlpha - Web APIs
examples drawing translucent shapes this example uses the globalalpha property to draw two semi-transparent rectangles.
... html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); ctx.globalalpha = 0.5; ctx.fillstyle = 'blue'; ctx.fillrect(10, 10, 100, 100); ctx.fillstyle = 'red'; ctx.fillrect(50, 50, 100, 100); result overlaying transparent shapes this example illustrates the effect of overlaying multiple transparent shapes on top of each other.
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.isPointInPath() - Web APIs
examples checking a point in the current path this example uses the ispointinpath() method to check if a point is within the current path.
...canvas id="canvas"></canvas> <p>in path: <code id="result">false</code></p> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); const result = document.getelementbyid('result'); ctx.rect(10, 10, 100, 100); ctx.fill(); result.innertext = ctx.ispointinpath(30, 70); result checking a point in the specified path whenever you move the mouse, this example checks whether the cursor is in a circular path2d path.
CanvasRenderingContext2D.isPointInStroke() - Web APIs
examples checking a point in the current path this example uses the ispointinstroke() method to check if a point is within the area of the current path's stroke.
... id="canvas"></canvas> <p>in stroke: <code id="result">false</code></p> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); const result = document.getelementbyid('result'); ctx.rect(10, 10, 100, 100); ctx.stroke(); result.innertext = ctx.ispointinstroke(50, 10); result checking a point in the specified path whenever you move the mouse, this example checks whether the cursor is in the stroke of an elliptical path2d path.
CanvasRenderingContext2D.lineCap - Web APIs
examples changing the shape of line caps this example rounds the end caps of a straight line.
... html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); ctx.beginpath(); ctx.moveto(20, 20); ctx.linewidth = 15; ctx.linecap = 'round'; ctx.lineto(100, 100); ctx.stroke(); result comparison of line caps in this example three lines are drawn, each with a different value for the linecap property.
CanvasRenderingContext2D.lineJoin - Web APIs
examples changing the joins in a path this example applies rounded line joins to a path.
... html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); ctx.linewidth = 20; ctx.linejoin = 'round'; ctx.beginpath(); ctx.moveto(20, 20); ctx.lineto(190, 100); ctx.lineto(280, 20); ctx.lineto(280, 150); ctx.stroke(); result comparison of line joins the example below draws three different paths, demonstrating each of the three linejoin options.
CanvasRenderingContext2D.lineTo() - Web APIs
examples drawing a straight line this example draws a straight line using the lineto() method.
...this example draws a letter 'm' with a single contiguous line.
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.measureText() - Web APIs
the canvasrenderingcontext2d.measuretext() method returns a textmetrics object that contains information about the measured text (such as its width, for example).
... example given this <canvas> element: <canvas id="canvas"></canvas> ...
CanvasRenderingContext2D.resetTransform() - Web APIs
syntax void ctx.resettransform(); examples resetting the matrix this example draws a rotated rectangle after modifying the matrix, and then resets the matrix using the resettransform() method.
...in this example, the first two shapes are drawn with a skew transformation, and the last two are drawn with the identity (regular) transformation.
CanvasRenderingContext2D.rotate() - Web APIs
examples rotating a shape this example rotates a rectangle by 45°.
... rotating a shape around its center this example rotates a shape around its center point.
CanvasRenderingContext2D.scale() - Web APIs
examples scaling a shape this example draws a scaled rectangle.
...in this example, the words "hello world!" are flipped horizontally.
CanvasRenderingContext2D.setTransform() - Web APIs
examples skewing a shape this example skews a rectangle both vertically (.2) and horizontally (.8).
... html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); ctx.settransform(1, .2, .8, 1, 0, 0); ctx.fillrect(0, 0, 100, 100); result retrieving and passing a dommatrix object in the following example, we have two <canvas> elements.
CanvasRenderingContext2D.shadowColor - Web APIs
examples adding a shadow to shapes this example adds a shadow to two squares; the first one is filled, and the second one is stroked.
...this example strokes and fills a rectangle with translucent colors.
CanvasRenderingContext2D.stroke() - Web APIs
examples a simple stroked rectangle this example creates a rectangle using the rect() method, and then draws it to the canvas using stroke().
...in this example, the square on the left is drawn with the stroke on top of the fill.
CanvasRenderingContext2D.strokeRect() - Web APIs
examples a simple stroked rectangle this example draws a rectangle with a green outline using the strokerect() method.
... const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); ctx.strokestyle = 'green'; ctx.strokerect(20, 10, 160, 100); result applying various context settings this example draws a rectangle with a drop shadow and thick, beveled outlines.
A basic ray-caster - Web APIs
this article provides an interesting real-world example of using the <canvas> element to do software rendering of a 3d environment using ray-casting.
...i know i could have started with a simpler example, but i'm sure the canvas tutorial will get to that, and i wanted to see if i could do this.
Advanced animations - Web APIs
ball.x + ball.vx < 0) { ball.vx = -ball.vx; } raf = window.requestanimationframe(draw); } canvas.addeventlistener('mouseover', function(e) { raf = window.requestanimationframe(draw); }); canvas.addeventlistener('mouseout', function(e) { window.cancelanimationframe(raf); }); ball.draw(); acceleration to make the motion more real, you can play with the velocity like this, for example: ball.vy *= .99; ball.vy += .25; this slows down the vertical velocity each frame, so that the ball will just bounce on the floor in the end.
...ball.vx = -ball.vx; } raf = window.requestanimationframe(draw); } canvas.addeventlistener('mouseover', function(e) { raf = window.requestanimationframe(draw); }); canvas.addeventlistener('mouseout', function(e) { window.cancelanimationframe(raf); }); ball.draw(); adding mouse control to get some control over the ball, we can make it follow our mouse using the mousemove event, for example.
Finale - Web APIs
WebAPICanvas APITutorialFinale
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.
Clipboard.write() - Web APIs
WebAPIClipboardwrite
example this example function replaces the current contents of the clipboard with a specified string.
... example of copying canvas contents to the clipboard function copycanvascontentstoclipboard(canvas, ondone, onerror) { canvas.toblob(function (blob) { let data = [new clipboarditem({ [blob.type]: blob })]; navigator.clipboard.write(data).then(function () { ondone(); }, function (err) { onerror(err); }) }); } note: you can only pass in one clipboard item at a time.
Console.timeEnd() - Web APIs
WebAPIConsoletimeEnd
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
WebAPIConsoletimeLog
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.trace() - Web APIs
WebAPIConsoletrace
see stack traces in the console documentation for details and examples.
... example function foo() { function bar() { console.trace(); } bar(); } foo(); in the console, the following trace will be displayed: bar foo <anonymous> specifications specification status comment console apithe definition of 'console.trace()' in that specification.
ConstantSourceNode - Web APIs
example in the article controlling multiple parameters with constantsourcenode, a constantsourcenode is created to allow one slider control to change the gain on two gainnodes.
... to see this example in action, as well as to read the rest of the code from which these snippets were derived, see controlling multiple parameters with constantsourcenode.
Constraint validation API - Web APIs
examples take the following form: <form> <label for="name">enter username (upper and lowercase letters): </label> <input type="text" name="name" id="name" required pattern="[a-za-z]+"> <button>submit</button> </form> the basic html form validation features will cause this to produce a default error message if you try to submit the form with either no valid filled in, or a value that does not mat...
...try again!'); } }); the example renders like so: in brief: we check the valid state of the input element every time its value is changed by running the checkvalidity() method via the input event handler.
ContentIndex - Web APIs
examples feature detection and interface access here we get a reference to the serviceworkerregistration, then check for the index property, which gives us access to the content index interface.
...dd indexed content async function registercontent(data) { const registration = await navigator.serviceworker.ready; // feature detect content index if (!registration.index) { return; } // register content try { await registration.index.add(data); } catch (e) { console.log('failed to register content: ', e.message); } } retrieving items within the current index the below example shows an asynchronous function that retrieves items within the content index and iterates over each entry, building a list for the interface.
ConvolverNode.buffer - Web APIs
for example, if you want to model the reverb in your bathroom, you might set up a microphone near the door to record the sound of a balloon pop or synthesized impulse from the sink.
... example var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); var convolver = audioctx.createconvolver(); ...
CrashReportBody - Web APIs
examples crash reports are generally only retrievable via endpoints set up using the report-to header.
... some sample json might look like this: { "type": "crash", "age": 42, "url": "https://example.com/", "user_agent": "mozilla/5.0 (x11; linux x86_64; rv:60.0) gecko/20100101 firefox/60.0", "body": { "reason": "oom" } } note: crash reports are always delivered to the endpoint group named default; there is currently no way to override this.
CredentialsContainer - Web APIs
for example, you might call this, after a user signs out of a website to ensure that he/she isn't automatically signed in on the next site visit.
... examples // tbd specifications specification status comment credential management level 1 working draft initial definition.
Crypto.getRandomValues() - Web APIs
there are a few reasons for this; for example, getrandomvalues() is not guaranteed to be running in a secure context.
... examples /* assuming that window.crypto.getrandomvalues is available */ var array = new uint32array(10); window.crypto.getrandomvalues(array); console.log("your lucky numbers:"); for (var i = 0; i < array.length; i++) { console.log(array[i]); } specification specification status comment web cryptography api recommendation initial definition ...
CryptoKey - Web APIs
WebAPICryptoKey
examples the examples for subtlecrypto methods often use cryptokey objects.
... for example: subtlecrypto.generatekey() subtlecrypto.derivekey() subtlecrypto.importkey() subtlecrypto.exportkey() subtlecrypto.wrapkey() subtlecrypto.unwrapkey() subtlecrypto.encrypt() subtlecrypto.decrypt() subtlecrypto.sign() subtlecrypto.verify() specifications specification status comment web cryptography apithe definition of 'cryptokey' in that specification.
CryptoKeyPair - Web APIs
examples the examples for subtlecrypto methods often use cryptokeypair objects.
... for example: subtlecrypto.generatekey() subtlecrypto.derivekey() subtlecrypto.importkey() subtlecrypto.exportkey() subtlecrypto.wrapkey() subtlecrypto.unwrapkey() subtlecrypto.encrypt() subtlecrypto.decrypt() subtlecrypto.sign() subtlecrypto.verify() specifications specification status comment web cryptography apithe definition of 'cryptokeypair' in that specification.
CustomElementRegistry.define() - Web APIs
examples autonomous custom element the following code is taken from our popup-info-box-web-component example (see it live also).
... customized built-in element the following code is taken from our word-count-web-component example (see it live also).
DOMHighResTimeStamp - Web APIs
however, if the browser is unable to provide a time value accurate to 5 µs (due, for example, to hardware or software constraints), the browser can represent the value as a time in milliseconds accurate to a millisecond.
... example to determine how much time has elapsed since a particular point in your code, you can do something like this: let starttime = performance.now(); /* ...
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.
DOMPointReadOnly.fromPoint() - Web APIs
examples creating a 2d point this sample creates a 2d point, specifying an inline object that includes the values to use for x and y.
... const point2d = dompointreadonly.frompoint({x: 25, y: 25}) creating a 3d point using an existing point this example creates a point, origpoint, of type dompoint, using new dompoint().
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.
...for example: <span class=" d d e f"></span> let span = document.queryselector("span"); let classes = span.classlist; span.classlist.add("x"); span.textcontent = `span classlist is "${classes}"`; the output looks like this: specifications specification status comment domthe definition of 'domtokenlist' in that specification.
DataTransfer.dropEffect - Web APIs
for example, when the user hovers over a target drop element, the browser's cursor may indicate which type of operation will occur.
... example this example shows the use of the dropeffect and effectallowed properties.
DataTransfer.getData() - Web APIs
example data types are text/plain and text/uri-list.
... example this example shows the use of the datatransfer object's getdata() and setdata() methods.
DataTransfer.mozItemCount - Web APIs
this can be used, for example, to get the number of files being dragged.
... example this example shows the use of the mozitemcount property.
DataTransfer.mozSetDataAt() - Web APIs
return value void example this example shows the use of the mozsetdataat() method in a dragstart handler.
... function dragstart_handler(event) { var dt = event.datatransfer; var idx = dt.mozitemcount; // add two new items to the drag transfer if (idx >= 0) { dt.mozsetdataat("text/uri-list","http://www.example.com/", idx); dt.mozsetdataat("text/html", "hello world", idx+1); } } specifications this method is not defined in any web standard.
DataTransfer.mozSourceNode - Web APIs
the datatransfer.mozsourcenode property is used to determine the node over which the mouse cursor was located when the the drag operation was initiated (for example, when a <button> was clicked).
... example this example shows the use of the mozsourcenode property in the dragend event handler.
DataTransferItem.type - Web APIs
some example types are: text/plain and text/html.
... example this example shows the use of the type property.
DataTransferItemList.DataTransferItem() - Web APIs
example this example shows how to use drag and drop.
...paragraph ...</p>", "text/html"); datalist.add("http://www.example.org","text/uri-list"); } function drop_handler(ev) { console.log("drop"); ev.preventdefault(); var data = ev.datatransfer.items; // loop through the dropped items and log their data for (var i = 0; i < data.length; i++) { if ((data[i].kind == 'string') && (data[i].type.match('^text/plain'))) { // this item is the target node data[i].getasstring(function (s){ ev.
DataTransferItemList.clear() - Web APIs
return value undefined example this example shows the use of the clear() method.
...paragraph ...</p>", "text/html"); datalist.add("http://www.example.org","text/uri-list"); } function drop_handler(ev) { console.log("drop"); ev.preventdefault(); var data = event.datatransfer.items; // loop through the dropped items and log their data for (var i = 0; i < data.length; i++) { if ((data[i].kind == 'string') && (data[i].type.match('^text/plain'))) { // this item is the target node data[i].getasstring(function (s){ ...
DataTransferItemList.length - Web APIs
example this example shows the use of the length property.
...paragraph ...</p>", "text/html"); datalist.add("http://www.example.org","text/uri-list"); } function drop_handler(ev) { console.log("drop"); ev.preventdefault(); var data = ev.datatransfer.items; // loop through the dropped items and log their data for (var i = 0; i < data.length; i++) { if ((data[i].kind == 'string') && (data[i].type.match('^text/plain'))) { // this item is the target node data[i].getasstring(function (s){ ev.
DedicatedWorkerGlobalScope.onmessage - Web APIs
}; example the following code snippet shows creation of a worker object using the worker() constructor.
... for a full example, see ourbasic dedicated worker example (run dedicated worker).
DedicatedWorkerGlobalScope.postMessage() - Web APIs
example the following code snippet shows worker.js, in which an onmessage handler is used to handle messages from the main script.
... for a full example, see ourbasic dedicated worker example (run dedicated worker).
DeprecationReportBody - Web APIs
properties id a string representing the deprecated feature that generated the report, for example navigatorgetusermedia.
... 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 reportingobserve...
Detecting device orientation - Web APIs
orientation example this example will work on any browser supporting the deviceorientation event and running on a device able to detect its orientation.
...{ x = -90}; // to make computation easier we shift the range of // x and y to [0,180] x += 90; y += 90; // 10 is half the size of the ball // it center the positioning point to the center of the ball ball.style.top = (maxy*y/180 - 10) + "px"; ball.style.left = (maxx*x/180 - 10) + "px"; } window.addeventlistener('deviceorientation', handleorientation); click here to open this example in a new window; because deviceorientation doesn't work in a cross-origin <iframe> in all browsers.
Using light sensors - Web APIs
window.addeventlistener("devicelight", function (event) { // read out the lux value var luminosity = event.value; alert(luminosity); }); example: window.addeventlistener('devicelight', function(event) { var bodybg= document.body.style; //event.value is the lux value returned by the sensor on the device if (event.value < 100) { alert('hey, you!
... you are working in a dark environment'); bodybg.backgroundcolor="lightgrey"; } else { bodybg.backgroundcolor="#fff"; } }); this example shows how the api can actually be used in the wild.
DeviceLightEvent - Web APIs
for example this may be useful to adjust the screen's brightness based on the current ambient light level in order to save energy or provide better readability.
... example window.addeventlistener('devicelight', function(event) { console.log(event.value); }); specifications no specification.
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 d...
... function dosomething() { console.info('dom loaded'); } if (document.readystate === 'loading') { // loading hasn't finished yet document.addeventlistener('domcontentloaded', dosomething); } else { // `domcontentloaded` has already fired dosomething(); } 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: cente...
Document: animationcancel event - Web APIs
examples this code adds a listener to the animationcancel event.
... document.addeventlistener('animationcancel', () => { console.log('animation canceled'); }); the same, but using the onanimationcancel property instead of addeventlistener(): document.onanimationcancel = () => { console.log('animation canceled'); }; 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.onanimationiteratio...
...n = () => { iterationcount++; console.log(`animation iteration count: ${iterationcount}`); }; see a live example of this event.
Document.createNodeIterator() - Web APIs
see the example.
... example const nodeiterator = document.createnodeiterator( document.body, nodefilter.show_element, { acceptnode(node) { return node.nodename.tolowercase() === 'p' ?
Document.documentElement - Web APIs
document.documentelement returns the element that is the root element of the document (for example, the <html> element for html documents).
... syntax const element = document.documentelement example const rootelement = document.documentelement; const firsttier = rootelement.childnodes; // firsttier is a nodelist of the direct children of the root element // such as <head> and <body> for (const child of firsttier) { // do something with each direct child of the root element } notes for any non-empty html document, documentelement will always be an <html> element.
Document.execCommand() - Web APIs
for example, insertimage requires the url of the image to insert.
... example an example of how to use it on codepen.
Document.exitFullscreen() - Web APIs
example this example causes the current document to toggle in and out of a full-screen presentation whenever the mouse button is clicked within it.
... document.onclick = function (event) { if (document.fullscreenelement) { document.exitfullscreen() .then(() => console.log("document exited form full screen mode")) .catch((err) => console.error(err)) } else { document.documentelement.requestfullscreen(); } } note: for a more complete example, see the example in element.requestfullscreen().
Document.forms - Web APIs
WebAPIDocumentforms
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="al...
...ert(document.forms[2].id);" value="paul's form" /> </form> </body> </html> getting an element from within a form var selectform = document.forms[index]; var selectformelement = document.forms[index].elements[index]; named form access <!doctype html> <html lang="en"> <head> <title>document.forms example</title> </head> <body> <form name="login"> <input name="email" type="email"> <input name="password" type="password"> <button type="submit">log in</button> </form> <script> var loginform = document.forms.login; // or document.forms['login'] loginform.elements.email.placeholder = 'test@example.com'; loginform.elements.password.placeholder = 'password'; </script> </body> </html> specifications specification status comment html living standardthe d...
Document.fullscreen - Web APIs
example this simple function reports whether or not full-screen mode is currently active, using the obsolete fullscreen property.
... function isdocumentinfullscreenmode() { return document.fullscreen; } this next example, on the other hand, uses the current fullscreenelement property to determine the same thing: function isdocumentinfullscreenmode() { return document.fullscreenelement !== null; } if fullscreenelement isn't null, this returns true, indicating that full-screen mode is in effect.
Document: fullscreenchange event - Web APIs
examples in this example, a handler for the fullscreenchange event is added to the document.
... if (document.fullscreenelement) { console.log(`element: ${document.fullscreenelement.id} entered full-screen mode.`); } else { console.log('leaving full-screen mode.'); } }); see element: fullscreenchange event for another example.
Document.getElementById() - Web APIs
example html <html> <head> <title>getelementbyid example</title> </head> <body> <p id="para">some text here</p> <button onclick="changecolor('blue');">blue</button> <button onclick="changecolor('red');">red</button> </body> </html> javascript function changecolor(newcolor) { var elem = document.getelementbyid('para'); elem.style.color = newcolor; } result usage notes the capitalizati...
... example <!doctype html> <html> <head> <meta charset="utf-8"> <title>document</title> </head> <body> <div id="parent-id"> <p>hello word1</p> <p id="test1">hello word2</p> <p>hello word3</p> <p>hello word4</p> </div> <script> var parentdom = document.getelementbyid('parent-id'); var test1 = parentdom.getelementbyid('test1'); //thr...
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 'tes...
...rent-id"); var test = parentdom.getelementsbyclassname("test"); // a list of matching elements, *not* the element itself console.log(test); //htmlcollection[1] var testtarget = parentdom.getelementsbyclassname("test")[0]; // the first element, as we wanted console.log(testtarget); //<p class="test">hello world 2</p> </script> </body> </html> multiple classes example document.getelementsbyclassname works very similarly to document.queryselector and document.queryselectorall.
Document.getElementsByTagName() - Web APIs
example in the following example, getelementsbytagname() starts from a particular parent element and searches top-down recursively through the dom from that parent element, building a collection of all descendant elements which match the tag name parameter.
... <!doctype html> <html lang="en"> <head> <meta charset="utf-8" /> <title>getelementsbytagname example</title> <script> function getallparaelems() { var allparas = document.getelementsbytagname('p'); var num = allparas.length; alert('there are ' + num + ' paragraph in this document'); } function div1paraelems() { var div1 = document.getelementbyid('div1'); var div1paras = div1.getelementsbytagname('p'); var num = div1paras.length; alert('the...
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.
... const para = document.queryselector('p'); document.addeventlistener('gotpointercapture', () => { console.log('i\'ve been captured!') }); para.addeventlistener('pointerdown', (event) => { para.setpointercapture(event.pointerid); }); the same example, using the ongotpointercapture event handler property: const para = document.queryselector('p'); document.ongotpointercapture = () => { console.log('i\'ve been captured!') }; para.addeventlistener('pointerdown', (event) => { para.setpointercapture(event.pointerid); }); specifications specification status pointer events obsolete ...
Document.hasFocus() - Web APIs
WebAPIDocumenthasFocus
for example, an active element within a popup window that is not the foreground doesn't have focus.
... example this example checks whether the document has focus every 300 milliseconds.
Document: keydown event - Web APIs
for example, a lowercase "a" will be reported as 65 by keydown and keyup, but as 97 by keypress.
...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.location - Web APIs
WebAPIDocumentlocation
this means that you can work with document.location as if it were a string in most cases: document.location = 'http://www.example.com' is a synonym of document.location.href = 'http://www.example.com'.
... 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.
... const para = document.queryselector('p'); document.addeventlistener('lostpointercapture', () => { console.log('i\'ve been released!') }); para.addeventlistener('pointerdown', (event) => { para.setpointercapture(event.pointerid); }); the same example, but using the onlostpointercapture event handler property: const para = document.queryselector('p'); document.onlostpointercapture = () => { console.log('i\'ve been released!') }; para.addeventlistener('pointerdown', (event) => { para.setpointercapture(event.pointerid); }); specifications specification status pointer events obsolete ...
Document.mozSetImageElement() - Web APIs
example this example changes the background of a <div> block each time the block is clicked by the user.
... view this example live.
Document.popupNode - Web APIs
in these other cases, for example when calling the popup's showpopup method, you may wish to set the popupnode property directly beforehand.
... syntax var node = document.popupnode; example <menupopup id="toolbarcontextmenu"> ...
Document.querySelector() - Web APIs
escaping special characters to match against an id or selectors that do not follow standard css syntax (by using a colon or space inappropriately, for example), you must escape the character with a backslash ("\").
...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.registerElement() - Web APIs
the name must contain a dash (-), for example my-tag.
... example here is a very simple example: var mytag = document.registerelement('my-tag'); now the new tag is registered in the browser.
Document: touchcancel event - Web APIs
the touchcancel event is fired when one or more touch points have been disrupted in an implementation-specific manner (for example, too many touch points are created).
... bubbles yes cancelable no interface touchevent event handler property ontouchcancel examples code samples for those events are available on the dedicated page: touch events.
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.
... to match id or selectors that do not follow the css syntax (by using semicolon or space inappropriately for example), it's mandatory to escape the wrong character with a double back slash: <div id="foo\bar"></div> <div id="foo:bar"></div> <script> document.queryselector('#foo\bar') // does not match anything document.queryselector('#foo\\\\bar') // match the first div document.queryselector('#foo:bar') // does not match anything document.queryselector('#foo\\:bar') // match the second div </script> specifications specification status comment selectors api level 2the definition of 'documentfragment.queryselector' in that specification.
DocumentOrShadowRoot.getSelection() - Web APIs
example function foo() { var selobj = document.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()), the object's tostring() method is called and the returned value is passed to the function.
... in the above example, selobj.tostring() is automatically called when it is passed to window.alert().
DynamicsCompressorNode.attack - Web APIs
example the below code demonstrates a simple usage of createdynamicscompressor() to add compression to an audio track.
... for a more complete example, have a look at our basic compressor example (view the source code).
DynamicsCompressorNode.knee - Web APIs
example the below code demonstrates a simple usage of createdynamicscompressor() to add compression to an audio track.
... for a more complete example, have a look at our basic compressor example (view the source code).
DynamicsCompressorNode.ratio - Web APIs
example the below code demonstrates a simple usage of createdynamicscompressor() to add compression to an audio track.
... for a more complete example, have a look at our basic compressor example (view the source code).
DynamicsCompressorNode.release - Web APIs
example the below code demonstrates a simple usage of createdynamicscompressor() to add compression to an audio track.
... for a more complete example, have a look at our basic compressor example (view the source code).
DynamicsCompressorNode.threshold - Web APIs
example the below code demonstrates a simple usage of createdynamicscompressor() to add compression to an audio track.
... for a more complete example, have a look at our basic compressor example (view the source code).
DynamicsCompressorNode - Web APIs
example the below code demonstrates a simple usage of createdynamicscompressor() to add compression to an audio track.
... for a more complete example, have a look at our basic compressor example (view the source code).
EffectTiming.easing - Web APIs
see github for a simple example that illustrates the difference between steps() and frames().
... 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'); // animat...
Element.clientTop - Web APIs
WebAPIElementclientTop
(actually might be math.round(parsefloat()).) for example, if the computed "border-top-width" is zero, then clienttop is also zero.
... syntax var top = element.clienttop; example in the following illustration, the client area is show in white.
Element: compositionend event - Web APIs
for example, this event could be fired after a user finishes entering a chinese character using a pinyin ime.
... bubbles yes cancelable yes interface compositionevent event handler property none examples const inputelement = document.queryselector('input[type="text"]'); inputelement.addeventlistener('compositionend', (event) => { console.log(`generated characters were: ${event.data}`); }); live example html <div class="control"> <label for="name">on macos, click in the textbox below,<br> then type <kbd>option</kbd> + <kbd>`</kbd>, then <kbd>a</kbd>:</label> <input type="text" id="example" name="example"> </div> <div class="event-log"> <label>event log:</label> <textarea readonly class="event-log-contents" rows="8" cols="25"></textarea> <button class="clear-log">clear</button> </div> css body { padding: .2rem; display: grid; ...
Element: compositionstart event - Web APIs
for example, this event could be fired after a user starts entering a chinese character using a pinyin ime.
... 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"> </div> <div class="event-log"> <label>event log:</label> <textarea readonly class="event-log-contents" rows="8" cols="25"></textarea> <button class="clear-log">clear</button> </div> css body { padding: .2rem; display: grid; ...
Element: compositionupdate event - Web APIs
for example, this event could be fired while a user enters a chinese character using a pinyin ime.
... bubbles yes cancelable yes interface compositionevent event handler property none examples const inputelement = document.queryselector('input[type="text"]'); inputelement.addeventlistener('compositionupdate', (event) => { console.log(`generated characters were: ${event.data}`); }); live example html <div class="control"> <label for="name">on macos, click in the textbox below,<br> then type <kbd>option</kbd> + <kbd>`</kbd>, then <kbd>a</kbd>:</label> <input type="text" id="example" name="example"> </div> <div class="event-log"> <label>event log:</label> <textarea readonly class="event-log-contents" rows="8" cols="25"></textarea> <button class="clear-log">clear</button> </div> css body { padding: .2rem; display: grid;...
Element.computedStyleMap() - Web APIs
examples we start with some simple html: a paragraph with a link, and a definition list to which we will add all the css property / value pairs.
... <p> <a href="https://example.com">link</a> </p> <dl id="regurgitation"></dl> we add a little bit of css a { --colour: red; color: var(--colour); } we add javascript to grab our link and return back a definition list of all the css property values using computedstylemap().
Element: error event - Web APIs
for example, if a script has an execution error or an image can't be found or is invalid.
... 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; display: flex; align-items: center; justify-content: center; } .event-log { grid-area: log; } .event-log-contents { resize: none; }...
Element.getElementsByTagNameNS() - Web APIs
for example, if you need to look for xhtml elements, use the xhtml namespace uri, http://www.w3.org/1999/xhtml.
... example // check the alignment on a number of cells in a table in an xhtml document.
Element: keydown event - Web APIs
for example, a lowercase "a" will be reported as 65 by keydown and keyup, but as 97 by keypress.
...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
for example, a lowercase "a" will be reported as 65 by keydown and keyup, but as 97 by keypress.
...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.localName - Web APIs
WebAPIElementlocalName
example (must be served with xml content type, such as text/xml or application/xhtml+xml.) <html xmlns="http://www.w3.org/1999/xhtml" xmlns:svg="http://www.w3.org/2000/svg"> <head> <script type="application/javascript"><![cdata[ function test() { var text = document.getelementbyid('text'); var circle = document.getelementbyid('circle'); text.value = "<svg:circle> has:\n" + "localname = '" + circle.localname + "'\n" + "namespaceuri = '" ...
...for example, in the qualified name ecomm:partners, partners is the local name and ecomm is the prefix: <ecomm:business id="soda_shop" type="brick_n_mortar" xmlns:ecomm="http://example.com/ecomm"> <ecomm:partners> <ecomm:partner id="1001">tony's syrup warehouse </ecomm:partner> </ecomm:partner> </ecomm:business> note: in gecko 1.9.2 and earlier, the property returns the upper-cased version of ...
Element: mouseenter event - Web APIs
examples the mouseover documentation has an example illustrating the difference between mouseover and mouseenter.
... mouseenter the following trivial example uses the mouseenter event to change the border on the div when the mouse enters the space alloted to it.
Element: mouseleave event - Web APIs
examples the mouseout documentation has an example illustrating the difference between mouseout and mouseleave.
... mouseleave the following trivial example uses the mouseenter event to change the border on the <div> when the mouse enters the space alloted to it.
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.
... mouseout and mouseleave the following example illustrates the difference between mouseout and mouseleave events.
Element.outerHTML - Web APIs
WebAPIElementouterHTML
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"> ...
...for example: var div = document.createelement("div"); div.outerhtml = "<div class=\"test\">test</div>"; console.log(div.outerhtml); // output: "<div></div>" also, while the element will be replaced in the document, the variable whose outerhtml property was set will still hold a reference to the original element: var p = document.getelementsbytagname("p")[0]; console.log(p.nodename); // shows: "p" p.outerh...
Element.scrollHeight - Web APIs
example padding-top lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
...for example: html <form name="registration"> <p> <textarea id="rules">lorem ipsum dolor sit amet, consectetur adipiscing elit.
Element: select event - Web APIs
for example, in html, select events can be dispatched only on form <input type="text"> and <textarea> elements.
... examples selection logger <input value="try selecting some text in this element."> <p id="log"></p> function logselection(event) { const log = document.getelementbyid('log'); const selection = event.target.value.substring(event.target.selectionstart, event.target.selectionend); log.textcontent = `you selected: ${selection}`; } const input = document.queryselector('input'); input.addeventlistener('select', logselection); onselect equivalent you can also set up the event handler using the onselect property: input.onselect = logselection; specifications specification status ui eventsthe definition of 'select' in that specification.
Element.setAttribute() - Web APIs
see the example below for a practical demonstration.
... example in the following example, setattribute() is used to set attributes on a <button>.
Element.slot - Web APIs
WebAPIElementslot
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.
...here is one such example: <my-paragraph> <span slot="my-text">let's have some different text!</span> </my-paragraph> in our javascript file we get a reference to the <span> shown above, then log a reference to the name of the corresponding <slot> element.
Element: touchcancel event - Web APIs
the touchcancel event is fired when one or more touch points have been disrupted in an implementation-specific manner (for example, too many touch points are created).
... bubbles yes cancelable no interface touchevent event handler property ontouchcancel examples code samples for those events are available on the dedicated page: touch events.
Event.explicitOriginalTarget - Web APIs
for example, mouse events are retargeted to their parent node when they happen over text nodes (see bug 185889), and in that case currenttarget will show the parent and explicitoriginaltarget will show the text node.
... example this property can be used with <command> to get the event details of the original object calling the command.
EventListener - Web APIs
this is shown in the example below.
... example html <button id="btn">click here!</button> javascript const buttonelement = document.getelementbyid('btn'); // add a handler for the 'click' event by providing a callback function.
EventTarget.removeEventListener() - Web APIs
for example, consider this call to addeventlistener(): element.addeventlistener("mousedown", handlemousedown, true); now consider each of these two calls to removeeventlistener(): element.removeeventlistener("mousedown", handlemousedown, false); // fails element.removeeventlistener("mousedown", handlemousedown, true); // succeeds the first call fails because the value of usecapture doesn't matc...
... example this example shows how to add a mouseover-based event listener that removes a click-based event listener.
EventTarget - Web APIs
for example xmlhttprequest, audionode, audiocontext, and others.
... void seteventhandler(domstring type, eventhandler handler) eventhandler geteventhandler(domstring type) example simple implementation of eventtarget var eventtarget = function() { this.listeners = {}; }; eventtarget.prototype.listeners = null; eventtarget.prototype.addeventlistener = function(type, callback) { if (!(type in this.listeners)) { this.listeners[type] = []; } this.listeners[type].push(callback); }; eventtarget.prototype.removeeventlistener = function(type, callback) { if (!(ty...
FederatedCredential - Web APIs
openid connect is an example of a federated identity provider framework.
... 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.
FetchEvent.replacesClientId - Web APIs
for example, when navigating from page a to page b replacesclientid is the id of the client associated with page a.
... example self.addeventlistener('fetch', function(event) { console.log(event.replacesclientid); }); specifications specification status comment service workersthe definition of 'replacesclientid' in that specification.
FetchEvent.resultingClientId - Web APIs
for example, when navigating from page a to page b resultingclientid is the id of the client associated with page b.
... example self.addeventlistener('fetch', function(event) { console.log(event.resultingclientid); }); specifications specification status comment service workersthe definition of 'resultingclientid' in that specification.
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-...
...contents { width: 18rem; height: 5rem; border: 1px solid black; margin: .2rem; padding: .2rem; } .example { display: grid; grid-template-areas: "select log" "preview log"; } .file-select { grid-area: select; } .preview { grid-area: preview; } .event-log { grid-area: log; } .event-log>label { display: block; } .event-log-contents { resize: none; } js const fileinput = document.queryselector('input[type="file"]'); const preview = document.queryselector('img.preview'); const eventlog = document.queryselector('.event-log-contents'); const reader = new filereader(); function handleevent(event) { eventlog.textcontent = eventlog.textcontent + `${event.type}: ${event.loaded} bytes transferred\n`; if (event.type === "load") { ...
FileReader: error event - Web APIs
the error event is fired when the read failed due to an error (for example, because the file was not found or not readable).
... 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); } } fileinput.addeventlistener('change', handleselected); specifications specification status fil...
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:...
... 1px solid black; margin: .2rem; padding: .2rem; } .example { display: grid; grid-template-areas: "select log" "preview log"; } .file-select { grid-area: select; } .preview { grid-area: preview; } .event-log { grid-area: log; } .event-log>label { display: block; } .event-log-contents { resize: none; } js const fileinput = document.queryselector('input[type="file"]'); const preview = document.queryselector('img.preview'); const eventlog = document.queryselector('.event-log-contents'); const reader = new filereader(); function handleevent(event) { eventlog.textcontent = eventlog.textcontent + `${event.type}: ${event.loaded} bytes transferred\n`; if (event.type === "load") { preview.src = reader.result; } } function addli...
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; heig...
...ht: 5rem; border: 1px solid black; margin: .2rem; padding: .2rem; } .example { display: grid; grid-template-areas: "select log" "preview log"; } .file-select { grid-area: select; } .preview { grid-area: preview; } .event-log { grid-area: log; } .event-log>label { display: block; } .event-log-contents { resize: none; } js const fileinput = document.queryselector('input[type="file"]'); const preview = document.queryselector('img.preview'); const eventlog = document.queryselector('.event-log-contents'); const reader = new filereader(); function handleevent(event) { eventlog.textcontent = eventlog.textcontent + `${event.type}: ${event.loaded} bytes transferred\n`; if (event.type === "load") { preview.src = reader.result; ...
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; ...
... border: 1px solid black; margin: .2rem; padding: .2rem; } .example { display: grid; grid-template-areas: "select log" "preview log"; } .file-select { grid-area: select; } .preview { grid-area: preview; } .event-log { grid-area: log; } .event-log>label { display: block; } .event-log-contents { resize: none; } js const fileinput = document.queryselector('input[type="file"]'); const preview = document.queryselector('img.preview'); const eventlog = document.queryselector('.event-log-contents'); const reader = new filereader(); function handleevent(event) { eventlog.textcontent = eventlog.textcontent + `${event.type}: ${event.loaded} bytes transferred\n`; if (event.type === "load") { preview.src = reader.result; } } functi...
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...
...; border: 1px solid black; margin: .2rem; padding: .2rem; } .example { display: grid; grid-template-areas: "select log" "preview log"; } .file-select { grid-area: select; } .preview { grid-area: preview; } .event-log { grid-area: log; } .event-log>label { display: block; } .event-log-contents { resize: none; } js const fileinput = document.queryselector('input[type="file"]'); const preview = document.queryselector('img.preview'); const eventlog = document.queryselector('.event-log-contents'); const reader = new filereader(); function handleevent(event) { eventlog.textcontent = eventlog.textcontent + `${event.type}: ${event.loaded} bytes transferred\n`; if (event.type === "load") { preview.src = reader.result; } } fun...
FileReader - Web APIs
see using files from web applications for details and examples.
... abort fired when a read has been aborted, for example because the program called filereader.abort().
FileSystemEntry.getParent() - Web APIs
this can happen, for example, if the file system's cached state differs from the actual state of the file system.
... example this example renames the file specified by the variable fileentry to "newname.html".
FileSystemEntry - Web APIs
for example, if your app is in http://www.html5rocks.com, open filesystem:http://www.html5rocks.com/temporary/ in a tab.
... example to see an example of how tourl() works, see the method description.
FileHandle API - Web APIs
that said, as the name does not match any real filename it can be an empty string, for example, and it doesn't even have to be unique.
...for example, there are many apis that expect blob or file objects such as filereader (which can be easier to use to read the whole file) or xmlhttprequest.
Using FormData Objects - Web APIs
this example builds a formdata instance containing values for fields named "username", "accountnum", "userfile" and "webmasterfile", then uses the xmlhttprequest method send() to send the form's data.
... var formdata = new formdata(someformelement); for example: var formelement = document.queryselector("form"); var request = new xmlhttprequest(); request.open("post", "submitform.php"); request.send(new formdata(formelement)); you can also append additional data to the formdata object between retrieving it from a form and sending it, like this: var formelement = document.queryselector("form"); var formdata = new formdata(formelement); var request = n...
FormData.append() - Web APIs
WebAPIFormDataappend
example the following line creates an empty formdata object: var formdata = new formdata(); // currently empty you can add key/value pairs to this using formdata.append: formdata.append('username', 'chris'); formdata.append('userpic', myfileinput.files[0], 'chris.jpg'); as with regular form data, you can append multiple values with the same name.
... for example (and being compatible with php's naming conventions by adding [] to the name): formdata.append('userpic[]', myfileinput.files[0], 'chris1.jpg'); formdata.append('userpic[]', myfileinput.files[1], 'chris2.jpg'); this technique makes it simpler to process multi-file uploads because the resultant data structure is more conducive to looping.
GainNode.gain - Web APIs
WebAPIGainNodegain
example the following example shows basic usage of an audiocontext to create a gainnode, which is then used to mute and unmute the audio when a mute button is clicked by changing the gain property value.
... the below snippet wouldn't work as is — for a complete working example, check out our voice-change-o-matic demo (view source.) <div> <button class="mute">mute button</button> </div> var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); var gainnode = audioctx.creategain(); var mute = document.queryselector('.mute'); var source; if (navigator.mediadevices.getusermedia) { navigator.mediadevices.getusermedia ( // constraints - only audio needed for this app { audio: true }, // success callback function(stream) { source = audioctx.createmediastreamsource(stream); }, // error callback function(err) { console.log('the following gum error occured: ' + err); } ); } else { console.log('getusermedia not supported on your browser...
GainNode - Web APIs
WebAPIGainNode
example the following example shows basic usage of an audiocontext to create a gainnode, which is then used to mute and unmute the audio when a mute button is clicked by changing the gain property value.
... the below snippet wouldn't work as is — for a complete working example, check out our voice-change-o-matic demo (view source.) <div> <button class="mute">mute button</button> </div> var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); var gainnode = audioctx.creategain(); var mute = document.queryselector('.mute'); var source; if (navigator.mediadevices.getusermedia) { navigator.mediadevices.getusermedia ( // constraints - only audio needed for this app { audio: true }, // success callback function(stream) { source = audioctx.createmediastreamsource(stream); }, // error callback function(err) { console.log('the following gum error occured: ' + err); } ); } else { console.log('getusermedia not supported on your browser...
Gamepad.buttons - Web APIs
WebAPIGamepadbuttons
syntax readonly attribute gamepadbutton[] buttons; example the following code is taken from my gamepad api button demo (you can view the demo live, and find the source code on github.) note the code fork — in chrome navigator.getgamepads needs a webkit prefix and the button values are stores as an array of double values, whereas in firefox navigator.getgamepads doesn't need a prefix, and the button values are stored as an array of gamepadbutton object...
...in this simple example i've just allowed either.
Gamepad.id - Web APIs
WebAPIGamepadid
for example, a ps2 controller returned 810-3-usb gamepad.
... syntax readonly attribute domstring id; example window.addeventlistener("gamepadconnected", function() { var gp = navigator.getgamepads()[0]; gamepadinfo.innerhtml = "gamepad connected at index " + gp.index + ": " + gp.id + "."; }); value a string.
GamepadButton - Web APIs
example the following code is taken from my gamepad api button demo (you can view the demo live, and find the source code on github.) note the code fork — in chrome navigator.getgamepads needs a webkit prefix and the button values are stored as an array of double values, whereas in firefox navigator.getgamepads doesn't need a prefix, and the button values are stored as an array of gamepadbutton object...
...in this simple example i've just allowed either.
GeolocationCoordinates.longitude - Web APIs
examples in this simple example, we fetch the user's location and display the resulting coordinates once they're returned.
...</p> <button id="get-location"> get my location </button> result take this example for a test drive here: specifications specification status comment geolocation apithe definition of 'coordinates.longitude' in that specification.
GlobalEventHandlers.onanimationcancel - Web APIs
this can happen, for example, when the animation-name is changed such that the animation is removed, or when the animating node is hidden—either directly or because any of its containing nodes are hidden—using css.
... example html <div class="main"> <div id="box" onanimationcancel="handlecancelevent(event);"> <div id="text">box</div> </div> </div> <div class="button" id="togglebox"> hide the box </div> <pre id="log"></pre> css :root { --boxwidth: 50px; } .main { width: 300px; height: 300px; border: 1px solid black; } .button { cursor: pointer; width: 300px; border: 1px solid black; f...
GlobalEventHandlers.onanimationend - Web APIs
example html content <div class="main"> <div id="box"> <div id="text">box</div> </div> </div> <div class="button" id="play"> play animation </div> <pre id="log"></pre> css content :root { --boxwidth:50px; } .main { width: 300px; height:300px; border: 1px solid black; } .button { cursor: pointer; width: 300px; border: 1px solid black; font-size: 16px; text-align: cen...
... up a handler for a click on the button that runs the animation: document.getelementbyid("play").addeventlistener("click", function(event) { document.getelementbyid("box").classname = "slideanimation"; event.target.style.display = "none"; }, false); this sets the class of the box we want to animate to the class that contains the animation description, then hides the play button because this example will only run the animation once.
GlobalEventHandlers.onanimationiteration - Web APIs
example let's create an animation which automatically pauses at the end of each iteration, allowing the user to choose whether or not to start the next iteration.
... much of this code is the same as in other examples of animation events, so it may look familiar.
GlobalEventHandlers.onanimationstart - Web APIs
example html content <div class="main"> <div id="box"> <div id="text">box</div> </div> </div> <div class="button" id="play"> play animation </div> <pre id="log"></pre> css content :root { --boxwidth:50px; } .main { width: 300px; height:300px; border: 1px solid black; } .button { cursor: pointer; width: 300px; border: 1px solid black; font-size: 16px; text-align: cen...
... up a handler for a click on the button that runs the animation: document.getelementbyid("play").addeventlistener("click", function(event) { document.getelementbyid("box").classname = "slideanimation"; event.target.style.display = "none"; }, false); this sets the class of the box we want to animate to the class that contains the animation description, then hides the play button because this example will only run the animation once.
GlobalEventHandlers.onchange - Web APIs
this may be done, for example, by clicking outside of the control or by using the tab key to switch to a different control.
... example this example logs the number of characters in an <input> element, every time you modify its contents and then change focus away from it.
GlobalEventHandlers.oncontextmenu - Web APIs
examples disabling context menus this snippet prevents context menus from opening in the window.
...is it disabled?<p> javascript window.oncontextmenu = (e) => { e.preventdefault(); } result pausing an animation this example pauses a spinning shape whenever you open the context menu.
GlobalEventHandlers.ondblclick - Web APIs
example this example logs the position of double clicks.
... html <p>double click anywhere in this example.</p> <p id="log"></p> javascript let log = document.getelementbyid('log'); document.ondblclick = logdoubleclick; function logdoubleclick(e) { log.textcontent = `position: (${e.clientx}, ${e.clienty})`; } result specifications specification status comment html living standardthe definition of 'ondblclick' in that specification.
GlobalEventHandlers.oninvalid - Web APIs
example this example demonstrates oninvalid and onsubmit event handlers on a form.
...ment.getelementbyid('form'); const error = document.getelementbyid('error'); const city = document.getelementbyid('city'); const thanks = document.getelementbyid('thanks'); city.oninvalid = invalid; form.onsubmit = submit; function invalid(event) { error.removeattribute('hidden'); } function submit(event) { form.setattribute('hidden', ''); thanks.removeattribute('hidden'); // for this example, don't actually submit the form event.preventdefault(); } result specification specification status comment html living standardthe definition of 'oninvalid' in that specification.
GlobalEventHandlers.onkeypress - Web APIs
examples basic example this example logs the keyboardevent.code value whenever you press a key inside the <input> element.
... html <input> <p id="log"></p> javascript const input = document.queryselector('input'); const log = document.getelementbyid('log'); input.onkeypress = logkey; function logkey(e) { log.textcontent += ` ${e.code}`; } result filter keys with a regular expression this example filters the characters typed into a form field using a regular expression.
GlobalEventHandlers.onmousemove - Web APIs
examples tooltips this example creates link tooltips that follow your mouse.
... node.textcontent = event.target.dataset.tooltip; node.removeattribute('hidden'); }; this.hide = function() { node.setattribute('hidden', ''); }; })(); const links = document.queryselectorall('a'); links.foreach(link => { link.onmouseover = tooltip.show; link.onmousemove = tooltip.follow; link.onmouseout = tooltip.hide; }); result draggable elements we also have an example available showing the use of the onmousemove event handler with draggable objects — view the example in action.
GlobalEventHandlers.onmouseout - Web APIs
for example, when the mouse moves off of an image in the web page, the mouseout event is raised for that image element.
... syntax element.onmouseout = function; example this example adds an onmouseout and an onmouseover event to a paragraph.
GlobalEventHandlers.onpointerdown - Web APIs
example this example demonstrates how to watch for and act upon pointerdown events using onpointerdown.
... we also have a handler for pointerup events: targetbox.onpointerup = handleup; function handleup(evt) { targetbox.innerhtml = "tap me, click me, or touch me!"; evt.preventdefault(); } this code's job is to just restore the original text into the target box after the user's interaction with the element ends (for example, when they release the mouse button, or when they lift the stylus or finger from the screen).
GlobalEventHandlers.onpointerleave - Web APIs
the global event handler for the pointerleave event, which is delivered to a node when the pointer (mouse cursor, fingertip, etc.) exits its hit test area (for example, if the cursor exits an element or window's content area).
... example this example shows two ways to use onpointerleave to set an element's pointerleave event handler.
GlobalEventHandlers.onsubmit - Web APIs
example this example demonstrates oninvalid and onsubmit event handlers on a form.
...ment.getelementbyid('form'); const error = document.getelementbyid('error'); const city = document.getelementbyid('city'); const thanks = document.getelementbyid('thanks'); city.oninvalid = invalid; form.onsubmit = submit; function invalid(event) { error.removeattribute('hidden'); } function submit(event) { form.setattribute('hidden', ''); thanks.removeattribute('hidden'); // for this example, don't actually submit the form event.preventdefault(); } result specifications specification status comment html living standardthe definition of 'onsubmit' in that specification.
Gyroscope.x - Web APIs
WebAPIGyroscopex
example the gyroscope is typically read in the sensor.onreading event callback.
... in the example below this occurs sixty times a second.
Gyroscope.y - Web APIs
WebAPIGyroscopey
example the gyroscope is typically read in the sensor.onreading event callback.
... in the example below this occurs sixty times a second.
Gyroscope.z - Web APIs
WebAPIGyroscopez
example the gyroscope is typically read in the sensor.onreading event callback.
... in the example below this occurs sixty times a second.
Gyroscope - Web APIs
WebAPIGyroscope
example the gyroscope is typically read in the sensor.onreading event callback.
... in the example below this occurs sixty times a second.
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.
... example <audio msaudiocategory="backgroundcapablemedia" controls="controls"> <source src="song.mp3"/> </audio> ...
HTMLCanvasElement.getContext() - Web APIs
contextattributes you can use several context attributes when creating your rendering context, for example: const gl = canvas.getcontext('webgl', { antialias: false, depth: false }); 2d context attributes: alpha: boolean that indicates if the canvas contains an alpha channel.
... 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.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.
... for example, you could conditionally set it to true if mimetype == 'image/jpeg', or similar, to gain performance in your application when translucency is not needed.
HTMLCollection.item - Web APIs
see the example below.
... example var c = document.images; // this is an htmlcollection var img0 = c.item(0); // you can use the item() method this way var img1 = c[1]; // but this notation is easier and more common ...
HTMLDialogElement: cancel event - Web APIs
for example, the browser might fire this event when the user presses the esc key or clicks a "close dialog" button which is part of the browser's ui.
... 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) => { result.textcontent = 'dialog was canceled'; }); const opendialog = document.queryselector('.open-dialog'); opendialog.addeventlistener('click', () => { if (typeof dialog.showmodal === 'function') { dialog.showmodal(); result.textcontent = ''; } else { ...
HTMLDialogElement.close() - Web APIs
examples the following example shows a simple button that, when clicked, opens a <dialog> containing a form via the showmodal() method.
... // update button opens a modal dialog updatebutton.addeventlistener('click', function() { dialog.showmodal(); opencheck(dialog); }); // form cancel button closes the dialog box cancelbutton.addeventlistener('click', function() { dialog.close('animalnotchosen'); opencheck(dialog); }); })(); </script> note: you can find this example on github as htmldialogelement-basic (see it live also).
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.
... // update button opens a modal dialog updatebutton.addeventlistener('click', function() { dialog.showmodal(); opencheck(dialog); }); // form cancel button closes the dialog box cancelbutton.addeventlistener('click', function() { dialog.close('animalnotchosen'); opencheck(dialog); }); })(); </script> note: you can find this example on github as htmldialogelement-basic (see it live also).
HTMLDialogElement.returnValue - Web APIs
examples the following example displays a button to open a <dialog> containing a form via the showmodal() method.
...lse if (returnvalue === 'confirm') { // user chose a favorite animal, do something with it } } // “update details” button opens the <dialog> modally updatebutton.addeventlistener('click', function() { dialog.showmodal(); opencheck(dialog); handleuserinput(dialog.returnvalue); }); })(); </script> note: you can find this example on github as htmldialogelement-basic (see it live also).
HTMLDialogElement.showModal() - Web APIs
examples the following example shows a simple button that, when clicked, opens a <dialog> containing a form via the showmodal() method.
... // update button opens a modal dialog updatebutton.addeventlistener('click', function() { dialog.showmodal(); opencheck(dialog); }); // form cancel button closes the dialog box cancelbutton.addeventlistener('click', function() { dialog.close('animalnotchosen'); opencheck(dialog); }); })(); </script> note: you can find this example on github as htmldialogelement-basic (see it live also).
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.
... // update button opens a modal dialog updatebutton.addeventlistener('click', function() { dialog.showmodal(); opencheck(dialog); }); // form cancel button closes the dialog box cancelbutton.addeventlistener('click', function() { dialog.close('animalnotchosen'); opencheck(dialog); }); })(); </script> note: you can find this example on github as htmldialogelement-basic (see it live also).
HTMLElement: gotpointercapture event - Web APIs
bubbles yes cancelable no interface pointerevent event handler property ongotpointercapture examples this example gets a <p> element and listens for the gotpointercapture event.
... const para = document.queryselector('p'); para.addeventlistener('gotpointercapture', () => { console.log('i\'ve been captured!') }); para.addeventlistener('pointerdown', (event) => { para.setpointercapture(event.pointerid); }); the same example, using the ongotpointercapture event handler property: const para = document.queryselector('p'); para.ongotpointercapture = () => { console.log('i\'ve been captured!') }; para.addeventlistener('pointerdown', (event) => { para.setpointercapture(event.pointerid); }); specifications specification status pointer events obsolete ...
HTMLElement.lang - Web APIs
WebAPIHTMLElementlang
common examples include "en" for english, "ja" for japanese, "es" for spanish and so on.
... example // this snippet compares the base language and // redirects to another url based on language if (document.documentelement.lang === "en") { window.location.href = "some_document.html.en"; } else if (document.documentelement.lang === "ru") { window.location.href = "some_document.html.ru"; } specification specification status comment document object model (dom) lev...
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.
... const para = document.queryselector('p'); para.addeventlistener('lostpointercapture', () => { console.log('i\'ve been released!') }); para.addeventlistener('pointerdown', (event) => { para.setpointercapture(event.pointerid); }); the same example, but using the onlostpointercapture event handler property: const para = document.queryselector('p'); para.onlostpointercapture = () => { console.log('i\'ve been released!') }; para.addeventlistener('pointerdown', (event) => { para.setpointercapture(event.pointerid); }); specifications specification status pointer events obsolete ...
HTMLElement.offsetHeight - Web APIs
if the element is hidden (for example, by setting style.display on the element or one of its ancestors to "none"), then 0 is returned.
... example the example image above shows a scrollbar and an offsetheight which fits on the window.
HTMLElement.offsetWidth - Web APIs
if the element is hidden (for example, by setting style.display on the element or one of its ancestors to "none"), then 0 is returned.
... example specification specification status comment css object model (cssom) view modulethe definition of 'offsetwidth' in that specification.
HTMLFormElement.elements - Web APIs
example quick syntax example in this example, we see how to obtain the list of form controls as well as how to access its members by index and by name or id.
... <form id="my-form"> <input type="text" name="username"> <input type="text" name="full-name"> <input type="password" name="password"> </form> var inputs = document.getelementbyid("my-form").elements; var inputbyindex = inputs[0]; var inputbyname = inputs["username"]; accessing form controls this example gets the form's element list, then iterates over the list, looking for <input> elements of type "text" so that some form of processing can be performed on them.
HTMLIFrameElement.referrerPolicy - Web APIs
the document https://example.com/page.html will send the referrer https://example.com/.
... 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.
HTMLImageElement.decode() - Web APIs
usage notes one potential use case for decode(): when loading very large images (for example, in an online photo album), you can present a low resolution thumbnail image initially and then replace that image with the full-resolution image by instantiating a new htmlimageelement, setting its source to the full-resolution image's url, then using decode() to get a promise which is resolved once the full-resolution image is ready for use.
... examples the following example shows how to use the decode() method to control when an image is appended to the dom.
HTMLImageElement.height - Web APIs
example in this example, two different sizes are provided for an image of a clock using the srcset attribute.
... var clockimage = document.queryselector("img"); let output = document.queryselector(".size"); const updateheight = event => { output.innertext = clockimage.height; }; window.addeventlistener("load", updateheight); window.addeventlistener("resize", updateheight); result this example may be easier to try out in its own window.
HTMLImageElement.sizes - Web APIs
example in this example, a blog-like layout is created, displaying some text and an image which for which three size points are specified, depending on the width of the window.
... buttons at the bottom of the example let you actually modify the sizes property slightly, switching the largest of the three widths for the image between 40em and 50em.
HTMLImageElement.width - Web APIs
example in this example, two different sizes are provided for an image of a clock using the srcset attribute.
... var clockimage = document.queryselector("img"); let output = document.queryselector(".size"); const updatewidth = event => { output.innertext = clockimage.width; }; window.addeventlistener("load", updatewidth); window.addeventlistener("resize", updatewidth); result this example may be easier to try out in its own window.
HTMLImageElement.x - Web APIs
example the example below demonstrates the use of the htmlimageelement properties x and y.
... html in this example, we see a table showing information about users of a web site, including their user id, their full name, and their avatar image.
HTMLImageElement.y - Web APIs
example the example below demonstrates the use of the htmlimageelement properties x and y.
... html in this example, we see a table showing information about users of a web site, including their user id, their full name, and their avatar 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.
... in this example, when an invalid event fires because of an invalid value in the input, the invalid value is logged.
HTMLInputElement.stepDown() - Web APIs
if the value before invoking the stepdown() method is invalid, for example, if it doesn't match the constraints set by the step attribute, invoking the stepdown() method will return a value that does match the form controls constraints.
... example click the button in this example to increment the number input type: html <p> <label>enter a number between 0 and 400 that is divisible by 5: <input type="number" step="5" id="thenumber" min="0" max="400"> </label> </p> <p> <label>enter how many values of step you would like to increment by or leave it blank: <input type="number" step="1" id="decrementer" min="-2" max="15"> </lab...
HTMLInputElement.webkitdirectory - Web APIs
for example, consider this file system: photoalbums birthdays jamie's 1st birthday pic1000.jpg pic1004.jpg pic1044.jpg don's 40th birthday pic2343.jpg pic2344.jpg pic2355.jpg pic2356.jpg vacations mars pic5533.jpg pic5534.jpg pic5556.jpg pic...
... example in this example, a directory picker is presented which lets the user choose one or more directories.
HTMLMediaElement.currentSrc - Web APIs
this could happen, for example, if the web server selects a media file based on the resolution of the user's display.
... example var obj = document.createelement('video'); console.log(obj.currentsrc); // "" specifications specification status comment html living standardthe definition of 'htmlmediaelement.currentsrc' in that specification.
HTMLMediaElement: emptied event - Web APIs
the emptied event is fired when the media has become empty; for example, this event is sent if the media has already been loaded (or partially loaded), and the load() method is called to reload it.
... 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.error - Web APIs
example this example establishes a video element and adds an error handler to it; the error handler simply logs the details to console.
... var videoelement = document.createelement('video'); videoelement.onerror = function() { console.log("error " + videoelement.error.code + "; details: " + videoelement.error.message); } videoelement.src = "https://example.com/bogusvideo.mp4"; specifications specification status comment html living standardthe definition of 'htmlmediaelement.error' in that specification.
HTMLMediaElement: error event - Web APIs
the error event is fired when the resource could not be loaded due to an error (for example, a network connectivity problem).
... 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: 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...
... eventlog.textcontent + `${event.type}\n`; } video.addeventlistener('loadstart', handleevent); video.addeventlistener('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 ...
HTMLMediaElement.networkState - Web APIs
examples this example will listen for the audio element to begin playing and then check if it is still loading data.
... <audio id="example" preload="auto"> <source src="sound.ogg" type="audio/ogg" /> </audio> var obj = document.getelementbyid('example'); obj.addeventlistener('playing', function() { if (obj.networkstate === 2) { // still loading...
HTMLMediaElement.playbackRate - Web APIs
the audio is muted when the fast forward or slow motion is outside a useful range (for example, gecko mutes the sound outside the range 0.25 to 5.0).
...(default: 1.0) example var obj = document.createelement('video'); console.log(obj.playbackrate); // expected output: 1 specifications specification status comment html living standardthe definition of 'htmlmediaelement.playbackrate' 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 { ...
... eventlog.textcontent + `${event.type}\n`; } video.addeventlistener('loadstart', handleevent); video.addeventlistener('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 ...
HTMLMediaElement - Web APIs
for example, 44100 samples per second is the sample rate used by cd audio.
... emptied fired when the media has become empty; for example, when the media has already been loaded (or partially loaded), and the htmlmediaelement.load() method is called to reload it.
HTMLScriptElement.referrerPolicy - Web APIs
the document https://example.com/page.html will send the referrer https://example.com/.
... 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.
HTMLSlotElement.assignedNodes() - Web APIs
examples the following snippet is taken from our slotchange example (see it live also).
...eryselectorall('slot'); slots[1].addeventlistener('slotchange', function(e) { let nodes = slots[1].assignednodes(); console.log('element in slot "' + slots[1].name + '" changed to "' + nodes[0].outerhtml + '".'); }); here we grab references to all the slots, then add a slotchange event listener to the 2nd slot in the template — which is the one that keeps having its contents changed in the example.
HTMLSlotElement.name - Web APIs
examples the following snippet is taken from our slotchange example (see it live also).
...eryselectorall('slot'); slots[1].addeventlistener('slotchange', function(e) { let nodes = slots[1].assignednodes(); console.log('element in slot "' + slots[1].name + '" changed to "' + nodes[0].outerhtml + '".'); }); here we grab references to all the slots, then add a slotchange event listener to the 2nd slot in the template — which is the one that keeps having its contents changed in the example.
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).
...wroot.queryselectorall('slot'); slots[1].addeventlistener('slotchange', function(e) { let nodes = slots[1].assignednodes(); console.log('element in slot "' + slots[1].name + '" changed to "' + nodes[0].outerhtml + '".'); }); here we grab references to all the <slot>s, then add a slotchange event listener to the template's second slot — which is the one which has its contents changed in the example.
HTMLSlotElement - Web APIs
examples the following snippet is taken from our slotchange example (see it live also).
...eryselectorall('slot'); slots[1].addeventlistener('slotchange', function(e) { let nodes = slots[1].assignednodes(); console.log('element in slot "' + slots[1].name + '" changed to "' + nodes[0].outerhtml + '".'); }); here we grab references to all the slots, then add a slotchange event listener to the 2nd slot in the template — which is the one that keeps having its contents changed in the example.
HTMLTableElement.tBodies - Web APIs
for example: <table> <tr> <td>cell one</td> </tr> </table> the html dom generated from the above html will have a <tbody> element even though the tags are not included in the source html.
... syntax htmlcollectionobject = table.tbodies example this snippet gets the number of bodies in a table.
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 ...
... pddthhmmss pddthhmms.xs pddthhmms.xxs pddthhmms.xxxs pthhmmss pthhmms.xs pthhmms.xxs pthhmms.xxxs ww dd hh mm ss p12dt7h12m13s p12dt7h12m13.3s p12dt7h12m13.45s p12dt7h12m13.455s pt7h12m13s pt7h12m13.2s pt7h12m13.56s pt7h12m13.999s 7d 5h 24m 13s syntax datetimestring = timeelt.datetime; timeelt.datetime = datetimestring example // assumes there is <time id="t"> element in the html var t = document.getelementbyid("t"); t.datetime = "6w 5h 34m 5s"; specifications specification status comment html living standardthe definition of 'htmltimeelement' in that specification.
History.go() - Web APIs
WebAPIHistorygo
so, for example, history.go(2) moves forward two pages and history.go(-2) moves back two pages.
... 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 comment html living standardthe definition of 'history.go()' in that specification.
History.state - Web APIs
WebAPIHistorystate
examples the code below logs the value of history.state before using the pushstate() method to push a value to the history.
... // should be null because we haven't modified the history stack yet console.log(`history.state before pushstate: ${history.state}`); // now push something on the stack history.pushstate({name: 'example'}, "pushstate example", 'page3.html'); // now state has a value.
History - Web APIs
WebAPIHistory
for example, for a page loaded in a new tab this property returns 1.
... go() asynchronously loads a page from the session history, identified by its relative location to the current page, for example -1 for the previous page or 1 for the next page.
History API - Web APIs
examples the following example assigns a listener to the onpopstate property.
... 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", "?page=3") history.back() // alerts "location: http://example.com/example.html?page=1, state: {"page":1}" history.back() // alerts "location: http://example.com/example.html, state: null" history.go(2) // alerts "location: http://example.com/example.html?page=3, state: {"page":3}" specifications specification status comment html living standardthe definition of 'history' in that specification.
IDBCursor.advance() - Web APIs
WebAPIIDBCursoradvance
example in this simple fragment we create a transaction, retrieve an object store, then use a cursor to iterate through the records in the object store.
...for a complete working example, see our idbcursor example (view example live.) function advanceresult() { list.innerhtml = ''; var transaction = db.transaction(['rushalbumlist'], "readonly"); var objectstore = transaction.objectstore('rushalbumlist'); objectstore.opencursor().onsuccess = function(event) { var cursor = event.target.result; if(cursor) { var listitem = document.createelement('li'); l...
IDBCursor.continue() - Web APIs
example 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.
...for a complete working example, see our idbcursor example (view example live.) function displaydata() { var transaction = db.transaction(['rushalbumlist'], "readonly"); var objectstore = transaction.objectstore('rushalbumlist'); objectstore.opencursor().onsuccess = function(event) { var cursor = event.target.result; if(cursor) { var listitem = document.createelement('li'); listitem.innerhtml = cursor.value.albumtitle + ', ' + cursor.value.year; list.appendchild(listitem); cursor.continue(); } else { console.log('entries...
IDBCursor.continuePrimaryKey() - Web APIs
calling this method more than once before new cursor data has been loaded - for example, calling continueprimarykey() twice from the same onsuccess handler - results in an invalidstateerror being thrown on the second call because the cursor’s got value flag has been unset.
... example here’s how you can resume an iteration of all articles tagged with "javascript" since your last visit: let request = articlestore.index("tag").opencursor(); let count = 0; let unreadlist = []; request.onsuccess = (event) => { let cursor = event.target.result; if (!cursor) { return; } let lastprimarykey = getlastiteratedarticleid(); if (lastprimarykey > cursor.primarykey) { ...
IDBCursor.delete() - Web APIs
WebAPIIDBCursordelete
example 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.
...for a complete working example, see our idbcursor example (view example live.) function deleteresult() { list.innerhtml = ''; var transaction = db.transaction(['rushalbumlist'], 'readwrite'); var objectstore = transaction.objectstore('rushalbumlist'); objectstore.opencursor().onsuccess = function(event) { var cursor = event.target.result; if(cursor) { if(cursor.value.albumtitle === 'grace under pressure') { ...
IDBCursor.key - Web APIs
WebAPIIDBCursorkey
example 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.
...for a complete working example, see our idbcursor example (view example live.) function displaydata() { var transaction = db.transaction(['rushalbumlist'], "readonly"); var objectstore = transaction.objectstore('rushalbumlist'); objectstore.opencursor().onsuccess = function(event) { var cursor = event.target.result; if(cursor) { var listitem = document.createelement('li'); listitem.innerhtml = cursor.va...
IDBCursor.primaryKey - Web APIs
example 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.
...for a complete working example, see our idbcursor example (view example live.) function displaydata() { var transaction = db.transaction(['rushalbumlist'], "readonly"); var objectstore = transaction.objectstore('rushalbumlist'); objectstore.opencursor().onsuccess = function(event) { var cursor = event.target.result; if(cursor) { var listitem = document.createelement('li'); listitem.innerhtml = curso...
IDBCursor.request - Web APIs
WebAPIIDBCursorrequest
examples when you open a cursor, the request property is then available on that cursor object, to tell you what request object the cursor originated from.
... for example: function displaydata() { list.innerhtml = ''; var transaction = db.transaction(['rushalbumlist'], 'readonly'); var objectstore = transaction.objectstore('rushalbumlist'); var request = objectstore.opencursor(); request.onsuccess = function(event) { var cursor = event.target.result; if(cursor) { var listitem = document.createelement('li'); listitem.innerhtml = '<strong>' + cursor.value.albumtitle + '</strong>, ' + cursor.value.year; list.appendchild(listitem); console.log(cursor.request); cursor.continue(); } else { console.log('entries all displayed.'); } }; }; specification specification status comment indexed database api draftthe definition of 'request' in that specifica...
IDBCursor.source - Web APIs
WebAPIIDBCursorsource
example 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.
...for a complete working example, see our idbcursor example (view example live.) function displaydata() { var transaction = db.transaction(['rushalbumlist'], "readonly"); var objectstore = transaction.objectstore('rushalbumlist'); objectstore.opencursor().onsuccess = function(event) { var cursor = event.target.result; if(cursor) { var listitem = document.createelement('li'); listitem.innerhtml = curso...
IDBCursor - Web APIs
WebAPIIDBCursor
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.
...for a complete working example, see our idbcursor example (view example live.) function displaydata() { var transaction = db.transaction(['rushalbumlist'], "readonly"); var objectstore = transaction.objectstore('rushalbumlist'); objectstore.opencursor().onsuccess = function(event) { var cursor = event.target.result; if(cursor) { var listitem = document.createelement('li'); listitem.innerhtml = cursor.value.albumtitle + ', ' + cursor.value.year; list.appendchild(listitem); cursor.continue(); } else { console.log('entries...
IDBCursorWithValue.value - Web APIs
example in this example we create a transaction, retrieve an object store, then use a cursor to iterate through all the records in the object store.
...for a complete working example, see our idbcursor example (view example live.) function displaydata() { var transaction = db.transaction(['rushalbumlist'], "readonly"); var objectstore = transaction.objectstore('rushalbumlist'); objectstore.opencursor().onsuccess = function(event) { var cursor = event.target.result; if(cursor) { var listitem = document.createelement('li'); listitem.innerhtml = cursor.value.albumtitle + ', ' + cursor.value.year; list.appendchild(lis...
IDBCursorWithValue - Web APIs
example in this example we create a transaction, retrieve an object store, then use a cursor to iterate through all the records in the object store.
...for a complete working example, see our idbcursor example (view example live.) function displaydata() { var transaction = db.transaction(['rushalbumlist'], "readonly"); var objectstore = transaction.objectstore('rushalbumlist'); objectstore.opencursor().onsuccess = function(event) { var cursor = event.target.result; if(cursor) { var listitem = document.createelement('li'); listitem.innerhtml = cursor.value.albumtitle + ', ' + cursor.value.year; list.appendchild(listitem); cursor.continue(); } else { console.log('entries...
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.
...dex('year', 'year', { unique: false }); }; dbopenrequest.onsuccess = (event) => { const db = dbopenrequest.result; db.addeventlistener('abort', () => { console.log('transaction aborted'); }); // open a read/write db transaction, ready for adding the data const transaction = db.transaction(['todolist'], 'readwrite'); // abort the transaction transaction.abort(); }; the same example, but assigning the event handler to the onabort property: // 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 c...
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 ...
...nst db = dbopenrequest.result; db.addeventlistener('error', () => { console.log(`error adding new item: ${newitem.tasktitle}`); }); // open a read/write db transaction, ready for adding the data const transaction = db.transaction(['todolist'], 'readwrite'); const objectstore = transaction.objectstore('todolist'); const objectstorerequest = objectstore.add(newitem); }; the same example, using the onerror property instead of addeventlistener(): // 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 ...
IDBDatabase.name - Web APIs
WebAPIIDBDatabasename
example this example shows a database connection being opened, the resulting idbdatabase object being stored in a db variable, and the name property then being logged.
... for a full example, see our to-do notifications app (view example live).
IDBDatabase.onclose - Web APIs
this can happen, for example, when the application is shut down or access to the disk the database is stored on is lost while the database is open.
... example db.onclose = function(event) { myappshowalert('the database "' + db.name + '" has unexpectedly closed.'); }; specifications specification status comment indexed database api draftthe definition of 'onclose' in that specification.
IDBDatabase.transaction() - Web APIs
example in this example we open a database connection, then use transaction() to open a transaction on the database.
... for a complete example, see our to-do notifications app (view example live.) var db; // let us open our database var dbopenrequest = window.indexeddb.open("todolist", 4); dbopenrequest.onsuccess = function(event) { note.innerhtml += '<li>database initialised.</li>'; // store the result of opening the database in the db variable.
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.cr...
...tore.createindex('day', 'day', { unique: false }); objectstore.createindex('month', 'month', { unique: false }); objectstore.createindex('year', 'year', { unique: false }); }; dbopenrequest.addeventlistener('success', event => { const db = event.target.result; db.addeventlistener('versionchange', event => { console.log('the version of this database has changed'); }); }); the same example, using the onversionchange event handler property: // 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 ...
IDBDatabase - Web APIs
example in the following code snippet, we open a database asynchronously (idbfactory), handle success and error cases, and create a new object store in the case that an upgrade is needed (idbdatabase).
... for a complete working example, see our to-do notifications app (view example live.) // let us open our database var dbopenrequest = window.indexeddb.open("todolist", 4); // these two event handlers act on the idbdatabase object, // when the database is opened successfully, or not dbopenrequest.onerror = function(event) { note.innerhtml += '<li>error loading database.</li>'; }; dbopenrequest.onsuccess = function(event) { note.innerhtml += '<li>database initialised.</li>'; // store the result of opening the database in the db // variable.
IDBFactory.cmp() - Web APIs
WebAPIIDBFactorycmp
note: do not use this method for comparing arbitrary javascript values, because many javascript values are either not valid indexeddb keys (booleans and objects, for example) or are treated as equivalent indexeddb keys (for example, since indexeddb ignores arrays with non-numeric properties and treats them as empty arrays, so any non-numeric arrays are treated as equivalent).
... example var a = 1; var b = 2; var result = window.indexeddb.cmp(a, b); console.log( "comparison results: " + result ); specifications specification status comment indexed database api 2.0the definition of 'cmp()' in that specification.
IDBFactory.open() - Web APIs
WebAPIIDBFactoryopen
example example of calling open with the current specification's version parameter: var request = window.indexeddb.open("todolist", 4); in the following code snippet, we make a request to open a database, and include handlers for the success and error cases.
... for a full working example, see our to-do notifications app (view example live.) var note = document.queryselector("ul"); // in the following line, you should include the prefixes // of implementations you want to test.
IDBFactory - Web APIs
example in the following code snippet, we make a request to open a database, and include handlers for the success and error cases.
... for a full working example, see our to-do notifications app (view example live.) // in the following line, you should include the prefixes of implementations you want to test.
IDBIndex.count() - Web APIs
WebAPIIDBIndexcount
example in the following example we open a transaction and an object store, then get the index lname from a simple contacts database.
...for a complete working example, see our idbindex-example demo repo (view the example live.) function displaydatabyindex() { tableentry.innerhtml = ''; var transaction = db.transaction(['contactslist'], 'readonly'); var objectstore = transaction.objectstore('contactslist'); var myindex = objectstore.index('lname'); var countrequest = myindex.count(); countrequest.onsuccess = function() { console.log(countreque...
IDBIndex.get() - Web APIs
WebAPIIDBIndexget
example in the following example we open a transaction and an object store, then get the index lname from a simple contacts database.
...for a complete working example, see our idbindex-example demo repo (view the example live.) function displaydatabyindex() { tableentry.innerhtml = ''; var transaction = db.transaction(['contactslist'], 'readonly'); var objectstore = transaction.objectstore('contactslist'); var myindex = objectstore.index('lname'); var getrequest = myindex.get('bungle'); getrequest.onsuccess = function() { console.log(getreque...
IDBIndex.getKey() - Web APIs
WebAPIIDBIndexgetKey
example in the following example we open a transaction and an object store, then get the index lname from a simple contacts database.
...for a complete working example, see our idbindex-example demo repo (view the example live.) function displaydatabyindex() { tableentry.innerhtml = ''; var transaction = db.transaction(['contactslist'], 'readonly'); var objectstore = transaction.objectstore('contactslist'); var myindex = objectstore.index('lname'); var getkeyrequest = myindex.getkey('bungle'); getkeyrequest.onsuccess = function() { console.log...
IDBIndex.keyPath - Web APIs
WebAPIIDBIndexkeyPath
example in the following example we open a transaction and an object store, then get the index lname from a simple contacts database.
...for a complete working example, see our idbindex-example demo repo (view the example live.) function displaydatabyindex() { tableentry.innerhtml = ''; var transaction = db.transaction(['contactslist'], 'readonly'); var objectstore = transaction.objectstore('contactslist'); var myindex = objectstore.index('lname'); console.log(myindex.keypath); myindex.opencursor().onsuccess = function(event) { var cursor = e...
IDBIndex.locale - Web APIs
WebAPIIDBIndexlocale
the locale read-only property of the idbindex interface returns the locale of the index (for example en-us, or pl) if it had a locale value specified upon its creation (see createindex()'s optionalparameters.) note that this property always returns the current locale being used in this index, in other words, it never returns "auto".
... example in the following example we open a transaction and an object store, then get the index lname from a simple contacts database.
IDBIndex.multiEntry - Web APIs
example in the following example we open a transaction and an object store, then get the index lname from a simple contacts database.
...for a complete working example, see our idbindex-example demo repo (view the example live.) function displaydatabyindex() { tableentry.innerhtml = ''; var transaction = db.transaction(['contactslist'], 'readonly'); var objectstore = transaction.objectstore('contactslist'); var myindex = objectstore.index('lname'); console.log(myindex.multientry); myindex.opencursor().onsuccess = function(event) { var cursor ...
IDBIndex.name - Web APIs
WebAPIIDBIndexname
example in the following example we open a transaction and an object store, then get the index lname from a simple contacts database.
...for a complete working example, see our idbindex-example demo repo (view the example live).
IDBIndex.objectStore - Web APIs
example in the following example we open a transaction and an object store, then get the index lname from a simple contacts database.
...for a complete working example, see our idbindex-example demo repo (view the example live.) function displaydatabyindex() { tableentry.innerhtml = ''; var transaction = db.transaction(['contactslist'], 'readonly'); var objectstore = transaction.objectstore('contactslist'); var myindex = objectstore.index('lname'); console.log(myindex.objectstore); myindex.opencursor().onsuccess = function(event) { var cursor...
IDBIndex.openCursor() - Web APIs
example in the following example we open a transaction and an object store, then get the index lname from a simple contacts database.
...for a complete working example, see our idbindex-example demo repo (view the example live.) function displaydatabyindex() { tableentry.innerhtml = ''; var transaction = db.transaction(['contactslist'], 'readonly'); var objectstore = transaction.objectstore('contactslist'); var myindex = objectstore.index('lname'); myindex.opencursor().onsuccess = function(event) { var cursor = event.target.result; if(cursor) { var tablerow = document.createeleme...
IDBIndex.unique - Web APIs
WebAPIIDBIndexunique
example in the following example we open a transaction and an object store, then get the index lname from a simple contacts database.
...for a complete working example, see our idbindex-example demo repo (view the example live.) function displaydatabyindex() { tableentry.innerhtml = ''; var transaction = db.transaction(['contactslist'], 'readonly'); var objectstore = transaction.objectstore('contactslist'); var myindex = objectstore.index('lname'); console.log(myindex.unique); myindex.opencursor().onsuccess = function(event) { var cursor = ev...
IDBKeyRange.bound() - Web APIs
WebAPIIDBKeyRangebound
example the following example illustrates how you'd use a bound key range.
... 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 = functi...
IDBKeyRange.lower - Web APIs
WebAPIIDBKeyRangelower
syntax var lower = mykeyrange.lower value the lower bound of the key range (can be any type.) example the following example illustrates how you'd use a key range.
... note: for a more complete example allowing you to experiment with key range, have a look at our idbkeyrange-example repo (view the example live too.) function displaydata() { var keyrangevalue = idbkeyrange.bound("f", "w", true, true); console.log(keyrangevalue.lower); var transaction = db.transaction(['fthings'], 'readonly'); var objectstore = transaction.objectstore('fthings'); objectstore.opencursor(keyrangevalue...
IDBKeyRange.lowerBound() - Web APIs
example the following example illustrates how you'd use a lower bound key range.
... note: for a more complete example allowing you to experiment with key range, have a look at our idbkeyrange-example repo (view the example live too.) function displaydata() { var keyrangevalue = idbkeyrange.lowerbound("f"); var transaction = db.transaction(['fthings'], 'readonly'); var objectstore = transaction.objectstore('fthings'); objectstore.opencursor(keyrangevalue).onsuccess = function(event) { var cursor =...
IDBKeyRange.lowerOpen - Web APIs
example the following example illustrates how you'd use a key range.
... note: for a more complete example allowing you to experiment with key range, have a look at our idbkeyrange-example repo (view the example live too.) function displaydata() { var keyrangevalue = idbkeyrange.bound("f", "w", true, true); console.log(keyrangevalue.loweropen); var transaction = db.transaction(['fthings'], 'readonly'); var objectstore = transaction.objectstore('fthings'); objectstore.opencursor(keyrangev...
IDBKeyRange.only() - Web APIs
WebAPIIDBKeyRangeonly
example the following example illustrates how you'd use an only key range.
... note: for a more complete example allowing you to experiment with key range, have a look at our idbkeyrange repo (view the example live too.) function displaydata() { var keyrangevalue = idbkeyrange.only("a"); var transaction = db.transaction(['fthings'], 'readonly'); var objectstore = transaction.objectstore('fthings'); objectstore.opencursor(keyrangevalue).onsuccess = function(event) { var cursor = event.target.result; ...
IDBKeyRange.upper - Web APIs
WebAPIIDBKeyRangeupper
syntax var upper = mykeyrange.upper value the upper bound of the key range (can be any type.) example the following example illustrates how you'd use a key range.
... note: for a more complete example allowing you to experiment with key range, have a look at our idbkeyrange-example repo (view the example live too.) function displaydata() { var keyrangevalue = idbkeyrange.bound("f", "w", true, true); console.log(keyrangevalue.upper); var transaction = db.transaction(['fthings'], 'readonly'); var objectstore = transaction.objectstore('fthings'); objectstore.opencursor(keyrangevalue...
IDBKeyRange.upperBound() - Web APIs
example the following example illustrates how you'd use an upper bound key range.
... note: for a more complete example allowing you to experiment with key range, have a look at our idbkeyrange-example repo (view the example live too.) function displaydata() { var keyrangevalue = idbkeyrange.upperbound("f"); var transaction = db.transaction(['fthings'], 'readonly'); var objectstore = transaction.objectstore('fthings'); objectstore.opencursor(keyrangevalue).onsuccess = function(event) { var cursor =...
IDBKeyRange.upperOpen - Web APIs
example the following example illustrates how you'd use a key range.
... note: for a more complete example allowing you to experiment with key range, have a look at our idbkeyrange-example repo (view the example live too.) function displaydata() { var keyrangevalue = idbkeyrange.bound("f", "w", true, true); console.log(keyrangevalue.upperopen); var transaction = db.transaction(['fthings'], 'readonly'); var objectstore = transaction.objectstore('fthings'); objectstore.opencursor(keyrangev...
IDBLocaleAwareKeyRange - Web APIs
with locale-aware indexes, the meaning of < depends on the locale, so for example in lithuanian y is sorted between i and k.
... 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 = document.createelement('tr'); tablerow.innerhtml = '&lt;td&gt;' + cursor.value.id + '&lt;/td&gt;' + '&lt;td&gt;' + cursor.value.lname + '&lt;/td&gt;' ...
IDBObjectStore.add() - Web APIs
example in the following code snippet, we open a read/write transaction on our database and add some data to an object store using add().
...for a full working example, see our to-do notifications app (view example live.) // let us open our database var dbopenrequest = window.indexeddb.open("todolist", 4); dbopenrequest.onsuccess = function(event) { note.innerhtml += '<li>database initialised.</li>'; // store the result of opening the database in the db variable.
IDBObjectStore.autoIncrement - Web APIs
example in the following code snippet, we open a read/write transaction on our database and add some data to an object store using add().
...for a full working example, see our to-do notifications app (view example live.) // let us open our database var dbopenrequest = window.indexeddb.open("todolist", 4); dbopenrequest.onsuccess = function(event) { note.innerhtml += '<li>database initialised.</li>'; // store the result of opening the database in the db variable.
IDBObjectStore.clear() - Web APIs
example in the following code snippet, we open a read/write transaction on our database and clear all the current data out of the object store using clear().
... for a full working example, see our to-do notifications app (view example live.) // let us open our database var dbopenrequest = window.indexeddb.open("todolist", 4); dbopenrequest.onsuccess = function(event) { note.innerhtml += '<li>database initialised.</li>'; // store the result of opening the database in the db variable.
IDBObjectStore.createIndex() - Web APIs
has been deleted or removed.) in firefox previous to version 41, an invalidstateerror was raised in this case as well, which was misleading; this has now been fixed (see bug 1176165.) example in the following example you can see the idbopendbrequest.onupgradeneeded handler being used to update the database structure if a database with a higher version number is loaded.
... for a full working example, see our to-do notifications app (view example live.) var db; // let us open our database var dbopenrequest = window.indexeddb.open("todolist", 4); // two event handlers for opening the database.
IDBObjectStore.delete() - Web APIs
example in the following code snippet, we open a read/write transaction on our database and delete one specific record out of our object store using delete() — a sample record with the key "walk dog".
... for a full working example, see our to-do notifications app (view example live.) // let us open our database var dbopenrequest = window.indexeddb.open("todolist", 4); dbopenrequest.onsuccess = function(event) { note.innerhtml += '<li>database initialised.</li>'; // store the result of opening the database in the db variable.
IDBObjectStore.deleteIndex() - Web APIs
example in the following example you can see the idbopendbrequest.onupgradeneeded handler being used to update the database structure if a database with a higher version number is loaded.
... for a full working example, see our to-do notifications app (view example live.) var db; // let us open our database var dbopenrequest = window.indexeddb.open("todolist", 4); // these two event handlers act on the database being opened successfully, or not dbopenrequest.onerror = function(event) { note.innerhtml += '<li>error loading database.</li>'; }; dbopenrequest.onsuccess = function(event) { note.innerhtml += '<li>database initialised.</li>'; // store the result of opening the database in the db variable.
IDBObjectStore.get() - Web APIs
example in the following code snippet, we open a read/write transaction on our database and get one specific record from object store using get() — a sample record with the key "walk dog".
...for a full working example, see our to-do notifications app (view example live.) // let us open our database var dbopenrequest = window.indexeddb.open("todolist", 4); dbopenrequest.onsuccess = function(event) { note.innerhtml += '<li>database initialised.</li>'; // store the result of opening the database in the db variable.
IDBObjectStore.indexNames - Web APIs
example in the following code snippet, we open a read/write transaction on our database and add some data to an object store using add().
...for a full working example, see our to-do notifications app (view example live.) // let us open our database var dbopenrequest = window.indexeddb.open("todolist", 4); dbopenrequest.onsuccess = function(event) { note.innerhtml += '<li>database initialised.</li>'; // store the result of opening the database in the db variable.
IDBObjectStore.keyPath - Web APIs
example in the following code snippet, we open a read/write transaction on our database and add some data to an object store using add().
...for a full working example, see our to-do notifications app (view example live.) // let us open our database var dbopenrequest = window.indexeddb.open("todolist", 4); dbopenrequest.onsuccess = function(event) { note.innerhtml += '<li>database initialised.</li>'; // store the result of opening the database in the db variable.
IDBObjectStore.name - Web APIs
example in the following code snippet, we open a read/write transaction on our database and add some data to an object store using add().
...for a full working example, see our to-do notifications app (view example live.) // let us open our database var dbopenrequest = window.indexeddb.open("todolist", 4); dbopenrequest.onsuccess = function(event) { note.innerhtml += '<li>database initialised.</li>'; // store the result of opening the database in the db variable.
IDBObjectStore.put() - Web APIs
example the following example requests a given record title; when that request is successful the onsuccess function gets the associated record from the idbobjectstore (made available as objectstoretitlerequest.result), updates one property of the record, and then puts the updated record back into the object store in another request with put().
... for a full working example, see our to-do notifications app (view example live.) const title = "walk dog"; // open up a transaction as usual const objectstore = db.transaction(['todolist'], "readwrite").objectstore('todolist'); // get the to-do list object that has this title as it's title const objectstoretitlerequest = objectstore.get(title); objectstoretitlerequest.onsuccess = () => { // grab the data object returned as the result const data = objectstoretitlerequest.result; // update the notified value in the object to "yes" data.notified = "yes"; // create another request that inserts the item back into the database const updatetitlerequest = objectstore.put(data); // log the transaction that originated this request console.log("the transaction that originated this re...
IDBObjectStore.transaction - Web APIs
example in the following code snippet, we open a read/write transaction on our database and add some data to an object store using add().
...for a full working example, see our to-do notifications app (view example live.) // let us open our database var dbopenrequest = window.indexeddb.open("todolist", 4); dbopenrequest.onsuccess = function(event) { note.innerhtml += '<li>database initialised.</li>'; // store the result of opening the database in the db variable.
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.
...; // define what data items the objectstore will contain objectstore.createindex('hours', 'hours', { unique: false }); objectstore.createindex('minutes', 'minutes', { unique: false }); objectstore.createindex('day', 'day', { unique: false }); objectstore.createindex('month', 'month', { unique: false }); objectstore.createindex('year', 'year', { unique: false }); }); this is the same example, but uses the onupgradeneeded event handler property.
IDBOpenDBRequest - Web APIs
example in the following example you can see the onupgradeneeded handler being used to update the database structure if a database with a higher version number is loaded.
... for a full working example, see our to-do notifications app (view example live.) var db; // let us open our database var dbopenrequest = window.indexeddb.open("todolist", 4); // these event handlers act on the database being opened.
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 ite...
...ansaction(['todolist'], 'readwrite'); const objectstore = transaction.objectstore('todolist'); const newitem = { tasktitle: 'my task', hours: 10, minutes: 10, day: 10, month: 'january', year: 2020 }; const objectstorerequest = objectstore.add(newitem); objectstorerequest.addeventlistener('error', () => { console.log(`error adding new item: ${newitem.tasktitle}`); }); }); the same example, using the onerror property instead of 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', { keypat...
IDBRequest.onerror - Web APIs
}; example the following example requests a given record title, onsuccess gets the associated record from the idbobjectstore (made available as objectstoretitlerequest.result), updates one property of the record, and then puts the updated record back into the object store.
...for a full working example, see our to-do notifications app (view example live.) var title = "walk dog"; // open up a transaction as usual var objectstore = db.transaction(['todolist'], "readwrite").objectstore('todolist'); // get the to-do list object that has this title as it's title var objectstoretitlerequest = objectstore.get(title); objectstoretitlerequest.onsuccess = function() { // grab the data object returned as the result var data = objectstoretitlerequest.result; // update the notified value in the object to "yes" data.notified = "yes"; // create another request that inserts the item back // into the database var updatetitlerequest = objectstore.put(data); /...
IDBRequest.onsuccess - Web APIs
}; example the following example requests a given record title, onsuccess gets the associated record from the idbobjectstore (made available as objectstoretitlerequest.result), updates one property of the record, and then puts the updated record back into the object store.
... for a full working example, see our to-do notifications app (view example live.) var title = "walk dog"; // open up a transaction as usual var objectstore = db.transaction(['todolist'], "readwrite").objectstore('todolist'); // get the to-do list object that has this title as it's title var objectstoretitlerequest = objectstore.get(title); objectstoretitlerequest.onsuccess = function() { // grab the data object returned as the result var data = objectstoretitlerequest.result; // update the notified value in the object to "yes" data.notified = "yes"; // create another request that inserts the item back // into the database var updatetitlerequest = objectstore.put(data); // when this new request succeeds, run the displaydata() // function again to update the display updat...
IDBRequest.readyState - Web APIs
example the following example requests a given record title, onsuccess gets the associated record from the idbobjectstore (made available as objectstoretitlerequest.result), updates one property of the record, and then puts the updated record back into the object store in another request.
...for a full working example, see our to-do notifications app (view example live.) var title = "walk dog"; // open up a transaction as usual var objectstore = db.transaction(['todolist'], "readwrite").objectstore('todolist'); // get the to-do list object that has this title as it's title var objectstoretitlerequest = objectstore.get(title); objectstoretitlerequest.onsuccess = function() { // grab the data object returned as the result var data = objectstoretitlerequest.result; // update the notified value in the object to "yes" data.notified = "yes"; // create another request that inserts the item // back into the database var updatetitlerequest = objectstore.put(data); // log the source of this request ...
IDBRequest.result - Web APIs
WebAPIIDBRequestresult
syntax var myresult = request.result; value any example the following example requests a given record title, onsuccess gets the associated record from the idbobjectstore (made available as objectstoretitlerequest.result), updates one property of the record, and then puts the updated record back into the object store.
... for a full working example, see our to-do notifications app (view example live.) var title = "walk dog"; // open up a transaction as usual var objectstore = db.transaction(['todolist'], "readwrite").objectstore('todolist'); // get the to-do list object that has this title as it's title var objectstoretitlerequest = objectstore.get(title); objectstoretitlerequest.onsuccess = function() { // grab the data object returned as the result var data = objectstoretitlerequest.result; // update the notified value in the object to "yes" data.notified = "yes"; // create another request that inserts the item // back into the database var updatetitlerequest = objectstore.put(data); // when this new request succeeds, run the displaydata() // function again to update the display updat...
IDBRequest.source - Web APIs
WebAPIIDBRequestsource
example the following example requests a given record title, onsuccess gets the associated record from the idbobjectstore (made available as objectstoretitlerequest.result), updates one property of the record, and then puts the updated record back into the object store in another request.
...for a full working example, see our to-do notifications app (view example live.) var title = "walk dog"; // open up a transaction as usual var objectstore = db.transaction(['todolist'], "readwrite").objectstore('todolist'); // get the to-do list object that has this title as its title var objectstoretitlerequest = objectstore.get(title); objectstoretitlerequest.onsuccess = function() { // grab the data object returned as the result var data = objectstoretitlerequest.result; // update the notified value in the object to "yes" data.notified = "yes"; // create another request that inserts the item // back into the database var updatetitlerequest = objectstore.put(data); // log the source of this request conso...
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('minute...
...s', 'minutes', { unique: false }); objectstore.createindex('day', 'day', { unique: false }); objectstore.createindex('month', 'month', { unique: false }); objectstore.createindex('year', 'year', { unique: false }); }; openrequest.addeventlistener('success', (event) => { console.log('database opened successfully!'); }); the same example, but using the onsuccess event handler property: // 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 c...
IDBTransaction.abort() - Web APIs
example in the following code snippet, we open a read/write transaction on our database and add some data to an object store.
...for a full working example, see our to-do notifications app (view example live.) // let us open our database var dbopenrequest = window.indexeddb.open("todolist", 4); dbopenrequest.onsuccess = function(event) { note.innerhtml += '<li>database initialised.</li>'; // store the result of opening the database in the db variable.
IDBTransaction.db - Web APIs
WebAPIIDBTransactiondb
example in the following code snippet, we open a read/write transaction on our database and add some data to an object store.
...for a full working example, see our to-do notifications app (view example live.) // let us open our database var dbopenrequest = window.indexeddb.open("todolist", 4); dbopenrequest.onsuccess = function(event) { note.innerhtml += '<li>database initialised.</li>'; // store the result of opening the database in the db variable.
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 cont...
... db.transaction(['todolist'], 'readwrite'); transaction.addeventlistener('error', () => { console.log(`error adding new item: ${newitem.tasktitle}`); }); const objectstore = transaction.objectstore('todolist'); const newitem = { tasktitle: 'my task', hours: 10, minutes: 10, day: 10, month: 'january', year: 2020 }; const objectstorerequest = objectstore.add(newitem); }; the same example, using the onerror property instead of addeventlistener(): // 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 ...
IDBTransaction.mode - Web APIs
transactions in this mode are known as "upgrade transactions." example in the following code snippet, we open a read/write transaction on our database and add some data to an object store.
...for a full working example, see our to-do notifications app (view example live.) // let us open our database var dbopenrequest = window.indexeddb.open("todolist", 4); dbopenrequest.onsuccess = function(event) { note.innerhtml += '<li>database initialised.</li>'; // store the result of opening the database in the db variable.
IDBTransaction.objectStore() - Web APIs
example in the following code snippet, we open a read/write transaction on our database and add some data to an object store.
...for a full working example, see our to-do notifications app (view example live.) // let us open our database var dbopenrequest = window.indexeddb.open("todolist", 4); dbopenrequest.onsuccess = function(event) { note.innerhtml += '<li>database initialised.</li>'; // store the result of opening the database in the db variable.
IDBTransaction.onabort - Web APIs
}; example in the following code snippet, we open a read/write transaction on our database and add some data to an object store.
...for a full working example, see our to-do notifications app (view example live.) // let us open our database var dbopenrequest = window.indexeddb.open("todolist", 4); dbopenrequest.onsuccess = function(event) { note.innerhtml += '<li>database initialised.</li>'; // store the result of opening the database in the db variable.
IDBTransaction.oncomplete - Web APIs
}; example in the following code snippet, we open a read/write transaction on our database and add some data to an object store.
...for a full working example, see our to-do notifications app (view example live.) // let us open our database var dbopenrequest = window.indexeddb.open("todolist", 4); dbopenrequest.onsuccess = function(event) { note.innerhtml += '<li>database initialised.</li>'; // store the result of opening the database in the db variable.
IDBTransaction.onerror - Web APIs
}; example in the following code snippet, we open a read/write transaction on our database and add some data to an object store.
...for a full working example, see our to-do notifications app (view example live.) // let us open our database var dbopenrequest = window.indexeddb.open("todolist", 4); dbopenrequest.onsuccess = function(event) { note.innerhtml += '<li>database initialised.</li>'; // store the result of opening the database in the db variable.
IDBVersionChangeEvent.newVersion - Web APIs
example in the following code snippet, we make a request to open a database, and include handlers for the success and error cases.
...for a full working example, see our to-do notifications app (view example live.) var note = document.queryselector("ul"); // in the following line, you should include the prefixes of // implementations you want to test.
IDBVersionChangeEvent - Web APIs
example in the following code snippet, we make a request to open a database, and include handlers for the success and error cases.
...for a full working example, see our to-do notifications app (view example live.) var note = document.queryselector("ul"); // in the following line, you should include the prefixes of implementations you want to test.
IdleDeadline.timeRemaining() - Web APIs
for example, if the callback finishes a task and has another one to begin, it can call timeremaining() to see if there's enough time to complete the next task.
... example see our complete example in the article cooperative scheduling of background tasks api.
ImageCapture.getPhotoCapabilities() - Web APIs
example the following example, extracted from chrome's image capture / photo resolution sample, uses the results from getphotocapabilities() to modify the size of an input range.
... this example also shows how the imagecapture object is created using a mediastreamtrack retrieved from a device's mediastream.
ImageCapture.getPhotoSettings() - Web APIs
example the following example, extracted from chrome's image capture / photo resolution sample, uses the results from getphotosettings() to modify the size of an input range.
... this example also shows how the imagecapture object is created using a mediastreamtrack retrieved from a device's mediastream.
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.
... let imagedata = new imagedata(200, 100); // imagedata { width: 200, height: 100, data: uint8clampedarray[80000] } initializing imagedata with an array this example instantiates an imagedata object with pixel colors defined by an array.
Checking when a deadline is due - Web APIs
in this article we look at a complex example involving checking the current time and date against a deadline stored via indexeddb.
... the main example application we will be referring to in this article is to-do list notifications, a simple to-do list application that stores task titles and deadline times and dates via indexeddb, and then provides users with notifications when deadline dates are reached, via the notification, and vibration apis.
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.
firesTouchEvents - Web APIs
for example, stylus and mouse devices typically generate touch events on mobile browsers.
... syntax var boolean = inputdevicecapabilities.firestouchevents returns a boolean example mybutton.addeventlistener('mousedown', function(e) { if (!e.sourcecapabilities.firestouchevents) mybutton.classlist.add("pressed"); }); specifications specification status comment inputdevicecapabilitiesthe definition of 'firetouchevents' in that specification.
InputDeviceCapabilities - Web APIs
for example, two mice with the same capabilities in a system may appear as a single inputdevicecapabilities instance.
...this allows, for example, touchscreen keyboards and physical keyboards to be represented the same way when they produce the same input.
InputDeviceCapabilities API - Web APIs
for example, the first version of the api indicates whether a device fires touch events rather than whether it is a touch screen.
...for example, let's say we have a web page that implements both a touchstart and a mousedown event.
InputEvent() - Web APIs
inputeventinitoptional is a inputeventinit dictionary, having the following fields: inputtype: (optional) a string specifying the type of change for editible content such as, for example, inserting, deleting, or formatting text.
...this may be an empty string if the change doesn't insert text (such as when deleting characters, for example).
InputEvent.data - Web APIs
WebAPIInputEventdata
this may be an empty string if the change doesn't insert text (such as when deleting characters, for example).
... 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 - Web APIs
this may be an empty string if the change doesn't insert text (such as when deleting characters, for example).
... inputevent.inputtyperead only returns the type of change for editable content such as, for example, inserting, deleting, or formatting text.
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.
...although this example has only one cache, you can use this approach for multiple caches.
IntersectionObserverEntry.intersectionRatio - Web APIs
example in this simple example, an intersection callback sets each target element's opacity to the intersection ratio of that element with the root.
... function intersectioncallback(entries) { entries.foreach(function(entry) { entry.target.style.opacity = entry.intersectionratio; }); } to see a more concrete example, take a look at handling intersection changes in timing element visibility with the intersection observer api.
IntersectionObserverEntry.isIntersecting - Web APIs
example in this simple example, an intersection callback is used to update a counter of how many targeted elements are currently intersecting with the intersection root.
... function intersectioncallback(entries) { entries.foreach(function(entry) { if (entry.isintersecting) { intersectingcount += 1; } else { intersectingcount -= 1; } }); } to see a more concrete example, take a look at handling intersection changes in timing element visibility with the intersection observer api.
IntersectionObserverEntry.target - Web APIs
example in this simple example, each targeted element's opacity is set to its intersectionratio.
... function intersectioncallback(entries) { entries.foreach(function(entry) { entry.target.opacity = entry.intersectionratio; }); } to see a more concrete example, take a look at handling intersection changes in timing element visibility with the intersection observer api.
InterventionReportBody - Web APIs
so for example, a script was been stopped because it was significantly slowing down the browser, or the browser's autoplay policy blocked audio from playing without a user gesture to trigger it.
... 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(firstre...
Keyboard.lock() - Web APIs
WebAPIKeyboardlock
examples capturing all keys the following example captures all keypresses.
... navigator.keyboard.lock(); capturing specific keys the following example captures the "w", "a", "s", and "d" keys.
KeyboardEvent.charCode - Web APIs
example html <p>type anything into the input box below to log a <code>charcode</code>.</p> <input type="text" /> <p id="log"></p> javascript let input = document.queryselector('input'); let log = document.queryselector('#log'); input.addeventlistener('keypress', function(e) { log.innertext = `key pressed: ${string.fromcharcode(e.charcode)}\ncharcode: ${e.charcode}`; }); result notes in a keypress event, the unicode value ...
... for a list of the charcode values associated with particular keys, run example 7: displaying event object properties and view the resulting html table.
KeyboardEvent.key - Web APIs
WebAPIKeyboardEventkey
keyboardevent sequence example consider the event sequence generated when we interact with the shift and the 2 key using a u.s keyboard layout as compared to when we do so using a uk keyboard layout.
... example this example uses eventtarget.addeventlistener() to listen for keydown events.
KeyframeEffect.KeyframeEffect() - Web APIs
0.5 would indicate starting halfway through the first iteration for example, and with this value set, an animation with 2 iterations would end halfway through a third iteration.
... 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...
LayoutShift - Web APIs
examples the following example shows how to capture layout shifts and log them to the console.
... note that in this example data is only sent to the server when the user leaves the tab.
LinearAccelerationSensor.x - Web APIs
example linear acceleration is typically read in the sensor.onreading event callback.
... in the example below this occurs sixty times a second.
LinearAccelerationSensor.y - Web APIs
example linear acceleration is typically read in the sensor.onreading event callback.
... in the example below this occurs sixty times a second.
LinearAccelerationSensor.z - Web APIs
example linear acceleration is typically read in the sensor.onreading event callback.
... in the example below this occurs sixty times a second.
LinearAccelerationSensor - Web APIs
example linear acceleration is typically read in the sensor.onreading event callback.
... in the example below this occurs sixty times a second.
LocalFileSystemSync - Web APIs
example //taking care of the browser-specific prefix window.requestfilesystemsync = window.requestfilesystemsync || window.webkitrequestfilesystemsync; // the first parameter defines the type of storage: persistent or temporary // next, set the size of space needed (in bytes) // initfs is the success callback // and the last one is the error callback // for denial of access and other errors.
...for example, you cannot run from file://.
Location - Web APIs
WebAPILocation
anatomy of location html <span id="href" title="href"><span id="protocol" title="protocol">http:</span>//<span id="host" title="host"><span id="hostname" title="hostname">example.org</span>:<span id="port" title="port">8888</span></span><span id="pathname" title="pathname">/foo/bar</span><span id="search" title="search">?q=baz</span><span id="hash" title="hash">#bang</span></span> css html, body {height:100%;} html {display:table; width:100%;} body {display:table-cell; text-align:center; vertical-align:middle; font-family:georgia; font-size:230%; line-height:1em; white-...
... 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-r...
Locks.name - Web APIs
WebAPILockname
for example, if only one tab of a web application should be synchronizing network resources with an offline database, it could use a lock name such as "net_db_sync".
... example the following examples show how the name property passed in the call to lockmanager.request().
MIDIConnectionEvent - Web APIs
for example, this event is fired whenever a midi device is either plugged in to or unplugged from a computer.
... 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
a midimessage event is fired every time a midi message is sent from a device represented by a midiinput, for example when a midi keyboard key is pressed, a knob is tweaked, or a slider is moved.
... 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.
Magnetometer.x - Web APIs
WebAPIMagnetometerx
example the magnetometer is typically read in the sensor.onreading event callback.
... in the example below this occurs sixty times a second.
Magnetometer.y - Web APIs
WebAPIMagnetometery
example the magnetometer is typically read in the sensor.onreading event callback.
... in the example below this occurs sixty times a second.
Magnetometer.z - Web APIs
WebAPIMagnetometerz
example the magnetometer is typically read in the sensor.onreading event callback.
... in the example below this occurs sixty times a second.
Magnetometer - Web APIs
example the magnetometer is typically read in the sensor.onreading event callback.
... in the example below this occurs sixty times a second.
MediaConfiguration - Web APIs
all of these must be present, as in the examples below, or a typeerror will occur.
... example //create a video configuration to be tested const videodecoderconfig = { type : 'file', // 'record', 'transmission', 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 ...
MediaElementAudioSourceNode - Web APIs
example this simple example creates a source from an <audio> element using createmediaelementsource(), then passes the audio through a gainnode before feeding it into the audiodestinationnode for playback.
... note: you can also view this example running live, or view the source.
MediaError.code - Web APIs
WebAPIMediaErrorcode
example this example creates a <video> element, establishes an error handler for it, and then sets the element's src attribute to the video resource to present in the element.
... the error handler simply outputs a message var obj = document.createelement('video'); obj.onerror = function() {console.log("error with media: " + obj.error.code);} obj.src="https://example.com/blahblah.mp4"; specifications specification status comment html living standardthe definition of 'mediaerror.code' in that specification.
MediaList.mediaText - Web APIs
each one is separated by a comma, for example screen and (min-width: 480px), print.
... examples the following would log to the console a textual representation of the medialist of the first stylesheet applied to the current document.
MediaPositionState.duration - Web APIs
for example, a browser might use this information along with the position property and the navigator.mediasession.playbackstate, as well as the session's metadata to provide an integrated common user interface showing the currently playing media as well as standard pause, play, forward, reverse, and other controls.
... example in this example, an app performing a live stream provides information to the browser by preparing a mediapositionstate object and submitting it by calling navigator.mediasession.setpositionstate().
MediaPositionState.playbackRate - Web APIs
for example, a browser might use this information along with the position property and the navigator.mediasession.playbackstate, as well as the session's metadata to provide an integrated common user interface showing the currently playing media as well as standard pause, play, forward, reverse, and other controls.
... example in this example, an app is updating the browser to let it know that the user has clicked a button causing the playback to shift to a double-speed mode.
MediaPositionState.position - Web APIs
for example, a browser might use this information along with the position property and the navigator.mediasession.playbackstate, as well as the session's metadata to provide an integrated common user interface showing the currently playing media as well as standard pause, play, forward, reverse, and other controls.
... example in this example, a player for a non-standard media file format, written in javascript, uses setinterval() to establish a callback which fires once per second to refresh the position information by calling setpositionstate().
MediaRecorder: error event - Web APIs
the mediarecorder interface's error event is fired when an error occurs: for example because recording wasn't allowed or was attempted using an unsupported codec.
... 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 onerror event handler property: async function record() { const stream = await navigator.mediadevices.getusermedia({audio: true}); const recor...
MediaRecorder.onerror - Web APIs
this may be the case, for example, with sources obtained using getusermedia() when the user denies permission to use an input device.
... example this example creates a new mediarecorder instance and starts recording using the user agent's default media format.
MediaRecorder.start() - Web APIs
this may be the case, for example, with sources obtained using getusermedia() when the user denies permission to use an input device.
... example ...
MediaRecorder - Web APIs
error fired when an error occurs: for example because recording wasn't allowed or was attempted using an unsupported codec.
... example if (navigator.mediadevices) { console.log('getusermedia supported.'); var constraints = { audio: true }; var chunks = []; navigator.mediadevices.getusermedia(constraints) .then(function(stream) { var mediarecorder = new mediarecorder(stream); visualize(stream); record.onclick = function() { mediarecorder.start(); console.log(mediarecorder.state); console.log("recorder started"); record.style.background = "red"; record.style.color = "black"; } stop.onclick = function() { mediarecorder.stop(); console.log(mediarecorder.state); console.log("recorder stopped"); record.style.background = ""; record.style.color = ""; } mediarecorder.onstop = func...
MediaRecorderErrorEvent.error - Web APIs
this may be the case, for example, with sources obtained using getusermedia() when the user denies permission to use an input device.
... example this function creates and returns a mediarecorder for a given mediastream, configured to buffer data into an array and to watch for errors.
MediaSource.endOfStream() - Web APIs
for example, you might have a function that handles media chunk requests, separate from other network requests.
...their sourcebuffer.updating property is true.) example the following snippet is from a simple example written by nick desaulniers (view the full demo live, or download the source for further investigation.) var asseturl = 'frag_bunny.mp4'; // need to be specific for blink regarding codecs // ./mp4info frag_bunny.mp4 | grep codec var mimecodec = 'video/mp4; codecs="avc1.42e01e, mp4a.40.2"'; if ('mediasource' in window && mediasource.istypesupported...
MediaSource - Web APIs
examples the following simple example loads a video with xmlhttprequest, playing it as soon as it can.
... this example was written by nick desaulniers and can be viewed live here (you can also download the source for further investigation.) var video = document.queryselector('video'); var asseturl = 'frag_bunny.mp4'; // need to be specific for blink regarding codecs // ./mp4info frag_bunny.mp4 | grep codec var mimecodec = 'video/mp4; codecs="avc1.42e01e, mp4a.40.2"'; if ('mediasource' in window && mediasource.istypesupported(mimecodec)) { var mediasource = new mediasource(); //console.log(mediasource.readystate); // closed video.src = url.createobjecturl(mediasource); mediasource.addeventlistener('sourceopen', sourceopen); } else { console.error('unsupported mime type or codec: ', mimecodec); } function sourceopen (_) { //console.log(this.readystate); // open var mediasource = this...
MediaStreamAudioSourceNode - Web APIs
example in this example, we grab a media (audio + video) stream from navigator.getusermedia, feed the media into a <video> element to play then mute the audio, but then also feed the audio into a mediastreamaudiosourcenode.
... note: you can see this example running live, or view the source.
MediaStreamConstraints.video - Web APIs
examples using a boolean value in this example, we provide a simple value of true for the video property.
... result using a mediatrackconstraints object now let's look at a similar example that uses a set of constraints based on the mediatrackconstraints dictionary: html content <p>click the start button below to begin the demonstration.</p> <div id="startbutton" class="button"> start </div> <video id="video" width="160" height="120" autoplay></video><br> <div id="log"></div> css content body { font: 14px "open sans", "arial", sans-serif; } video { margin-top: 20px; b...
MediaStreamTrack.applyConstraints() - Web APIs
for example, you may prefer high-density video but require that the frame rate be a little low to help keep the data rate low enough not overtax the network.
... examples the following shows how to specify a basic and advanced set of constraints.
MediaStreamTrack.enabled - Web APIs
for example, the green "in use" light next to the camera in imac and macbook computers turns off while the track is muted in this way.
... example this example demonstrates a click event handler for a pause button.
MediaStreamTrack.getConstraints() - Web APIs
for example, you may prefer high definition video but require that the frame rate be a little low to help keep the data rate low enough not overtax the network.
... example this example obtains the current constraints for a track, sets the facingmode, and applies the updated constraints.
MediaStreamTrack: mute event - Web APIs
bubbles no cancelable no interface event event handler property onmute examples in this example, event handlers are established for the mute and unmute events in order to detect when the media is not flowing from the source for the mediastreamtrack referenced by musictrack.
...the following example shows this: musictrack.onmute = event => { document.getelementbyid("timeline-widget").style.backgroundcolor = "#aaa"; } musictrack.mute = event = > { document.getelementbyid("timeline-widget").style.backgroundcolor = "#fff"; } specifications specification status comment media capture and streamsthe definition of 'mute' in that specification.
MediaStreamTrack.stop() - Web APIs
since multiple tracks may use the same source (for example, if two tabs are using the device's microphone), the source itself isn't necessarily immediately stopped.
... examples stopping a video stream in this example, we see a function which stops a streamed video by calling stop() on every track on a given <video>.
MediaStreamTrack: unmute event - Web APIs
examples in this example, event handlers are established for the mute and unmute events in order to detect when the media is not flowing from the source for the mediastreamtrack stored in the variable musictrack.
...the following example shows this: musictrack.onmute = event => { document.getelementbyid("timeline-widget").style.backgroundcolor = "#aaa"; } musictrack.mute = event = > { document.getelementbyid("timeline-widget").style.backgroundcolor = "#fff"; } specifications specification status comment media capture and streamsthe definition of 'unmute' in that specification.
MediaStreamTrackAudioSourceNode - Web APIs
example in this example, we grab a media (audio + video) stream from navigator.getusermedia, feed the media into a <video> element to play then mute the audio, but then also feed the audio into a mediastreamaudiosourcenode.
... note: you can see this example running live, or view the source.
MediaStream Image Capture API - Web APIs
the example code is adapted from chrome's image capture examples.
...the example below simply says give me whatever video device is available, though the getusermedia() method allows more specific capabilities to be requested.
Recording a media element - Web APIs
in this article, we'll look at an example that does just that.
... getting an input stream and setting up the recorder now let's look at the most intricate piece of code in this example: our event handler for clicks on the start button: startbutton.addeventlistener("click", function() { navigator.mediadevices.getusermedia({ video: true, audio: true }).then(stream => { preview.srcobject = stream; downloadbutton.href = stream; preview.capturestream = preview.capturestream || preview.mozcapturestream; return new promise(resolve => preview.onplaying = re...
Using the MediaStream Recording API - Web APIs
for example, in web dictaphone we have three main ui areas, stacked vertically.
...we register an event handler to do this using mediarecorder.ondataavailable: let chunks = []; mediarecorder.ondataavailable = function(e) { chunks.push(e.data); } note: the browser will fire dataavailable events as needed, but if you want to intervene you can also include a timeslice when invoking the start() method — for example start(10000) — to control this interval, or call mediarecorder.requestdata() to trigger an event when you need it.
MediaTrackConstraints.aspectRatio - Web APIs
for example, the standard high-definition video aspect ratio of 16:9 can be computed as 1920/1080, or 1.7777777778.
... example see example: constraint exerciser in capabilities, constraints, and settings for an example.
MediaTrackConstraints.groupId - Web APIs
for example, the microphone and speaker on the same headset would share a group id.
... example see example: constraint exerciser in capabilities, constraints, and settings for an example.
MediaTrackSettings.aspectRatio - Web APIs
for example, the standard 16:9 high-definition aspect ratio can be computed as 1920/1080, or 1.7777777778.
... example see example: constraint exerciser in capabilities, constraints, and settings for an example.
MediaTrackSettings.deviceId - Web APIs
this id is valid across multiple browsing sessions for the same origin and is guaranteed to be different for all other origins, so you can safely use it to request the same source be used for multiple sessions, for example.
... example see example: constraint exerciser in capabilities, constraints, and settings for an example.
MediaTrackSettings.echoCancellation - Web APIs
for example, it might apply a filter that negates the sound being produced on the speakers from being included in the input track generated from the microphone.
... example see example: constraint exerciser in capabilities, constraints, and settings for an example.
MediaTrackSettings.facingMode - Web APIs
"user" the video source is facing toward the user; this includes, for example, the front-facing camera on a smartphone.
... example see example: constraint exerciser in capabilities, constraints, and settings for an example.
MediaTrackSettings.sampleSize - Web APIs
for example, 16-bit stereo audio requires (16/8)*2 or 4 bytes per sample.
... example see example: constraint exerciser in capabilities, constraints, and settings for an example.
Media Capture and Streams API (Media Stream) - Web APIs
see an example in get the video.
...this article discusses capabilities and constraints, as well as media settings, and includes an example we call the constraint exerciser.
MessageChannel() - Web APIs
example in the following code block, you can see a new channel being created using the messagechannel.messagechannel constructor.
... para = document.queryselector('p'); var ifr = document.queryselector('iframe'); var otherwindow = ifr.contentwindow; ifr.addeventlistener("load", iframeloaded, false); function iframeloaded() { otherwindow.postmessage('hello from the main page!', '*', [channel.port2]); } channel.port1.onmessage = handlemessage; function handlemessage(e) { para.innerhtml = e.data; } for a full working example, see our channel messaging basic demo on github (run it live too).
MessageChannel.port2 - Web APIs
example in the following code block, you can see a new channel being created using the messagechannel.messagechannel constructor.
... para = document.queryselector('p'); var ifr = document.queryselector('iframe'); var otherwindow = ifr.contentwindow; ifr.addeventlistener("load", iframeloaded, false); function iframeloaded() { otherwindow.postmessage('hello from the main page!', '*', [channel.port2]); } channel.port1.onmessage = handlemessage; function handlemessage(e) { para.innerhtml = e.data; } for a full working example, see our channel messaging basic demo on github (run it live too).
MessageChannel - Web APIs
example in the following example, you can see a new channel being created using the messagechannel.messagechannel constructor.
...it for the iframe to load iframe.addeventlistener("load", onload); function onload() { // listen for messages on port1 channel.port1.onmessage = onmessage; // transfer port2 to the iframe iframe.contentwindow.postmessage('hello from the main page!', '*', [channel.port2]); } // handle messages received on port1 function onmessage(e) { output.innerhtml = e.data; } for a full working example, see our channel messaging basic demo on github (run it live too).
MessagePort.onmessage - Web APIs
}; example in the following code block, you can see a new channel being created using the messagechannel.messagechannel constructor.
... para = document.queryselector('p'); var ifr = document.queryselector('iframe'); var otherwindow = ifr.contentwindow; ifr.addeventlistener("load", iframeloaded, false); function iframeloaded() { otherwindow.postmessage('hello from the main page!', '*', [channel.port2]); } channel.port1.onmessage = handlemessage; function handlemessage(e) { para.innerhtml = e.data; } for a full working example, see our channel messaging basic demo on github (run it live too).
MessagePort.postMessage() - Web APIs
example in the following code block, you can see a new channel being created using the messagechannel.messagechannel constructor.
... para = document.queryselector('p'); var ifr = document.queryselector('iframe'); var otherwindow = ifr.contentwindow; ifr.addeventlistener("load", iframeloaded, false); function iframeloaded() { otherwindow.postmessage('hello from the main page!', '*', [channel.port2]); } channel.port1.onmessage = handlemessage; function handlemessage(e) { para.innerhtml = e.data; } for a full working example, see our channel messaging basic demo on github (run it live too).
MessagePort - Web APIs
example in the following example, you can see a new channel being created using the messagechannel() constructor.
...it for the iframe to load iframe.addeventlistener("load", onload); function onload() { // listen for messages on port1 channel.port1.onmessage = onmessage; // transfer port2 to the iframe iframe.contentwindow.postmessage('hello from the main page!', '*', [channel.port2]); } // handle messages received on port1 function onmessage(e) { output.innerhtml = e.data; } for a full working example, see our channel messaging basic demo on github (run it live too).
MouseEvent.altKey - Web APIs
WebAPIMouseEventaltKey
on some linux variants, for example, a left mouse click combined with the alt key is used to move or resize windows.
... example this example logs the altkey property when you trigger a click event.
MouseEvent.buttons - Web APIs
for example, if the secondary (2) and auxilary (4) buttons are pressed simultaneously, the value is 6 (i.e., 2 + 4).
... 0 : no button or un-initialized 1 : primary button (usually the left button) 2 : secondary button (usually the right button) 4 : auxiliary button (usually the mouse wheel button or middle button) 8 : 4th button (typically the "browser back" button) 16 : 5th button (typically the "browser forward" button) example this example logs the buttons property when you trigger a mousedown event.
MouseEvent.clientX - Web APIs
for example, clicking on the left edge of the client area will always result in a mouse event with a clientx value of 0, regardless of whether the page is scrolled horizontally.
... example this example displays your mouse's coordinates whenever you trigger the mousemove event.
MouseEvent.clientY - Web APIs
for example, clicking on the top edge of the client area will always result in a mouse event with a clienty value of 0, regardless of whether the page is scrolled vertically.
... example this example displays your mouse's coordinates whenever you trigger the mousemove event.
MouseEvent.metaKey - Web APIs
on windows, for example, this key may open the start menu.
... example this example logs the metakey property when you trigger a click event.
MouseEvent.screenX - Web APIs
example this example displays your mouse's coordinates whenever you trigger the mousemove event.
...'#screen-log'); document.addeventlistener('mousemove', logkey); function logkey(e) { screenlog.innertext = ` screen x/y: ${e.screenx}, ${e.screeny} client x/y: ${e.clientx}, ${e.clienty}`; } result routing an event when you trap events on the window, document, or other roomy elements, you can get the coordinates of that event (e.g., a click) and route it properly, as the following example demonstrates: function checkclickmap(e) { if (e.screenx < 50) doredbutton(); if (50 <= e.screenx && e.screenx < 100) doyellowbutton(); if (e.screenx >= 100) doredbutton(); } specifications specification status comment css object model (cssom) view modulethe definition of 'screenx' in that specification.
MouseEvent - Web APIs
this lets you, for example, determine whether a mouse event was generated by an actual mouse or by a touch event (which might affect the degree of accuracy with which you interpret the coordinates associated with the event).
... example this example demonstrates simulating a click (that is programmatically generating a click event) on a checkbox using dom methods.
MutationObserver.MutationObserver() - Web APIs
see the example below for more details.
... example this example simply creates a new mutationobserver configured to watch a node and all of its children for additions and removals of elements to the tree, as well as any changes to attributes on any of the elements in the tree.
MutationObserver.observe() - Web APIs
(for example, if mutationobserverinit.childlist, mutationobserverinit.attributes, and mutationobserverinit.characterdata are all false.) the value of options.attributes is false (indicating that attribute changes are not to be monitored), but attributeoldvalue is true and/or attributefilter is present.
... example in this example, we demonstrate how to call the method observe() on an instance of mutationobserver, once it has been set up, passing it a target element and a mutationobserverinit options object.
MutationObserverInit.attributeFilter - Web APIs
example in this example, a mutation observer is set up to watch for changes to the status and username attributes in any elements contained within a subtree that displays the names of users in a chat room.
... this lets the code, for example, reflect changes to users' nicknames, or to mark them as away from keyboard (afk) or offline.
MutationObserverInit.attributeOldValue - Web APIs
example in this example, a mutation observer is set up to watch for changes to the status and username attributes in any elements contained within a subtree that displays the names of users in a chat room.
... this lets the code, for example, reflect changes to users' nicknames, or to mark them as away from keyboard (afk) or offline.
MutationObserverInit.attributes - Web APIs
example in this example, a mutation observer is set up to watch for changes to the status and username attributes in any elements contained within a subtree that displays the names of users in a chat room.
... this lets the code, for example, reflect changes to users' nicknames, or to mark them as away from keyboard (afk) or offline.
MutationObserverInit.subtree - Web APIs
for example, to watch the target node only for attribute changes, the mutationobserverinit passed into mutationobserver() can be: var options = { attributes: true, subtree: false }; since the default value of subtree is false, line 3 is optional.
... to monitor the entire subtree for attribute changes, simply set subtree to true: var options = { attributes: true, subtree: true }; example specifications specification status comment domthe definition of 'mutationobserverinit.subtree' 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!
... await self.registration.navigationpreload.enable(); } }()); }); using a preloaded response the following example shows the implementation of a fetch event that uses a preloaded response.
Navigator.cookieEnabled - Web APIs
for example, chrome 80+ does not allow creating cookies with samesite=none attribute, unless they are created over https and with secure attribute.
... example if (!navigator.cookieenabled) { // the browser does not support or is blocking cookies from being set.
Navigator.mediaSession - Web APIs
an internet radio app, for example, can use setactionhandler() to let fhe media controls on a keyboard or elsehwere on the user's device be used to control the app's media playback.
... example in this example, metadata is submitted to the mediasession object.
Navigator.requestMediaKeySystemAccess() - Web APIs
for example com.example.somesystem or org.w3.clearkey.
... notsupportederror either the specified keysystem isn't supported by the platform or the browser, or none of the configurations specified by supportedconfigurations can be satisfied (if, for example, none of the codecs specified in contenttype are available).
navigator.hardwareConcurrency - Web APIs
so a four-core cpu may offer eight logical processor cores, for example.
... 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.
NavigatorID.userAgent - Web APIs
for example: in firefox, you can change the preference general.useragent.override in about:config.
...gecko-based browsers comply with the following general structure: useragent = appcodename/appversion number (platform; security; os-or-cpu; localization; rv: revision-version-number) product/productsub application-name application-name-version example alert(window.navigator.useragent) // alerts "mozilla/5.0 (windows; u; win98; en-us; rv:0.9.2) gecko/20010725 netscape6/6.1" specifications specification status comment html living standardthe definition of 'navigatorid.useragent' in that specification.
NavigatorLanguage.language - Web APIs
examples of valid language codes include "en", "en-us", "fr", "fr-fr", "es-es", etc.
... example if (/^en\b/.test(navigator.language)) { dolangselect(window.navigator.language); } specifications specification status comment html living standardthe definition of 'navigatorlanguage: language' in that specification.
Online and offline events - Web APIs
example there's a simple test case that you can run to verify that the events are working (does not work in chrome due to attaching the event listener to document.body).
...offline', updateonlinestatus); }); a touch of css #status { position: fixed; width: 100%; font: bold 1em sans-serif; color: #fff; padding: 0.5em; } #log { padding: 2.5em 0.5em 0.5em; font: 1em sans-serif; } .online { background: green; } .offline { background: red; } and the corresponding htmlxxx when mochitests for this are created, point to those instead and update this example -nickolay <div id="status"></div> <div id="log"></div> <p>this is a test</p> here's the live result notes if the api isn't implemented in the browser, you can use other signals to detect if you are offline including using service workers and responses from xmlhttprequest.
NavigatorPlugins.plugins - Web APIs
examples the following example function returns the version of the shockwave flash plugin.
...in chrome) return flash.description.replace(/shockwave flash /,""); } } the following example displays information about the installed plugin(s).
Node.childNodes - Web APIs
WebAPINodechildNodes
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!
...(for example, to get the name of the first childnode: elementnodereference.childnodes[1].nodename.) the document object itself has 2 children: the doctype declaration and the root element, typically referred to as documentelement.
Node.compareDocumentPosition() - Web APIs
for example, if othernode is located earlier in the document and contains the node on which comparedocumentposition() was called, then both the document_position_contains and document_position_preceding bits would be set, producing a value of 10 (0x0a).
... example const head = document.head; const body = document.body; if (head.comparedocumentposition(body) & node.document_position_following) { console.log('well-formed document'); } else { console.error('<head> is not before <body>'); } note: because the result returned by comparedocumentposition() is a bitmask, the bitwise and operator must be used for meaningful results.
Node.getRootNode() - Web APIs
WebAPINodegetRootNode
this will differ in exact form depending on where you called getrootnode(); for example: calling it on an element inside a standard web page will return an htmldocument object representing the entire page.
... 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
WebAPINodeisConnected
the isconnected read-only property of the node interface returns a boolean indicating whether the node is connected (directly or indirectly) to the context object, for example the document object in the case of the normal dom, or the shadowroot in the case of a shadow dom.
... 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('style'); console.log(style.isconnected); // returns false style.textcontent = ` .wrapper { position: relative; } .info { font-size: 0.8rem; width: 200px; display: inline-block; border: 1px solid black; padding...
Node.localName - Web APIs
WebAPINodelocalName
syntax name = element.localname name is the local name as a string (see notes below for details) example (must be served with xml content type, such as text/xml or application/xhtml+xml.) <html xmlns="http://www.w3.org/1999/xhtml" xmlns:svg="http://www.w3.org/2000/svg"> <head> <script type="application/javascript"><![cdata[ function test() { var text = document.getelementbyid('text'); var circle = document.getelementbyid('circle'); text.value = "<svg:circle> has:\n" + "localname = '" + circle.localname + "'\n" + "namespaceuri = '" + circle.namespac...
...for example, in the qualified name ecomm:partners, partners is the local name and ecomm is the prefix: <ecomm:business id="soda_shop" type="brick_n_mortar" xmlns:ecomm="http://example.com/ecomm"> <ecomm:partners> <ecomm:partner id="1001">tony's syrup warehouse </ecomm:partner> </ecomm:partners> </ecomm:business> note: in gecko 1.9.2 and earlier, the property returns the upper-cased version of...
Node.nodeType - Web APIs
WebAPINodenodeType
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 c...
...omments this example checks if the first node inside the document element is a comment, and displays a message if not.
Node.previousSibling - Web APIs
syntax previousnode = node.previoussibling; example <img id="b0"> <img id="b1"> <img id="b2"> console.log(document.getelementbyid("b1").previoussibling); // <img id="b0"> console.log(document.getelementbyid("b2").previoussibling.id); // "b1" notes gecko-based browsers insert text nodes into a document to represent whitespace in the source markup.
... therefore a node obtained, for example, using node.firstchild or node.previoussibling may refer to a whitespace text node rather than the actual element the author intended to get.
Node.rootNode - Web APIs
WebAPINoderootNode
example running the following line in supporting browsers should return a reference to the html/document node: console.log(document.body.rootnode); notes gecko-based browsers insert text nodes into a document to represent whitespace in the source markup.
... therefore a node obtained, for example, using node.firstchild or node.previoussibling may refer to a whitespace text node rather than the actual element the author intended to get.
NodeList.prototype.forEach() - Web APIs
WebAPINodeListforEach
example let node = document.createelement("div"); let kid1 = document.createelement("p"); let kid2 = document.createtextnode("hey"); let kid3 = document.createelement("span"); node.appendchild(kid1); node.appendchild(kid2); node.appendchild(kid3); let list = node.childnodes; list.foreach( function(currentvalue, currentindex, listobj) { console.log(currentvalue + ', ' + currentindex + ', ' + thi...
...(callback, thisarg) { thisarg = thisarg || window; for (var i = 0; i < this.length; i++) { callback.call(thisarg, this[i], i, this); } }; } or if (window.nodelist && !nodelist.prototype.foreach) { nodelist.prototype.foreach = array.prototype.foreach; } the above behavior is how many browsers actually implement nodelist.prototype.foreach() (chrome, for example).
NodeList.length - Web APIs
WebAPINodeListlength
example the length property is often useful in dom programming.
...it's also commonly used as the iterator in a for loop, as in this example.
Notification.timestamp - Web APIs
for example, a timestamp for an upcoming meeting could be set in the future, whereas a timestamp for a missed message could be set in the past.
... examples the following snippet fires a notification; a simple options object is created, then the notification is fired using the notification() constructor.
Notifications API - Web APIs
this should be done in response to a user gesture, such as clicking a button, for example: btn.addeventlistener('click', function() { let promise = notification.requestpermission(); // wait for permission }) this is not only best practice — you should not be spamming users with notifications they didn't agree to — but going forward browsers will explicitly disallow notifications not triggered in response to a user gesture.
... firefox is already doing this from version 72, for example.
OVR_multiview2 - Web APIs
examples this example is taken from the specification.
... see also this three.js demo for a live multiview example.
OfflineAudioContext.startRendering() - Web APIs
example in this simple example, we declare both an audiocontext and an offlineaudiocontext object.
... note: for a working example, see our offline-audio-context-promise github repo (see the source code too.) // define online and offline audio context var audioctx = new audiocontext(); var offlinectx = new offlineaudiocontext(2,44100*40,44100); source = offlinectx.createbuffersource(); // use xhr to load an audio track, and // decodeaudiodata to decode it and offlineaudiocontext to render it function getdata() { requ...
OfflineAudioContext - Web APIs
examples in this simple example, we declare both an audiocontext and an offlineaudiocontext object.
... note: for a working example, see our offline-audio-context-promise github repo (see the source code too.) // define online and offline audio context var audioctx = new audiocontext(); var offlinectx = new offlineaudiocontext(2,44100*40,44100); source = offlinectx.createbuffersource(); // use xhr to load an audio track, and // decodeaudiodata to decode it and offlineaudiocontext to render it function getdata() { requ...
OffscreenCanvas.convertToBlob() - Web APIs
syntax promise<blob> offscreencanvas.converttoblob(options); parameters optionsoptional you can specify several options when converting your offscreencanvas object into a blob object, for example: const blob = offscreencanvas.converttoblob({ type: "image/jpeg", quality: 0.95 }); options: type: a domstring indicating the image format.
... examples var offscreen = new offscreencanvas(256, 256); var gl = offscreen.getcontext("webgl"); // ...
OffscreenCanvas.convertToBlob() - Web APIs
syntax promise<blob> offscreencanvas.converttoblob(options); parameters optionsoptional you can specify several options when converting your offscreencanvas object into a blob object, for example: const blob = offscreencanvas.converttoblob({ type: "image/jpeg", quality: 0.95 }); options: type: a domstring indicating the image format.
... examples var offscreen = new offscreencanvas(256, 256); var gl = offscreen.getcontext("webgl"); // ...
OffscreenCanvas.getContext() - Web APIs
contextattributes you can use several context attributes when creating your rendering context, for example: offscreen.getcontext("webgl", { antialias: false, depth: false }); 2d context attributes: alpha: boolean that indicates if the canvas contains an alpha channel.
... 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.convertToBlob() - Web APIs
syntax promise<blob> offscreencanvas.converttoblob(options); parameters options optional you can specify several options when converting your offscreencanvas object into a blob object, for example: const blob = offscreencanvas.converttoblob({ type: "image/jpeg", quality: 0.95 }); options: type: a domstring indicating the image format.
... examples var offscreen = new offscreencanvas(256, 256); var gl = offscreen.getcontext("webgl"); // ...
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.
... model.quaternion.fromarray(sensor.quaternion).inverse(); }); sensor.addeventlistener('error', error => { if (event.error.name == 'notreadableerror') { console.log("sensor is not available."); } }); sensor.start(); permissions example using orientation sensors requires requsting permissions for multiple device sensors.
OscillatorNode.detune - Web APIs
example the following example shows basic usage of an audiocontext to create an oscillator node.
... for applied examples/information, check out our violent theremin demo (see app.js for relevant code).
OscillatorNode.frequency - Web APIs
example the following example shows basic usage of an audiocontext to create an oscillator node.
... for an applied example, check out our violent theremin demo (see app.js for relevant code).
OscillatorNode.onended - Web APIs
}; example the following example shows basic usage of an audiocontext to create an oscillator node.
... for an applied example, check out our violent theremin demo (see app.js for relevant code).
OscillatorNode.start() - Web APIs
example the following example shows basic usage of an audiocontext to create an oscillator node.
... for an applied example, check out our violent theremin demo (see app.js for relevant code).
OscillatorNode.stop() - Web APIs
example the following example shows basic usage of an audiocontext to create an oscillator node.
... for an applied example, check out our violent theremin demo (see app.js for relevant code).
OscillatorNode.type - Web APIs
example the following example shows basic usage of an audiocontext to create an oscillator node.
... for an applied example, check out our violent theremin demo (see app.js for relevant code).
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.
... for an applied example, check out our violent theremin demo (see app.js for relevant code).
ParentNode.replaceChildren() - Web APIs
examples emptying a node replacechildren() provides a very convenient mechanism for emptying a node of all its children.
...for example, say we have a simple application allowing you to choose what food you want for your party.
PasswordCredential.additionalData - Web APIs
example the following example creates a formdata object with an appended csrf token.
...navigator.credentials.get(options).then(function(creds) { if (creds.type == 'password') { var form = new formdata(); var csrf_token = document.queryselector('csrf_token').value; form.append('csrf_token', csrf_token); creds.additionaldata = form; fetch('https://www.example.com', { method: 'post', credentials: creds }); }; }); specifications specification status comment credential management level 1 working draft initial definition.
Path2D() - Web APIs
WebAPIPath2DPath2D
examples creating and copying paths this example creates and copies a path2d path.
... <canvas id="canvas"></canvas> const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); let path1 = new path2d(); path1.rect(10, 10, 100,100); let path2 = new path2d(path1); path2.moveto(220, 60); path2.arc(170, 60, 50, 0, 2 * math.pi); ctx.stroke(path2); using svg paths this example creates a path2d path using svg path data.
PaymentCurrencyAmount.value - Web APIs
see the example verifying a properly formatted price below for a simple regular expression that can be used to validate the value string prior to submission.
... 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 the value entered as a price is formatted correctly prior to submission by matching it against a simple regular expression: function checkpriceformat(price) { let validregex = /^-?[0-9]+(\.[0-9]+)?$/; return validregex.test(price); } this function, checkpriceformat(), will return true if the specified price string is formatted properly, or false if it's not.
PaymentRequest.onpaymentmethodchange - Web APIs
for example, when using apple pay, the user can swipe to select different credit cards, debit cards, and so forth.
... 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 han...
PaymentRequest: paymentmethodchange event - Web APIs
for example, if the user switches from one credit card to another on their apple pay account, a paymentmethodchange event is fired to let you know about the change.
... bubbles no cancelable no interface paymentmethodchangeevent event handler property onpaymentmethodchange examples let's take a look at an example.
PaymentRequest.shippingAddress - Web APIs
syntax var paymentaddress = paymentrequest.shippingaddress; example generally, the user agent will fill the shippingaddress property value.
... in the example below, the cost of shipping varies by geography.
PaymentRequest: shippingoptionchange event - Web APIs
bubbles no cancelable no interface paymentrequestupdateevent event handler property onshippingoptionchange examples this code snippet sets up a handler for the shippingoptionchange event.
...for example, if there are three options (such as "free ground shipping", "2-day air", and "next day"), each time the user chooses one of those options, this event handler is called to recalculate the total based on the changed shipping option.
PaymentResponse.shippingAddress - Web APIs
example generally, the user agent will fill the shippingaddress property for you.
... in the example below, the cost of shipping varies by geography.
PaymentResponse - Web APIs
the contents of the object depend on the payment method being used; for example, if the basic card payment method is used, this object must conform to the structure defined in the basiccardresponse dictionary.
... paymentresponse.methodname read only secure context returns the payment method identifier for the payment method that the user selected, for example, visa, mastercard, paypal, etc..
PaymentValidationErrors - Web APIs
for example, if the user chose to pay by credit card using the basic-card payment method, this is a basiccarderrors object.
... example specifications specification status comment payment request api candidate recommendation initial definition.
performance.getEntries() - Web APIs
the list's members (entries) can be created by making performance marks or measures (for example by calling the mark() method) at explicit points in time.
... example function use_performanceentry_methods() { console.log("performanceentry tests ..."); if (performance.mark === undefined) { console.log("...
performance.getEntriesByName() - Web APIs
the list's members (entries) can be created by making performance marks or measures (for example by calling the mark() method) at explicit points in time.
... example function use_performanceentry_methods() { log("performanceentry tests ..."); if (performance.mark === undefined) { log("...
performance.getEntriesByType() - Web APIs
the list's members (entries) can be created by making performance marks or measures (for example by calling the mark() method) at explicit points in time.
... example function useperformanceentrymethods() { log("performanceentry tests ..."); if (performance.mark === undefined) { log("...
performance.measure() - Web APIs
return value void example the following example shows how measure() is used to create a new measure performance entry in the browser's performance entry buffer.
... const markernamea = "example-marker-a" const markernameb = "example-marker-b" // run some nested timeouts, and create a performancemark for each.
performance.now() - Web APIs
WebAPIPerformancenow
for example, firefox rounds the returned time to 1 millisecond increments.
... syntax t = performance.now(); example const t0 = performance.now(); dosomething(); const t1 = performance.now(); console.log(`call to dosomething took ${t1 - t0} milliseconds.`); unlike other timing data available to javascript (for example date.now), the timestamps returned by performance.now() are not limited to one-millisecond resolution.
PerformanceEntry.entryType - Web APIs
the entrytype property returns a domstring representing the type of performance metric such as, for example, "mark".
... longtask performancelongtasktiming domstring reports instances of long tasks example the following example shows the use of the entrytype property.
PerformanceObserverEntryList.getEntries() - Web APIs
"initiatortype", the type of the initiating resource (for example an html element).
... example function print_perf_entry(pe) { console.log("name: " + pe.name + "; entrytype: " + pe.entrytype + "; starttime: " + pe.starttime + "; duration: " + pe.duration); } // create observer for all performance event types var observe_all = new performanceobserver(function(list, obs) { var perfentries; // print all entries perfentries = li...
PerformanceResourceTiming - Web APIs
an application can use the timing metrics to determine, for example, the length of time it takes to fetch a specific resource, such as an xmlhttprequest, <svg>, image, or script.
... example see the example in using the resource timing api.
Permissions.query() - Web APIs
WebAPIPermissionsquery
firefox for example currently supports geolocation, notifications, push, and persistent-storage (see our permissions.webidl file).
... example navigator.permissions.query({name:'geolocation'}).then(function(result) { if (result.state == 'granted') { showlocalnewswithgeolocation(); } else if (result.state == 'prompt') { showbuttontoenablelocalnews(); } // don't do anything if the permission was denied.
PhotoCapabilities - Web APIs
example the following example, extracted from chrome's image capture / photo resolution sample, uses the results from getphotocapabilities() to modify the size of an input range.
... this example also shows how the imagecapture object is created using a mediastreamtrack retrieved from a device's mediastream.
PluginArray - Web APIs
examples the following example function returns the version of the shockwave flash plugin.
...table'); for(var i = 0; i < pluginslength; i++) { let newrow = table.insertrow(); newrow.insertcell().textcontent = navigator.plugins[i].name; newrow.insertcell().textcontent = navigator.plugins[i].filename; newrow.insertcell().textcontent = navigator.plugins[i].description; newrow.insertcell().textcontent = navigator.plugins[i].version?navigator.plugins[i].version:""; } the following example displays information about the installed plugin(s).
PointerEvent.height - Web APIs
depending on the source of the pointer device (for example a finger), for a given pointer, each event may produce a different value.
... example an example of this property is included in the pointerevent.width example.
PointerEvent.isPrimary - Web APIs
for example, a touch contact and a mouse cursor moved simultaneously will produce pointers that are both considered primary.
... example this example illustrates using the value of isprimary to call the appropriate processing function.
PointerEvent - Web APIs
pointercancel a browser fires this event if it concludes the pointer will no longer be able to generate events (for example the related device is deactived).
... example examples of each property, event type, and global event handler are included in their respective reference pages.
Pinch zoom gestures - Web APIs
this example shows how to detect the pinch/zoom gesture, which uses pointer events to detect whether the user moves two pointers closer or farther apart from each other.
... example in this example, you use the pointer events to simultaneously detect two pointing devices of any type, including fingers, mice, and pens.
PopStateEvent - Web APIs
the popstate event as an 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", "?page=3"); histo...
...ry.back(); // alerts "location: http://example.com/example.html?page=1, state: {"page":1}" history.back(); // alerts "location: http://example.com/example.html, state: null history.go(2); // alerts "location: http://example.com/example.html?page=3, state: {"page":3} note that even though the original history entry (for http://example.com/example.html) has no state object associated with it, a popstate event is still fired when we activate that entry after the second call to history.back().
Proximity Events - Web APIs
these events make it possible to react to such a change, for example by shutting down the screen of a smartphone when the user is having a phone call with the device close to their ear.
... example window.addeventlistener('userproximity', function(event) { if (event.near) { // let's power off the screen navigator.mozpower.screenenabled = false; } else { // otherwise, let's power on the screen navigator.mozpower.screenenabled = true; } }); specifications specification status comment proximity sensorthe definition of 'proximity events' in t...
PublicKeyCredential.id - Web APIs
note: this property may only be used in top-level contexts and will not be available in an <iframe> for example.
... 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.credentials.create({ publickey }) .then(function (newcredentialinfo) { var id = newcredentialinfo.id; // do something with the id // send attestation response and client extensions // to the server to proceed with the registration // of the credential }...
PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable() - Web APIs
note: this method may only be used in top-level contexts and will not be available in an <iframe> for example.
... 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
note: this property may only be used in top-level contexts and will not be available in an <iframe> for example.
... 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({ publickey: options }) .then(function (pubkeycredential) { var rawid = pubkeycredential.rawid; // do something with rawid }).catch...
PublicKeyCredential.response - Web APIs
note: this property may only be used in top-level contexts and will not be available in an <iframe> for example.
... 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 }) .then(function (pubkeycr...
PublicKeyCredential - Web APIs
examples creating a new instance of publickeycredential here, we use navigator.credentials.create() to generate a new credential.
... 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 response = newcredentialinfo.response; var clientextensionsresults = newcredentialinfo.getclientextensionresults(); }).catch(function (err) { console.error(err); }); getting an existing instance of publickeycredential here, we fetch an existing credential from an authenticator, using navigator.credentials.get().
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 ser...
...ver */, 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({ publickey }) .then(function (newcredentialinfo) { // send attestation response and client extensions // to the server to proceed with the registration // of the credential }).catch(function (err) { console.error(err); }); specifications specification status comment web authentication: an api for accessing public key credentials level 1the definition of 'excludecredentials' in that specification.
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 : "logi...
...n.example.com" }, user: { id: new uint8array(26), /* to be changed for each user */ name: "jdoe@example.com", displayname: "john doe", } }; navigator.credentials.create({ publickey }) .then(function (newcredentialinfo) { // send attestation response and client extensions // to the server to proceed with the registration // of the credential }).catch(function (err) { console.error(err); }); specifications specification status comment web authentication: an api for accessing public key credentials level 1the definition of 'pubkeycredparams' in that specification.
PublicKeyCredentialCreationOptions.timeout - Web APIs
examples var publickey = { timeout: 6000, // accepting to wait for a minute before giving up.
... 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.credentials.create({ publickey }) .then(function (newcredentialinfo) { // send attestation response and client extensions // to the server to proceed with the registration // of the credential }).catch(function (err) { console.error(err); }); specifications specification status comment web authentication: an api for accessing public key credentials level 1the definition of 't...
PublicKeyCredentialCreationOptions.user - Web APIs
"jdoe@example.com").this property is intended for display and may be use to distinguish different account with the same displayname.
... 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/avatar/jdoe.png" }, pubkeycredparams: [ { type: "public-key", alg: -7 } ] }; navigator.credentials.create({ publickey }) .then(function (newcredentialinfo) { // send attestation response and client extensions // to the server to proceed with the registration // of the credential }).catch(function (err) { console.error(err); }); specifications ...
PublicKeyCredentialRequestOptions.rpId - Web APIs
for example, if you are browsing on foo.example.com, the rpid value may be "example.com" but not "bar.org" or "baz.example.com".
... 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 ...
PublicKeyCredentialRequestOptions - Web APIs
"login.example.org").
... 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) // actu...
PushEvent.data - Web APIs
WebAPIPushEventdata
examples the following example takes data from a pushevent and displays it on all of the service workers' clients.
..."something has happened"; var message = data.message || "here's something you might want to check out."; var icon = "images/new-notification.png"; var notification = new notification(title, { body: message, tag: 'simple-push-demo-notification', icon: icon }); notification.addeventlistener('click', function() { if (clients.openwindow) { clients.openwindow('https://example.blog.com/2015/03/04/something-new.html'); } }); }); specifications specification status comment push apithe definition of 'data' in that specification.
PushEvent - Web APIs
WebAPIPushEvent
examples the following example takes data from a pushevent and displays it on all of the service worker's clients.
...thing has happened"; var message = data.message || "here's something you might want to check out."; var icon = "images/new-notification.png"; var notification = new self.notification(title, { body: message, tag: 'simple-push-demo-notification', icon: icon }); notification.addeventlistener('click', function() { if (clients.openwindow) { clients.openwindow('https://example.blog.com/2015/03/04/something-new.html'); } }); }); specifications specification status comment push apithe definition of 'pushevent' in that specification.
PushManager - Web APIs
example this.onpush = function(event) { console.log(event.data); // from here we can write the data to indexeddb, send it to any open // windows, display a notification, etc.
... } navigator.serviceworker.register('serviceworker.js').then( function(serviceworkerregistration) { serviceworkerregistration.pushmanager.subscribe().then( function(pushsubscription) { console.log(pushsubscription.endpoint); // the push subscription details needed by the application // server are now available, and can be sent to it using, // for example, an xmlhttprequest.
RTCDataChannel.bufferedAmount - Web APIs
this event may be used, for example, to implement code which queues more messages to be sent whenever there's room to buffer them.
... example the snippet below includes a function which changes the contents of a block with the id "buffersize" to a string indicating the number of bytes currently buffered on an rtcdatachannel.
RTCDataChannel.bufferedAmountLowThreshold - Web APIs
this event may be used, for example, to implement code which queues more messages to be sent whenever there's room to buffer them.
... syntax var threshold = adatachannel.bufferedamountlowthreshold; adatachannel.bufferedamountlowthreshold = threshold; value the number of queued outgoing data bytes below which the buffer is considered to be "low." example in this snippet of code, bufferedamountlowthreshold is set to 64kb, and a handler for the bufferedamountlow event is established by setting the rtcdatachannel.onbufferedamountlow property to a function which should send more data into the buffer by calling send().
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", "unrecog...
...for example, an sdp syntax error displays the line number of the error within the sdp, and an sctp error displays a message corresponding to the sctp cause code.
RTCDataChannel.protocol - Web APIs
the ability for each channel to have a defined subprotocol lets your app, for example, use json objects as messages on one channel while another channel is plaintext and another is raw binary or even some other format.
... example var pc = new rtcpeerconnection(); var dc = pc.createdatachannel("my channel", { protocol: "json" }); function handlechannelmessage(datachannel, msg) { switch(datachannel.protocol) { case "json": /* process json data */ break; case "raw": /* process raw binary data */ break; } } specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcdatachannel.protocol' in that specification.
RTCDataChannel.send() - Web APIs
for example, if one peer is a modern browser that supports using the eor (end of record) flag to indicate when a received message is the last piece of a multi-part object sent using send().
... example in this example, a routine called sendmessage() is created; it accepts an object as input and sends to the remote peer, over the rtcdatachannel, a json string with the specified object and a time stamp.
RTCDataChannel - Web APIs
for example, after rtcdatachannel.close() was called but the underlying data transport might not have been closed yet.onerror the rtcdatachannel.onerror property is an eventhandler which specifies a function to be called when the error event is received.
... example var pc = new rtcpeerconnection(); var dc = pc.createdatachannel("my channel"); dc.onmessage = function (event) { console.log("received: " + event.data); }; dc.onopen = function () { console.log("datachannel open"); }; dc.onclose = function () { console.log("datachannel close"); }; specifications specification status comment webrtc 1.0: real-time communicat...
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.
... pc.ondatachannel = function(event) { inbounddatachannel = event.channel; inbounddatachannel.onmessage = handleincomingmessage; inbounddatachannel.onopen = handlechannelopen; inbounddatachannel.onclose = handlechannelclose; } see a simple rtcdatachannel sample for another, more complete, example of how to use data channels.
RTCDtlsTransport - Web APIs
for example, to create the connection using the highest level of bundling: const rtcconfig = { bundlepolicy: "max-bundle" }; const pc = new rtcpeerconnection(rtcconfig); bundling lets you use one rtcdtlstransport to carry the data for multiple higher-level transports, such as multiple rtcrtptransceivers.
... 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
WebAPIRTCError
examples in this example, a handler is established for an rtcdatachannel's error event.
... the above example uses addeventlistener() to add the handler for error events.
RTCErrorEvent.error - Web APIs
examples in this example, a handler is established for an rtcdatachannel's error event.
... the above example uses addeventlistener() to add the handler for error events.
RTCIceCandidate.priority - Web APIs
in this example, the priority is 2043278322.
... example this candidate examines the priority of the candidate and, if it's greater than the priority of a previously-seen candidate, remembers the candidate for later use.
RTCIceCandidate.protocol - Web APIs
usage notes here's an example candidate a-line from an ice transaction: a=candidate:4234997325 1 udp 2043278322 192.168.0.56 44323 typ host the third field, "udp", is the protocol type, indicating that the candidate would use the udp transport protocol.
... example this code snippet examines the value of protocol to decide if it should look at the value of tcptype to see if it's a simultaneous-open (s-o) candidate.
RTCIceCandidate.relatedPort - Web APIs
see the example, which shows a bit of this.
... example in this example, the candidate's type is checked, and then debugging output is presented, based on the candidate type, including the candidate's type, address (ip and port), and related address (relatedaddress and relatedport).
RTCIceCandidate. toJSON() - Web APIs
see the example below.
... example this simple example obtains a json string representing an rtcicecandidate found in the variable candidate.
RTCIceCandidateInit.candidate - Web APIs
in the example above, the priority is 2043278322.
...the complete list of attributes for this example candidate is: foundation = 4234997325 component = "rtp" (the number 1 is encoded to this string; 2 becomes "rtcp") protocol = "udp" priority = 2043278322 ip = "192.168.0.56" port = 44323 type = "host" example when a new ice candidate is received by your signaling code from the remote peer, you need to construct the rtcicecandidate object that encapsulates it.
RTCIceCandidateStats.networkType - Web APIs
for example, if the networktype is wifi but the user is connected using a cellular hotspot, the connection will be bottlenecked by the underlying cellular network (and any other networks between the two peers).
... example this example sets up a periodic function using setinterval() that outputs statistics reports for candidates that use or would use a cellular data network to a log view.
RTCIceServer.credential - Web APIs
}; var credential = iceserver.credential; iceserver.credential = newcredential; example this example creates a new rtcpeerconnection which uses a turn server at turnserver.example.org to negotiate connections.
... mypeerconnection = new rtcpeerconnection({ iceservers: [ { urls: "turn:turnserver.example.org", // a turn server username: "webrtc", credential: "turnpassword" } ] }); specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtciceserver.credential' in that specification.
RTCIceServer.credentialType - Web APIs
example this example creates a new rtcpeerconnection which will use a turn server at turnserver.example.org to negotiate connections.
... mypeerconnection = new rtcpeerconnection({ iceservers: [ { urls: "turn:turnserver.example.org", // a turn server username: "webrtc", credential: "turnpassword", credentialtype: "password" } ] }); specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtciceserver.credential' in that specification.
RTCIceServer.username - Web APIs
}; var username = iceserver.username; iceserver.username = newusername; example this example creates a new rtcpeerconnection which will use a turn server at turnserver.example.org to negotiate connections.
... mypeerconnection = new rtcpeerconnection({ iceservers: [ { urls: "turn:turnserver.example.org", // a turn server username: "webrtc", credential: "turnpassword" } ] }); specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtciceserver.username' in that specification.
RTCInboundRtpStreamStats - Web APIs
this counter may also be incremented when fec packets arrive in-band along with media content; this can happen with opus, for example.
... examples specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcinboundrtpstreamstats' in that specification.
RTCOutboundRtpStreamStats.qpSum - Web APIs
for example, for the vp8 codec, the qp value can be anywhere from 1 to 127 and is found in the frame header element "y_ac_qi", whose value is defined in rfc 6386: 19.2.
... example calculating average quantization the calculateaverageqp() function shown below computes the average qp for the given rtcstats object that contains rtp stream statistics, returning 0 if the object doesn't describe an rtp stream.
RTCPeerConnection.addIceCandidate() - Web APIs
examples this code snippet shows how to signal ice candidates across an arbitrary signaling channel.
... // this example assumes that the other peer is using a signaling channel as follows: // // pc.onicecandidate = event => { // if (event.candidate) { // signalingchannel.send(json.stringify({ice: event.candidate})); // "ice" is arbitrary // } else { // // all ice candidates have been sent // } // } signalingchannel.onmessage = receivedstring => { const message = json.parse(receivedstring); if (message.ice) { // a typical value of ice here might look something like this: // // {candidate: "candidate:0 1 udp 2122154243 192.168.1.9 53421 typ host", sdpmid: "0", ...} // // pass the whole thing to addicecandidate: pc.addicecandidate(message.ice).catch(e => { console.log("failure during addicecandidate(): " + e.name); }); } else { // handle ot...
RTCPeerConnection.createDataChannel() - Web APIs
examples this example shows how to create a data channel and set up handlers for the open and message events to send and receive messages on it (for brievity, the example assumes onnegotiationneeded is set up).
...(event.data); } } alternatively, more symmetrical out-of-band negotiation can be used, using an agreed-upon id (0 here): // both sides var pc = new rtcpeerconnection(options); var channel = pc.createdatachannel("chat", {negotiated: true, id: 0}); channel.onopen = function(event) { channel.send('hi!'); } channel.onmessage = function(event) { console.log(event.data); } for a more thorough example showing how the connection and channel are established, see a simple rtcdatachannel sample.
RTCPeerConnection.getConfiguration() - Web APIs
example this example adds a new certificate to an active connection if it doesn't already have one in use.
...if ((configuration.certificates != undefined) && (!configuration.certificates.length)) { rtcpeerconnection.generatecertificate({ name: 'rsassa-pkcs1-v1_5', hash: 'sha-256', moduluslength: 2048, publicexponent: new uint8array([1, 0, 1]) }).then(function(cert) { configuration.certificates = [cert]; mypeerconnection.setconfiguration(configuration); }); } this example fetches the current configuration of the rtcpeerconnection, then looks to see if it has any certificates set by examining whether or not (a) the configuration has a value for certificates, and (b) whether its length is zero.
RTCPeerConnection: iceconnectionstatechange event - Web APIs
examples an event handler for this event can be added using the rtcpeerconnection.oniceconnectionstatechange property or by using addeventlistener() on the rtcpeerconnection.
... in this example, a handler for iceconnectionstatechange is set up to update a call state indicator by using the value of iceconnectionstate to create a string which corresponds to the name of a css class that we can assign to the status indicator to cause it to reflect the current state of the connection.
RTCPeerConnection.iceGatheringState - Web APIs
this lets you detect, for example, when collection of ice candidates has finished.
... example var pc = new rtcpeerconnection(); var state = pc.icegatheringstate; specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcpeerconnection.icegatheringstate' in that specification.
RTCPeerConnection: negotiationneeded event - Web APIs
examples in this example, we use addeventlistener() to create an event handler for negotiationneeded.
... the negotiationneeded event by assigning the event handler function to the rtcpeerconnection.onnegotiationneeded property: pc.onnegotiationneeded = ev => { pc.createoffer() .then(offer => return pc.setlocaldescription(offer)) .then(() => sendsignalingmessage({ type: "video-offer", sdp: pc.localdescription })) .catch(err => { /* handle error */ ); }; for a more detailed example, see starting negotiation in signaling and video calling.
RTCPeerConnectionIceErrorEvent.address - Web APIs
for example, on a mobile phone, there are typically at least two network interfaces available: the cellular connection and a wifi connection.
... examples this example creates a handler for icecandidateerror events which creates human readable messages describing the local network interface for the connection as well as the ice server that was being used to try to open the connection, then calls a function to display those as well as the event's errortext property's contents.
RTCRtcpParameters - Web APIs
this is used, for example, in sdes (sdp security descriptions) messages, described in rfc 4568.
... examples this example obtains the canonical name (cname) being used for rtcp on an rtcrtpsender or rtcrtpreceiver.
RTCRtpCodecCapability - Web APIs
properties channels optional an unsigned integer value indicating the maximum number of channels supported by the codec; for example, a codec that supports only mono sound would have a value of 1; stereo codecs would have a 2, etc.
... examples tbd specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcrtpcodeccapability' in that specification.
RTCRtpReceiver.getCapabilities() static function - Web APIs
for that reason, in privacy-sensitive contexts, the browser may choose to obscure the capabilities; this might be done, for example, by leaving out rarely-used codec configurations.
... example the function below returns a boolean indicating whether or not the device supports receiving h.264 video on a webrtc connection.
RTCRtpSender.getCapabilities() static function - Web APIs
for that reason, in privacy-sensitive contexts, the browser may choose to obscure the capabilities; this might be done, for example, by leaving out rarely-used codec configurations.
... example the function below returns a boolean indicating whether or not the device supports sending h.264 video on an rtcrtpsender.
RTCRtpSender.replaceTrack() - Web APIs
see the example switching cameras below.
... examples switching video cameras // example to change video camera, suppose selected value saved into window.selectedcamera navigator.mediadevices .getusermedia({ video: { deviceid: { exact: window.selectedcamera } } }) .then(function(stream) { let videotrack = stream.getvideotracks()[0]; pcs.foreach(function(pc) { var sender = pc.getsenders().find(funct...
RTCTrackEvent - Web APIs
you can add a track event listener to be notified when the new track is available so that you can, for example, attach its media to a <video> element, using either rtcpeerconnection.addeventlistener() or the ontrack event handler property.
... example this simple example creates an event listener for the track event which sets the srcobject of the <video> element with the id videobox to the first stream in the list passed in the event's streams array.
Range.setStart() - Web APIs
WebAPIRangesetStart
examples highlight part of an element this example uses the range.setstart() and range.setend() methods to add part of an address to a range.
...const endoffset = 5; // end at fifth node: dodge city, ks const range = document.createrange(); range.setstart(address, startoffset); range.setend(address, endoffset); const mark = document.createelement('mark'); range.surroundcontents(mark); result get characters from a text node this example uses the range.setstart() and range.setend() methods to define the contents of a range.
ReadableStream.ReadableStream() - Web APIs
examples in the following simple example, a custom readablestream is created using a constructor (see our simple random stream example for the full code).
...ntroller.enqueue(string); // show it on the screen let listitem = document.createelement('li'); listitem.textcontent = string; list1.appendchild(listitem); }, 1000); button.addeventlistener('click', function() { clearinterval(interval); fetchstream(); controller.close(); }) }, pull(controller) { // we don't really need a pull in this example }, cancel() { // this is called if the reader cancels, // so we should stop generating strings clearinterval(interval); } }); specifications specification status comment streamsthe definition of 'readablestream()' in that specification.
ReadableStream.getReader() - Web APIs
examples in the following simple example, a previously-created custom readablestream is read using a readablestreamdefaultreader created using getreader().
... (see our simple random stream example for the full code).
ReadableStream.pipeThrough() - Web APIs
for example, a textdecoder, has bytes written to it and strings read from it, while a video decoder has encoded bytes written to it and uncompressed video frames read from it.
... examples in the following example (see unpack chunks of a png for the full code running live, and png-transform-stream for the source code), an image is fetched and its body retrieved as a readablestream.
ReadableStream - Web APIs
examples in the following example, an artificial response is created to stream html fragments fetched from another resource to the browser.
... fetch("https://www.example.org/").then((response) => { const reader = response.body.getreader(); const stream = new readablestream({ start(controller) { // the following function handles each data chunk function push() { // "done" is a boolean and value a "uint8array" reader.read().then(({ done, value }) => { // is there no more data to read?
ReadableStreamDefaultController.close() - Web APIs
examples in the following simple example, a custom readablestream is created using a constructor (see our simple random stream example for the full code).
...ntroller.enqueue(string); // show it on the screen let listitem = document.createelement('li'); listitem.textcontent = string; list1.appendchild(listitem); }, 1000); button.addeventlistener('click', function() { clearinterval(interval); fetchstream(); controller.close(); }) }, pull(controller) { // we don't really need a pull in this example }, cancel() { // this is called if the reader cancels, // so we should stop generating strings clearinterval(interval); } }); specifications specification status comment streamsthe definition of 'close()' in that specification.
ReadableStreamDefaultController.enqueue() - Web APIs
examples in the following simple example, a custom readablestream is created using a constructor (see our simple random stream example for the full code).
...ntroller.enqueue(string); // show it on the screen let listitem = document.createelement('li'); listitem.textcontent = string; list1.appendchild(listitem); }, 1000); button.addeventlistener('click', function() { clearinterval(interval); fetchstream(); controller.close(); }) }, pull(controller) { // we don't really need a pull in this example }, cancel() { // this is called if the reader cancels, // so we should stop generating strings clearinterval(interval); } }); specifications specification status comment streamsthe definition of 'enqueue()' in that specification.
ReadableStreamDefaultController - Web APIs
examples in the following simple example, a custom readablestream is created using a constructor (see our simple random stream example for the full code).
...ntroller.enqueue(string); // show it on the screen let listitem = document.createelement('li'); listitem.textcontent = string; list1.appendchild(listitem); }, 1000); button.addeventlistener('click', function() { clearinterval(interval); fetchstream(); controller.close(); }) }, pull(controller) { // we don't really need a pull in this example }, cancel() { // this is called if the reader cancels, // so we should stop generating strings clearinterval(interval); } }); specifications specification status comment streamsthe definition of 'readablestreamdefaultcontroller' in that specification.
ReadableStreamDefaultReader.ReadableStreamDefaultReader() - Web APIs
examples in the following simple example, a previously-created custom readablestream is read using a readablestreamdefaultreader created using getreader().
... (see our simple random stream example for the full code).
ReadableStreamDefaultReader.cancel() - Web APIs
examples in the following simple example, a previously-created custom readablestream is read using a readablestreamdefaultreader created using getreader().
... (this code is based on our simple random stream example).
ReadableStreamDefaultReader - Web APIs
examples in the following example, an artifical response is created to stream html fragments fetched from another resource to the browser.
... fetch("https://www.example.org/").then((response) => { const reader = response.body.getreader(); const stream = new readablestream({ start(controller) { // the following function handles each data chunk function push() { // "done" is a boolean and value a "uint8array" return reader.read().then(({ done, value }) => { // is there no more data to read?
RelativeOrientationSensor - Web APIs
examples basic example the following example, which is loosely based on intel's orientation phone demo, instantiates an relativeorientationsensor with a frequency of 60 times a second.
... model.quaternion.fromarray(sensor.quaternion).inverse(); }); sensor.addeventlistener('error', error => { if (event.error.name == 'notreadableerror') { console.log("sensor is not available."); } }); sensor.start(); permissions example using orientation sensors requires requsting permissions for multiple device sensors.
Report.url - Web APIs
WebAPIReporturl
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.
... "https://www.example.com/cats.html" console.log(firstreport.url); }, options); specifications specification status comment reporting apithe definition of 'report.url' in that specification.
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 reportingobserve...
...r.observe(); this tells the observer to start collecting reports in its report queue, and runs the callback function specified inside the constructor: observer.observe(); later on in the example we deliberately use the deprecated version of mediadevices.getusermedia(): if(navigator.mozgetusermedia) { navigator.mozgetusermedia( constraints, success, failure); } else { navigator.getusermedia( constraints, success, failure); } this causes a deprecation report to be generated; because of the event handler we set up inside the reportingobserver() constructor, we can now click the button to display the report details.
Request.context - Web APIs
WebAPIRequestcontext
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.
... 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 request context in a variable: var myrequest = new request('flowers.jpg'); var mycontext = myrequest.context; // returns the empty string by default ...
Request.destination - Web APIs
the destination is used by the user agent to, for example, help determine which set of rules to follow for cors purposes, or how to navigate any complicated code paths that affect how specific types of request get handled.
... example 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 save the request's destination: var myrequest = new request('flowers.jpg'); var mydestination = myrequest.destination; // returns the empty string by default specifications specification status comment fetchthe definition of 'd...
ResizeObserver() - Web APIs
this could be used for example to automatically unobserve the observer when a certain condition is reached, but you can omit it if you don't need it.
... 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 { h1elem.style.fontsize = math.max(1.5, entry.contentrect.width/200) + 'rem'; pelem.style.fontsize = math.max(1, entry.contentrect.width/600) + 'rem'; } } ...
ResizeObserverEntry.contentBoxSize - Web APIs
examples the following snippet is taken from the resize-observer-border-radius.html (see source) example.
... this example includes a green box, sized as a percentage of the viewport size.
ResizeObserverEntry.target - Web APIs
examples the following snippet is taken from the resize-observer-border-radius.html (see source) example.
... this example includes a green box, sized as a percentage of the viewport size.
Response.redirected - Web APIs
see the example disallowing redirects, which shows this being done.
... 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
WebAPIResponse
you can create a new response object using the response.response() constructor, but you are more likely to encounter a response object being returned as the result of another api operation—for example, a service worker fetchevent.respondwith, or a simple windoworworkerglobalscope.fetch().
... 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.
RsaHashedKeyGenParams - Web APIs
this should be at least 2048: see for example see nist sp 800-131a rev.
... examples see the examples for subtlecrypto.generatekey().
RsaPssParams - Web APIs
for example, if you use sha-256 as the digest algorithm, this could be 32.
... examples see the examples for subtlecrypto.sign() and subtlecrypto.verify().
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 - ...
... intellifont intellifont - example myglyph.format = "truedoc-pfr"; specifications specification status comment scalable vector graphics (svg) 1.1 (second edition)the definition of 'format' in that specification.
SVGLength - Web APIs
WebAPISVGLength
ants svg_lengthtype_unknown = 0 svg_lengthtype_number = 1 svg_lengthtype_percentage = 2 svg_lengthtype_ems = 3 svg_lengthtype_exs = 4 svg_lengthtype_px = 5 svg_lengthtype_cm = 6 svg_lengthtype_mm = 7 svg_lengthtype_in = 8 svg_lengthtype_pt = 9 svg_lengthtype_pc = 10 normative document svg 1.1 (2nd edition) example <svg height="200" onload="start();" version="1.1" width="200" xmlns="http://www.w3.org/2000/svg"> <script type="text/javascript"><![cdata[ function start() { var rect = document.getelementbyid("myrect"); var val = rect.x.baseval; // read x in pixel and cm units console.log("value: " + val.value + ", valueinspecifiedunits: " + val.unittype + ": " + val.valueinspecifiedunit...
...for example, if the original value were "0.5cm" and the method was invoked to convert to millimeters, then the unittype would be changed to svg_lengthtype_mm, valueinspecifiedunits would be changed to the numeric value 5 and valueasstring would be changed to "5mm".
SVGSVGElement - Web APIs
if getcurrenttime() is called before the document timeline has begun (for example, by script running in a <script> element before the document's svgload event is dispatched), then 0 is returned.
...if setcurrenttime() is called before the document timeline has begun (for example, by script running in a <script> element before the document's svgload event is dispatched), then the value of seconds in the last invocation of the method gives the time that the document will seek to once the document timeline has begun.
SVGTransformList - Web APIs
example using multiple svgtransform objects in this example we create a function that will apply three different transformations to the svg element that has been clicked on.
... <svg id="my-svg" viewbox="0 0 300 280" xmlns="http://www.w3.org/2000/svg" version="1.1"> <desc>example showing how to transform svg elements that using svgtransform objects</desc> <script type="application/ecmascript"> <![cdata[ function transformme(evt) { // svg root element to access the createsvgtransform() function var svgroot = evt.target.parentnode; // svgtransformlist of the element that has been clicked on var tfmlist = evt.target.transform.baseval; // create a seperate transform object for each tr...
SVGUseElement - Web APIs
if the element does not have a shadow tree (for example, because its uri is invalid or because it has been disabled by conditional processing), then getting this attribute returns null.
...if the element does not have a shadow tree (for example, because its uri is invalid or because it has been disabled by conditional processing), then getting this attribute returns null.
Screen.lockOrientation() - Web APIs
for example, if the panel resolution is 1280*800, default will make it landscape, if the resolution is 800*1280, default will make it to portrait.
... 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.bufferSize - Web APIs
example 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.
... note: for a full working example, see our script-processor-node github repo (also view the source code.) var myscript = document.queryselector('script'); var mypre = document.queryselector('pre'); var playbutton = document.queryselector('button'); // create audiocontext and buffer source var audioctx = new audiocontext(); source = audioctx.createbuffersource(); // create a scriptprocessornode with a buffersize of 4096 and a single input and output channel var scriptnode = aud...
ScriptProcessorNode.onaudioprocess - Web APIs
} example 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.
... note: for a full working example, see our script-processor-node github repo (also view the source code.) var myscript = document.queryselector('script'); var mypre = document.queryselector('pre'); var playbutton = document.queryselector('button'); // create audiocontext and buffer source var audioctx = new audiocontext(); source = audioctx.createbuffersource(); // create a scriptprocessornode with a buffersize of 4096 and a single input and output channel var scriptnode...
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.
... note: for a full working example, see our script-processor-node github repo (also view the source code.) var myscript = document.queryselector('script'); var mypre = document.queryselector('pre'); var playbutton = document.queryselector('button'); // create audiocontext and buffer source var audioctx = new audiocontext(); source = audioctx.createbuffersource(); // create a scriptprocessornode with a buffersize of 4096 and a single input and output channel var scriptnode = aud...
Selection.containsNode() - Web APIs
example check for selection this snippet checks whether anything inside the body element is selected.
... console.log(window.getselection().containsnode(document.body, true)); find the hidden word in this example, a message appears when you select the secret word.
ServiceWorker.onstatechange - Web APIs
} ) examples this code snippet is from the service worker registration-events sample (live demo).
...for example: navigator.serviceworker.register(..).then(function(swr) { swr.installing.state == "installing" swr.installing.onstatechange = function() { swr.installing == null; // at this point, swr.waiting or swr.active might be true.
ServiceWorkerContainer.startMessages() - Web APIs
it's possible to start dispatching these messages earlier by calling serviceworkercontainer.startmessages(), for example if you've invoked a message handler using eventtarget.addeventlistener() before the page has finished loading, but want to start processing the messages right away.
... examples if('serviceworker' in navigator) { navigator.serviceworker .register('/sw.js') .then(function() { console.log('service worker registered'); }); } // ...
ServiceWorkerGlobalScope.onpush - Web APIs
}) example the following example takes data from a pushevent and displays it on all of the service worker's clients.
..."something has happened"; var message = data.message || "here's something you might want to check out."; var icon = "images/new-notification.png"; var notification = new notification(title, { body: message, tag: 'simple-push-demo-notification', icon: icon }); notification.addeventlistener('click', function() { if (clients.openwindow) { clients.openwindow('https://example.blog.com/2015/03/04/something-new.html'); } }); }); specifications specification status comment push apithe definition of 'onpush' in that specification.
ServiceWorkerGlobalScope.onpushsubscriptionchange - Web APIs
this might happen if, for example, the push service sets an expiration time a subscription.
...}) example self.addeventlistener('pushsubscriptionchange', function() { // do something, usually resubscribe to push and // send the new subscription details back to the // server via xhr or fetch }); specifications specification status comment push apithe definition of 'onpushsubscriptionchange' in that specification.
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.
ServiceWorkerGlobalScope.skipWaiting() - Web APIs
example while self.skipwaiting() can be called at any point during the service worker's execution, it will only have an effect if there's a newly installed service worker that might otherwise remain in the waiting state.
... the following example causes a newly installed service worker to progress into the activating state, regardless of whether there is already an active service worker.
ServiceWorkerRegistration.index - Web APIs
syntax var a contentindex object = serviceworkerregistration.index; value a contentindex object examples you can access the property from either your main script or the registered service worker.
... here is an example from the main script: // reference registration const registration = await navigator.serviceworker.ready; // feature detection if ('index' in registration) { // content index api functionality const contentindex = registration.index; } from the service worker: // service worker script const contentindex = self.registration.index; specifications specification status comment unknownthe definition of 'index' in that specification.
ServiceWorkerRegistration.pushManager - Web APIs
examples this.onpush = function(event) { console.log(event.data); // from here we can write the data to indexeddb, send it to any open // windows, display a notification, etc.
...ker.js').then( function(serviceworkerregistration) { serviceworkerregistration.pushmanager.subscribe().then( function(pushsubscription) { console.log(pushsubscription.subscriptionid); console.log(pushsubscription.endpoint); // the push subscription details needed by the application // server are now available, and can be sent to it using, // for example, an xmlhttprequest.
ShadowRoot.mode - Web APIs
WebAPIShadowRootmode
when the mode of a shadow root is "closed", the shadow root’s implementation internals are inaccessible and unchangeable from javascript—in the same way the implementation internals of, for example, the <video> element are inaccessible and unchangeable from javascript.
... 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!
SharedWorker.port - Web APIs
WebAPISharedWorkerport
example the following code snippet shows creation of a sharedworker object using the sharedworker() constructor.
... multiple scripts can then access the worker through a messageport object accessed using the sharedworker.port property — the port is started using its start() method: var myworker = new sharedworker('worker.js'); myworker.port.start(); for a full example, see our basic shared worker example (run shared worker.) specifications specification status comment html living standardthe definition of 'abstractworker.onerror' in that specification.
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.
... self.onconnect = function(e) { var port = e.ports[0]; port.onmessage = function(e) { var workerresult = 'result: ' + (e.data[0] * e.data[1]); port.postmessage(workerresult); } port.start(); } for a complete running example, see our basic shared worker example (run shared worker.) addeventlistener equivalent you could also set up an event handler using the addeventlistener() method: self.addeventlistener('connect', function(e) { var port = e.ports[0]; port.onmessage = function(e) { var workerresult = 'result: ' + (e.data[0] * e.data[1]); port.postmessage(workerresult); } }); specifications ...
SharedWorkerGlobalScope.onconnect - Web APIs
}; 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.
... onconnect = function(e) { var port = e.ports[0]; port.onmessage = function(e) { var workerresult = 'result: ' + (e.data[0] * e.data[1]); port.postmessage(workerresult); } port.start(); } for a complete running example, see our basic shared worker example (run shared worker.) note: the data property of the event object used to be null in firefox.
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.
...here is one such example: <my-paragraph> <span slot="my-text">let's have some different text!</span> </my-paragraph> in our javascript file we get a reference to the <span> shown above, then log a reference to the original <slot> element the <span> was inserted in.
SourceBuffer.abort() - Web APIs
example the spec description of abort() is somewhat confusing — consider for example step 1 of reset parser state.
...for example, consider this code: sourcebuffer.addeventlistener('updateend', function (_) { ...
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.
... this example was written by nick desaulniers and can be viewed live here (you can also download the source for further investigation.) var video = document.queryselector('video'); var asseturl = 'frag_bunny.mp4'; // need to be specific for blink regarding codecs // ./mp4info frag_bunny.mp4 | grep codec var mimecodec = 'video/mp4; codecs="avc1.42e01e, mp4a.40.2"'; if ('mediasource' in window && mediasource.istypesupported(mimecodec)) { var mediasource = new mediasource(); //console.log(mediasource.readystate); // closed video.src = url.createobjecturl(mediasource); mediasource.addeventlistener('sourceopen', sourceopen); } else { console.error('unsupported mime type or codec: ', mimecodec); } function sourceopen (_) { //console.log(this.readystate); // open var mediasource = this...
SourceBufferList - Web APIs
[]) or functions such as foreach() for example.
...[].) examples tbd.
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 ...
...| teal | thistle | tomato | turquoise | violet | white | yellow ;' var recognition = new speechrecognition(); var speechrecognitionlist = new speechgrammarlist(); speechrecognitionlist.addfromstring(grammar, 1); recognition.grammars = speechrecognitionlist; speechrecognitionlist.addfromuri('http://www.example.com/grammar.txt'); // adds a second grammar to the list.
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); } ...
SpeechSynthesisUtterance.rate - Web APIs
other values act as a percentage relative to this, so for example 2 is twice as fast, 0.5 is half as fast, etc.
... examples var synth = window.speechsynthesis; var inputform = document.queryselector('form'); var inputtxt = document.queryselector('input'); var voiceselect = document.queryselector('select'); var voices = synth.getvoices(); ...
Storage.clear() - Web APIs
WebAPIStorageclear
examples the following function creates three data entries in local storage, and then deletes them by using clear().
... function populatestorage() { localstorage.setitem('bgcolor', 'red'); localstorage.setitem('font', 'helvetica'); localstorage.setitem('image', 'migato.png'); localstorage.clear(); } note: for a real world example, see our web storage demo.
Storage.getItem() - Web APIs
WebAPIStoragegetItem
example the following function retrieves three data items from local storage, then uses them to set custom styles on a page.
...timage = localstorage.getitem('image'); document.getelementbyid('bgcolor').value = currentcolor; document.getelementbyid('font').value = currentfont; document.getelementbyid('image').value = currentimage; htmlelem.style.backgroundcolor = '#' + currentcolor; pelem.style.fontfamily = currentfont; imgelem.setattribute('src', currentimage); } note: to see this used within a real world example, see our web storage demo.
Storage.key() - Web APIs
WebAPIStoragekey
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: ...
...for a real world example, see our web storage demo.
Storage.removeItem() - Web APIs
example the following function creates three data items inside local storage, then removes the image data item.
... function populatestorage() { sessionstorage.setitem('bgcolor', 'red'); sessionstorage.setitem('font', 'helvetica'); sessionstorage.setitem('image', 'mycat.png'); sessionstorage.removeitem('image'); } note: to see this used within a real world example, see our web storage demo.
Storage.setItem() - Web APIs
WebAPIStoragesetItem
example the following function creates three data items inside local storage.
... function populatestorage() { localstorage.setitem('bgcolor', 'red'); localstorage.setitem('font', 'helvetica'); localstorage.setitem('image', 'mycat.png'); } note: to see this used within a real world example, see our web storage demo.
Using the Storage Access API - Web APIs
accessing a user's cookies in an embedded cross-origin iframe in this example we show how an embedded cross-origin <iframe> can access a user’s cookies under a storage access policy that blocks third-party cookies.
...}); note that access requests are automatically denied unless the embedded content is currently processing a user gesture such as a tap or click — so this code needs to be run inside some kind of user gesture-based event handler, for example: btn.addeventlistener('click', () => { // run code here }); ...
Using writable streams - Web APIs
introducing an example in our dom-examples/streams repo you’ll find a simple writer example (see it live also).
... the constructor call in our example looks like this: const decoder = new textdecoder("utf-8"); const queuingstrategy = new countqueuingstrategy({ highwatermark: 1 }); let result = ""; const writablestream = new writablestream({ // implement the sink write(chunk) { return new promise((resolve, reject) => { var buffer = new arraybuffer(2); var view = new uint16array(buffer); view[0] = chunk; var decod...
StylePropertyMapReadOnly.get() - Web APIs
examples let's get just a few properties and values.
... let's start by creating a link inside a paragraph in our html, and adding a definition list which we will populate with javascript: <p> <a href="https://example.com">link</a> </p> <dl id="regurgitation"></dl> we add a bit of css, including a custom property and an inhertable property: p { font-weight: bold; } a { --colour: red; color: var(--colour); } we use the element's computedstylemap() to return a stylepropertymapreadonly object.
SubmitEvent() - Web APIs
examples this code snippet locates a form in the current document, and then an html <button> within the form with the class submit on it.
... const form = document.queryselector("form"); const formtrigger = form.queryselector("button.submit"); const submitevent = new submitevent("submit", { submitter: formtrigger }); form.dispatchevent(submitevent); this is a somewhat contrived example, as you can do nearly all of this much more easily, but this gives you deep control over the process that can be useful.
SubtleCrypto.digest() - Web APIs
examples basic example this example encodes a message, then calculates its sha-256 digest and logs the digest length: const text = 'an obscure body in the s-k system, your majesty.
...this example calculates a digest, then converts the arraybuffer to a hex string: const text = 'an obscure body in the s-k system, your majesty.
Text.isElementContentWhitespace - Web APIs
putting any property that represents the textual content of the text node into test() should do the same work just like the three example above.
... syntax b = textnode.iselementcontentwhitespace; example in the example below, we create a node with mixed display and whitespace characters and the attribute is false.
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.
...y([-16, -96, -82, -73]); let u16arr = new uint16array([41200, 47022]); let i16arr = new int16array([-24336, -18514]); let i32arr = new int32array([-1213292304]); console.log(utf8decoder.decode(u8arr)); console.log(utf8decoder.decode(i8arr)); console.log(utf8decoder.decode(u16arr)); console.log(utf8decoder.decode(i16arr)); console.log(utf8decoder.decode(i32arr)); handling non-utf8 text in this example, we decode the russian text "Привет, мир!", which means "hello, world." in our textdecoder() constructor, we specify the windows-1251 character encoding, which is appropriate for cyrillic script.
TextEncoder.prototype.encodeInto() - Web APIs
for example, if your wasm allocator is known to use power-of-two buckets, rounduptobucketsize() should return the argument if it is a power-of-two or the next power-of-two otherwise.
...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...
TextTrack - Web APIs
WebAPITextTrack
for example, this can be "en-us" for united states english or "pt-br" for brazilian portuguese.
... example tbd specifications specification status comment html living standardthe definition of 'texttrack' in that specification.
Touch.clientX - Web APIs
WebAPITouchclientX
example this example illustrates using the touch object's touch.clientx and touch.clienty properties.
... in this example, we assume the user initiates a touch on an element with an id of source, moves within the element or out of the element and then releases contact with the surface.
Touch.clientY - Web APIs
WebAPITouchclientY
example this example illustrates using the touch object's touch.clientx and touch.clienty properties.
... in this example, we assume the user initiates a touch on an element with an id of source, moves within the element or out of the element and then releases contact with the surface.
Touch.radiusX - Web APIs
WebAPITouchradiusX
this may be a relatively large ellipse representing the contact between a fingertip and the screen or a small area representing the tip of a stylus, for example.
... example this example illustrates using the touch interface's touch.radiusx, touch.radiusx and touch.rotationangle properties.
Touch.radiusY - Web APIs
WebAPITouchradiusY
this may be a large ellipse representing the contact between a fingertip and the screen or a small one representing the tip of a stylus, for example.
... example the touch.radiusx example includes an example of this property's usage.
Touch.rotationAngle - Web APIs
this may be a relatively large ellipse representing the contact between a fingertip and the screen or a small area representing the tip of a stylus, for example.
... example the touch.radiusx example includes an example of this property's usage.
TouchList - Web APIs
WebAPITouchList
for example, if the user has three fingers on the touch surface (such as a screen or trackpad), the corresponding touchlist object would have one touch object for each finger, for a total of three entries.
... example see the example on the main touch events article.
Multi-touch interaction - Web APIs
example this example demonstrates using the touchstart, touchmove, touchcancel, and touchend) touch events for the following gestures: single touch, two (simultaneous) touches, more than two simultaneous touches, 1-finger swipe, and 2-finger move/pinch/swipe.
...it also calls preventdefault() to keep the browser from applying further event handling (for example, mouse event emulation).
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.
UIEvent.isChar - Web APIs
WebAPIUIEventisChar
some keystroke combinations may raise events but not produce any character (example: ctrl-alt-?).
... example in this snippet, which is part of an event handler, the event is checked to see if it generates a character; if it does, the value of uievent.which is appended to a string which buffers the typed characters.
sourceCapabilities - Web APIs
for example, when a user lifts their finger off of a touchscreen, several uievents may be generated including touchend, mousedown, click, and focus.
...for example, many user agents allow a window to be resized with a mouse or a keyboard, but this detail is not exposed to the web platform in any way, and so the sourcecapabilities of a resize event will typically be null.
URL() - Web APIs
WebAPIURLURL
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); // => 'http...
... // => 'https://developer.mozilla.org/docs' new url('/docs', ''); // raises a typeerror exception as '' is not a valid url new url('/docs'); // raises a typeerror exception as '/docs' is not a valid url new url('http://www.example.com', ); // => 'http://www.example.com/' new url('http://www.example.com', b); // => 'http://www.example.com/' new url("//foo.com", "https://example.com") // => 'https://foo.com' (see relative urls) specification specification status comment urlthe definition of 'url.url()' in that specification.
URLSearchParams() - Web APIs
examples the following example shows how to create a urlsearchparams object from a url string.
... // retrieve params via url.search, passed into ctor var url = new url('https://example.com?foo=1&bar=2'); var params = new urlsearchparams(url.search); // pass in a string literal var params2 = new urlsearchparams("foo=1&bar=2"); var params2a = new urlsearchparams("?foo=1&bar=2"); // pass in a sequence of pairs var params3 = new urlsearchparams([["foo", "1"], ["bar", "2"]]); // pass in a record var params4 = new urlsearchparams({"foo": "1", "bar": "2"}); specifications specification status comment urlthe definition of 'urlsearchparams()' in that specification.
URLSearchParams.append() - Web APIs
as shown in the example below, if the same key is appended multiple times it will appear in the parameter string multiple times for each value.
... 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.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.
... params.append('foo', 4); console.log(params.tostring()); //prints 'foo=1&bar=2&foo=4' // note: params can also be directly created let url = new url('https://example.com?foo=1&bar=2'); let params = url.searchparams; // or even simpler let params = new urlsearchparams('foo=1&bar=2'); specifications specification status comment urlthe definition of 'tostring() (see "stringifier")' in that specification.
USB.requestDevice() - Web APIs
WebAPIUSBrequestDevice
example the following example looks for one of two usb devices.
...for example, if only a usb device with product id 0xa800 is found, then only one device will be listed by the user agent.
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.
... for example, a usb serial device must provide bulk input and output endpoints but their endpoint numbers will depend on what other interfaces the device provides.
User Timing API - Web APIs
for more details and example code regarding these two performance event types and the methods, see using the user timing api.
...the method takes one argument, the name of the mark (for example performance.mark("mark-1")).
validityState.badInput - Web APIs
for example, if you have a number input element whose content is a string.
... example <input type="number" id="age"> var input = document.getelementbyid("age"); if (input.validity.badinput) { console.log("bad input detected…"); } else { console.log("content of input ok."); } specifications specification status comment html living standardthe definition of 'validitystate.badinput' in that specification.
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 ...
...for example, if the number input value is not a floating point number, the badinput is true.
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.
...for example: window.navigator.vibrate([200, 100, 200]); this vibrates the device for 200 ms, then pauses for 100 ms before vibrating the device again for another 200 ms.
VideoTrack.label - Web APIs
WebAPIVideoTracklabel
for example, a track whose kind is "sign" might have a label such as "a sign-language interpretation.".
... example this example returns an array of track kinds and labels for potential use in a user interface to select video tracks for a specified media element.
VideoTrackList: change event - Web APIs
the change event is fired when a video track is made active or inactive, for example by changing the track's selected property.
... 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 = document.queryselector('video'); videoelement.videotracks.onchange = (event) => { console.log(`'${event.type}' event fired`);...
VideoTrackList.onchange - Web APIs
example this snippet establishes a handler for the change event that looks at each of the tracks in the list, calling a function to update the state of a user interface control that indicates the current state of the track.
... var tracklist = document.queryselector("video").videotracks; tracklist.onchange = function(event) { tracklist.foreach(function(track) { updatetrackselectedbutton(track.id, track.selected); }); }; the updatetrackselectedbutton(), in this example, should be a function that finds a user interface control using the track's id (perhaps the app uses the track id as the control element's id) and the track's selected flag to determine which state the control should be in now.
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.
... var bottombar = document.getelementbyid('bottombar'); var viewport = window.visualviewport; function resizehandler() { if (viewport.scale > 1.3) bottombar.style.display = "none"; else bottombar.style.display = "block"; } window.visualviewport.addeventlistener('resize', resizehandler); simulating position: device-fixed this example, also taken from the visual viewport readme, shows how to use this api to simulate position: device-fixed, which fixes elements to the visual viewport.
WEBGL_compressed_texture_astc.getSupportedProfiles() - Web APIs
low dynamic ranges are for example jpeg format images which won't exceed 255:1, or crt monitors which won't exceed 100:1.
... 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_draw_buffers - Web APIs
the webgl_draw_buffers extension is part of the webgl api and enables a fragment shader to write to several textures, which is useful for deferred shading, for example.
... 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_w...
WaveShaperNode.curve - Web APIs
example the following example shows basic usage of an audiocontext to create a wave shaper node.
... for applied examples/information, check out our voice-change-o-matic demo (see app.js for relevant code).
WaveShaperNode.oversample - Web APIs
example the following example shows basic usage of an audiocontext to create a wave shaper node.
... for applied examples/information, check out our voice-change-o-matic demo (see app.js for relevant code).
WaveShaperNode - Web APIs
example the following example shows basic usage of an audiocontext to create a wave shaper node.
... for applied examples/information, check out our voice-change-o-matic demo (see app.js for relevant code).
WebGLContextEvent.statusMessage - Web APIs
examples the statusmessage property can contain a platform dependent string with details of an event.
... this can occur, for example, if the webglcontextcreationerror event is fired.
WebGLProgram - Web APIs
\n\n' + info; } see webglshader for information on creating the vertexshader and fragmentshader in the above example.
... 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.
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.
... \n\n' + info; } see webglshader for information on creating the vertexshader and fragmentshader in the above example.
WebGLRenderingContext.enableVertexAttribArray() - Web APIs
example this code — a snippet taken from the full example a basic 2d webgl animation example — shows the use of enablevertexarray() to activate the attribute that will be used by the webgl layer to pass individual vertexes from the vertex buffer into the vertex shader function.
...gl.bindbuffer(gl.array_buffer, vertexbuffer); avertexposition = gl.getattriblocation(shaderprogram, "avertexposition"); gl.enablevertexattribarray(avertexposition); gl.vertexattribpointer(avertexposition, vertexnumcomponents, gl.float, false, 0, 0); gl.drawarrays(gl.triangles, 0, vertexcount); this code snippet is taken from the function animatescene() in "a basic 2d webgl animation example." see that article for the full sample and to see the resulting animation in action.
WebGLRenderingContext.getUniformLocation() - Web APIs
example in this example, taken from the animatescene() method in the article a basic 2d webgl animation example, obtains the locations of three uniforms from the shading program, then sets the value of each of the three uniforms.
...gfactor"); uglobalcolor = gl.getuniformlocation(shaderprogram, "uglobalcolor"); urotationvector = gl.getuniformlocation(shaderprogram, "urotationvector") gl.uniform2fv(uscalingfactor, currentscale); gl.uniform2fv(urotationvector, currentrotation); gl.uniform4fv(uglobalcolor, [0.1, 0.7, 0.2, 1.0]); this code snippet is taken from the function animatescene() in "a basic 2d webgl animation example." see that article for the full sample and to see the resulting animation in action.
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 definit...
WebGLRenderingContext.uniform[1234][fi][v]() - Web APIs
a sequence of floating point numbers (for example a float32array or an array of numbers) for floating point vector methods (methods with "fv").
... examples gl.uniform1f(u_alpha, 0.8); specifications specification status comment webgl 1.0the definition of 'uniform' in that specification.
WebGLRenderingContext.vertexAttrib[1234]f[v]() - Web APIs
for example, if you have a shader which has a color vertex attribute, but you want to draw everything in a single color, you can use vertexattrib to achieve that without creating a buffer filled with only one value or having to create a separate shader which uses a uniform for the color.
... 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 matrix3...
Canvas size and WebGL - Web APIs
« previousnext » this webgl example explores the effect of setting (or not setting) the canvas size to its element size in css pixels, as it appears in the browser window.
..." + "your browser or device may not support webgl."; return; } gl.viewport(0, 0, gl.drawingbufferwidth, gl.drawingbufferheight); gl.enable(gl.scissor_test); gl.scissor(30, 10, 60, 60); gl.clearcolor(1.0, 1.0, 0.0, 1.0); gl.clear(gl.color_buffer_bit); }); }, false); the source code of this example is also available on github.
Clearing with colors - Web APIs
« previousnext » an example showing how to clear a webgl rendering context to a solid color.
... gl.clear(gl.color_buffer_bit); }, false); the source code of this example is also available on github.
Hello vertex attributes - Web APIs
« previousnext » this webgl example demonstrates how to combine shader programming and user interaction by sending user input to the shader using vertex attributes.
...webgl"); if (!gl) { var paragraph = document.queryselector("p"); paragraph.innerhtml = "failed to get webgl context." + "your browser or device may not support webgl."; return null; } gl.viewport(0, 0, gl.drawingbufferwidth, gl.drawingbufferheight); gl.clearcolor(0.0, 0.0, 0.0, 1.0); gl.clear(gl.color_buffer_bit); return gl; } })(); the source code of this example is also available on github.
Simple color animation - Web APIs
color animation with clear this example provides a simple illustration of color animation with webgl, as well as user interaction.
... function getrandomcolor() { return [math.random(), math.random(), math.random()]; } }, false); the source code of this example is also available on github.
Textures from code - Web APIs
« previousnext » this webgl example provides a simple demonstration of procedural texturing with fragment shaders.
...webgl"); if (!gl) { var paragraph = document.queryselector("p"); paragraph.innerhtml = "failed to get webgl context." + "your browser or device may not support webgl."; return null; } gl.viewport(0, 0, gl.drawingbufferwidth, gl.drawingbufferheight); gl.clearcolor(0.0, 0.0, 0.0, 1.0); gl.clear(gl.color_buffer_bit); return gl; } })(); the source code of this example is also available on github.
Animating objects with WebGL - Web APIs
« previousnext » in this example, we'll actually rotate our square plane.
... this example uses the glmatrix library to perform its matrix and vertex math.
Establishing a connection: The WebRTC perfect negotiation pattern - Web APIs
the perfect negotiation pattern is an example of the ways in which negotiation have improved since the early days of webrtc.
... implementing perfect negotiation let's take a look at an example that implements the perfect negotiation pattern.
Taking still photos with WebRTC - Web APIs
this will happen for example if there's no compatible camera connected, or the user denied access.
... you can play with this effect using, for example, the firefox developer tools' style editor; see edit css filters for details on how to do so.
Improving compatibility using WebRTC adapter.js - Web APIs
for example, on firefox versions older than 38, the adapter adds the rtcpeerconnection.urls property; firefox doesn't natively support this property until firefox 38, while on chrome, the adapter adds support for the promise based api is added if it's not present.
... these are just a couple of examples; there are of course other adjustments made for you by the shim.
WebRTC Statistics API - Web APIs
in this example, a new rtcpeerconnection is created, and then setinterval() is used to set the function getconnectionstats() to be called every second.
... this example specifically looks for the report whose type is inbound-rtp and whose kind is video.
WebSocket: error event - Web APIs
the error event is fired when a connection with a websocket has been closed due to an error (some data couldn't be sent for example).
... 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.
Writing a WebSocket server in C# - Web APIs
let us extend our example.
... example in c#: byte[] decoded = new byte[3]; byte[] encoded = new byte[3] {112, 16, 109}; byte[] mask = new byte[4] {61, 84, 35, 6}; for (int i = 0; i < encoded.length; i++) { decoded[i] = (byte)(encoded[i] ^ mask[i % 4]); } put together wsserver.cs // // csc wsserver.cs // wsserver.exe using system; using system.net; using system.net.sockets; using system.text; using system.text.regularexpress...
Using bounded reference spaces - Web APIs
<<<--- example --->>> creating a bounded reference space before creating a project that relies on bounded reference spaces, it's important to keep in mind that not all xr devices are capable of creating them.
... 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.
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.
... the alternative is to use an interleaved buffer format: lrlrlrlrlrlrlrlrlrlrlrlrlrlrlrlr (for a buffer of 16 frames) this format is very common for storing and playing back audio without much processing, for example a decoded mp3 stream.
Using IIR filters - Web APIs
this article looks at how to implement one, and use it in a simple example.
... demo our simple example for this guide provides a play/pause button that starts and pauses audio play, and a toggle that turns an iir filter on and off, altering the tone of the sound.
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.
...- service): rp: { name: "acme" }, // user: user: { id: new uint8array(16), name: "john.p.smith@example.com", displayname: "john p.
Window: animationcancel event - Web APIs
examples this code adds a listener to the animationcancel event.
... window.addeventlistener('animationcancel', () => { console.log('animation canceled'); }); the same, but using the onanimationcancel property instead of addeventlistener(): window.onanimationcancel = () => { console.log('animation canceled'); }; 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 = ...
...() => { iterationcount++; console.log(`animation iteration count: ${iterationcount}`); }; see a live example of this event.
Window.captureEvents() - Web APIs
example <!doctype html> <html lang="en"> <head> <!-- ...
... when you call the captureevents() method on the window, events of the type you specify (for example, event.click) no longer pass through to "lower" objects in the hierarchy.
Window.closed - Web APIs
WebAPIWindowclosed
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.
... refreshing a previously opened popup in this example the function refreshpopupwindow() calls the reload() method of the popup's location object to refresh its data.
Window.console - Web APIs
WebAPIWindowconsole
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: error event - Web APIs
the error event is fired on a window object when a resource failed to load or couldn't be used — for example if a script has an execution error.
... 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; display: flex; align-items: center; justify-content: center; } .event-log { grid-area: log; } .event-log-contents { resize: non...
Window.getDefaultComputedStyle() - Web APIs
example simple example var elem1 = document.getelementbyid("elemid"); var style = window.getdefaultcomputedstyle(elem1); longer example <style> #elem-container { position: absolute; left: 100px; top: 200px; height: 100px; } </style> <div id="elem-container">dummy</div> <div id="output"></div> <script> var elem = document.getelementbyid("elem-container"); var thecssprop = win...
...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...
... in the above example, selobj.tostring() is automatically called when it is passed to window.alert().
Window.history - Web APIs
WebAPIWindowhistory
see manipulating the browser history for examples and details.
... example history.back(); // equivalent to clicking back button history.go(-1); // equivalent to history.back(); notes for top-level pages you can see the list of pages in the session history, accessible via the history object, in the browser's dropdowns next to the back and forward buttons.
Window.innerHeight - Web APIs
example assuming a frameset var intframeheight = window.innerheight; // or var intframeheight = self.innerheight; // will return the height of the frame viewport within the frameset var intframesetheight = parent.innerheight; // will return the height of the viewport of the closest frameset var intouterframesetheight = top.innerheight; // will return the height of the viewport of the outermost frame...
... graphical example the following figure shows the difference between outerheight and innerheight.
Window: message event - Web APIs
the message event is fired on a window object when the window receives a message, for example from a call to window.postmessage() from another browsing context.
... 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.addeventlistener('message', (event) => { console.log(`received message: ${event.data}`); }); alternatively the listener could use the onmessage event handler property: w...
Window.pageYOffset - Web APIs
example var contenthtml = ` <h2 id="introduction">introduction</h2> <p>lorem ipsum dolor sit amet, consectetur adipiscing elit.
...integer euismod lectus a ipsum pellentesque lacinia.</p> `; document.getelementbyid("frame").contentdocument .body.innerhtml = contenthtml; in this example, an <iframe> is created and filled with content, then a specific element within the document is scrolled into view in the frame.
Window: pagehide event - Web APIs
for example, when the user clicks the browser's back button, the current page receives a pagehide event before the previous page is shown.
... 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.personalbar - Web APIs
syntax objref =window.personalbar example fixme: https://bugzilla.mozilla.org/show_bug.cgi?id=790023 the following complete html example shows the way that the visible property of the various "bar" objects is used, and also the change to the privileges necessary to write to the visible property of any of the bars on an existing window.
... <!doctype html> <html> <head> <title>various dom tests</title> <script> // changing bar states on the existing window netscape.security.privilegemanager.enableprivilege("universalbrowserwrite"); window.personalbar.visible = !window.personalbar.visible; </script> </head> <body> <p>various dom tests</p> </body> </html> notes when you load the example page above, the browser displays the following dialog: to toggle the visibility of these bars, you must either sign your scripts or enable the appropriate privileges, as in the example above.
Window.prompt() - Web APIs
WebAPIWindowprompt
example let sign = prompt("what's your sign?"); if (sign.tolowercase() == "scorpio") { alert("wow!
...for example, if their answer should be a number, you should cast the value to number.
Window.requestAnimationFrame() - Web APIs
check the example below for a way to do this.
... example in this example, an element is animated for 2 seconds (2000 milliseconds).
Window: resize event - Web APIs
examples window size logger the following example reports the window size each time it is resized.
... bear in mind that since the example is running in an <iframe>, you'll need to actually get the <iframe> to resize before you see an effect.
Window.screenLeft - Web APIs
WebAPIWindowscreenLeft
examples in our screenleft-screentop example, you'll see a canvas onto which has been drawn a circle.
... in this example we are using screenleft/screentop plus window.requestanimationframe() to constantly redraw the circle in the same physical position on the screen, even if the window position is moved.
Window.screenTop - Web APIs
WebAPIWindowscreenTop
examples in our screenleft-screentop example, you'll see a canvas onto which has been drawn a circle.
... in this example we are using screenleft/screentop plus window.requestanimationframe() to constantly redraw the circle in the same physical position on the screen, even if the window position is moved.
Window.screenX - Web APIs
WebAPIWindowscreenX
examples in our screenleft-screentop (source code) example, you'll see a canvas onto which has been drawn a circle.
... in this example we are using window.screenleft/window.screentop plus window.requestanimationframe() to constantly redraw the circle in the same physical position on the screen, even if the window position is moved.
Window.screenY - Web APIs
WebAPIWindowscreenY
examples in our screenleft-screentop example, you'll see a canvas onto which has been drawn a circle.
... in this example we are using window.screenleft/window.screentop plus window.requestanimationframe() to constantly redraw the circle in the same physical position on the screen, even if the window position is moved.
Window.scrollX - Web APIs
WebAPIWindowscrollX
example this example checks the current horizontal scroll position of the document.
...a fully compatible example: var x = (window.pagexoffset !== undefined) ?
Window.scrollY - Web APIs
WebAPIWindowscrollY
example // make sure and go down to the second page if (window.scrolly) { window.scroll(0, 0); // reset the scroll position to the top left of the document.
...a fully compatible example: var supportpageoffset = window.pagexoffset !== undefined; var iscss1compat = ((document.compatmode || "") === "css1compat"); var x = supportpageoffset ?
Window.sizeToContent() - Web APIs
in order for it to work, the dom content should be loaded when this function is called—for example, once the domcontentloaded event has been thrown.
... syntax window.sizetocontent() example window.sizetocontent(); specification this feature is not part of any specification.
Window.statusbar - Web APIs
WebAPIWindowstatusbar
syntax objref = window.statusbar example the following complete html example shows a way that the visible property of the various "bar" objects is used, and also the change to the privileges necessary to write to the visible property of any of the bars on an existing window.
... <!doctype html> <html lang="en"> <head> <meta charset="utf-8" /> <title>various dom tests</title> <script> // changing bar states on the existing window netscape.security.privilegemanager.enableprivilege("universalbrowserwrite"); window.statusbar.visible=!window.statusbar.visible; </script> </head> <body> <p>various dom tests</p> </body> </html> notes when you load the example page above, the browser displays the following dialog: to toggle the visibility of these bars, you must either sign your scripts or enable the appropriate privileges, as in the example above.
Window.toolbar - Web APIs
WebAPIWindowtoolbar
syntax objref = window.toolbar example the following complete html example shows way that the visible property of the various "bar" objects is used, and also the change to the privileges necessary to write to the visible property of any of the bars on an existing window.
... <!doctype html> <html> <head> <title>various dom tests</title> <script> // changing bar states on the existing window netscape.security.privilegemanager.enableprivilege("universalbrowserwrite"); window.toolbar.visible=!window.toolbar.visible; </script> </head> <body> <p>various dom tests</p> </body> </html> notes when you load the example page above, the browser displays the following dialog: to toggle the visibility of these bars, you must either sign your scripts or enable the appropriate privileges, as in the example above.
Window: unload event - Web APIs
event) pagehide the document is in the following state: all the resources still exist (img, iframe etc.) nothing is visible anymore to the end user ui interactions are ineffective (window.open, alert, confirm, etc.) an error won't stop the unloading workflow please note that the unload event also follows the document tree: parent frame unload will happen before child frame unload (see example below).
... 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> below, the content of child-frame.html: <!doctype html> <html> <head> <title>child frame</title> <script> window.addeventlistener('beforeunload', function(event) { console.log('i am the 2nd one.'); }); window.addeventlistener('unload', function(event) { console.log('i am the 4th and last one…'); }); </script> </head> <body> �...
Window.window - Web APIs
WebAPIWindowwindow
another reason, is that without this property you wouldn't be able to write, for example, "window.open('http://google.com/')".
...for example, if we refer to "this.window.location.href", a javascript module could define a property called "window" inside of a class it defined (since no global "window" variable exists for it by default) which could be created after passing in a window object to the module class' constructor.
WindowEventHandlers.onhashchange - Web APIs
examples using an event handler this example uses an event handler (window.onhashchange) to check the new hash value whenever it changes.
... function locationhashchanged() { if (location.hash === '#cool-feature') { console.log("you're visiting a cool feature!"); } } window.onhashchange = locationhashchanged; using an event listener this example uses an event listener to log a notification whenever the hash has changed.
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", "?p...
...age=3"); history.back(); // alerts "location: http://example.com/example.html?page=1, state: {"page":1}" history.back(); // alerts "location: http://example.com/example.html, state: null history.go(2); // alerts "location: http://example.com/example.html?page=3, state: {"page":3} note that even though the original history entry (for http://example.com/example.html) has no state object associated with it, a popstate event is still fired, when we activate that entry after the second call to history.back().
WindowOrWorkerGlobalScope.atob() - Web APIs
for example, you can encode, transmit, and decode control characters such as ascii values 0 through 31.
... example const encodeddata = window.btoa('hello, world'); // encode a string const decodeddata = window.atob(encodeddata); // decode the string polyfill you can use a polifill from https://github.com/maxart2501/base64-js/blob/master/base64.js for browsers that don't support it.
WindowOrWorkerGlobalScope.fetch() - Web APIs
examples in our fetch request example (see fetch request live) we create a new request object using the relevant constructor, then fetch it using a fetch() call.
...status: ${response.status}`); } return response.blob(); }) .then(function(response) { let objecturl = url.createobjecturl(response); myimage.src = objecturl; }); in the fetch with init then request example (see fetch request init live), we do the same thing except that we pass in an init object when we invoke fetch(): const myimage = document.queryselector('img'); let myheaders = new headers(); myheaders.append('content-type', 'image/jpeg'); const myinit = { method: 'get', headers: myheaders, mode: 'cors', cache: 'default' }; let myrequest = new request('flowers.jpg'); fetch(myrequest,...
Worker.onmessage - Web APIs
WebAPIWorkeronmessage
} example the following code snippet shows creation of a worker object using the worker() constructor.
... for a full example, see ourbasic dedicated worker example (run dedicated worker).
Worker - Web APIs
WebAPIWorker
example the following code snippet creates a worker object using the worker() constructor, then uses the worker object: var myworker = new worker('/worker.js'); var first = document.queryselector('input#number1'); var second = document.queryselector('input#number2'); first.onchange = function() { myworker.postmessage([first.value, second.value]); console.log('message posted to worker'); } for a f...
...ull example, see ourbasic dedicated worker example (run dedicated worker).
WorkerGlobalScope.console - Web APIs
example this property allows you to have access to a browser console for debugging purposes, inside a worker.
... so for example you could call console.log('test'); inside a worker (which would basically be the equivalent of self.console.log('test');, as these are being called on the worker scope, which can be referenced with workerglobalscope.self), to return a test message out to the browser console.
WorkerGlobalScope.dump() - Web APIs
example to write an output from your worker to your computer's terminal, you first have to run an instance of firefox started from your command line/terminal.
... for example, on mac os x you'd run it using something like this (assuming you are inside the applications folder): ./firefox.app/contents/macos/firefox-bin -profile /tmp -no-remote now go into about:config and enable the browser.dom.window.dump.enabled pref.
WritableStream.getWriter() - Web APIs
examples the following example illustrates several features of this interface.
...ild(listitem); result += decoded; resolve(); }); }, close() { var listitem = document.createelement('li'); listitem.textcontent = "[message received] " + result; list.appendchild(listitem); }, abort(err) { console.log("sink error:", err); } }, queuingstrategy); sendmessage("hello, world.", writablestream); you can find the full code in our simple writer example.
WritableStreamDefaultWriter.WritableStreamDefaultWriter() - Web APIs
examples the following example shows the creation of a writablestream with a custom sink and an api-supplied queuing strategy.
...ild(listitem); result += decoded; resolve(); }); }, close() { var listitem = document.createelement('li'); listitem.textcontent = "[message received] " + result; list.appendchild(listitem); }, abort(err) { console.log("sink error:", err); } }, queuingstrategy); sendmessage("hello, world.", writablestream); you can find the full code in our simple writer example.
WritableStreamDefaultWriter.close() - Web APIs
examples the following example shows the creation of a writablestream with a custom sink and an api-supplied queuing strategy.
...ild(listitem); result += decoded; resolve(); }); }, close() { var listitem = document.createelement('li'); listitem.textcontent = "[message received] " + result; list.appendchild(listitem); }, abort(err) { console.log("sink error:", err); } }, queuingstrategy); sendmessage("hello, world.", writablestream); you can find the full code in our simple writer example.
WritableStreamDefaultWriter.write() - Web APIs
examples the following example shows the creation of a writablestream with a custom sink and an api-supplied queuing strategy.
...ild(listitem); result += decoded; resolve(); }); }, close() { var listitem = document.createelement('li'); listitem.textcontent = "[message received] " + result; list.appendchild(listitem); }, abort(err) { console.log("sink error:", err); } }, queuingstrategy); sendmessage("hello, world.", writablestream); you can find the full code in our simple writer example.
WritableStreamDefaultWriter - Web APIs
examples the following example shows the creation of a writablestream with a custom sink and an api-supplied queuing strategy.
... result += decoded; resolve(); }); }, close() { var listitem = document.createelement('li'); listitem.textcontent = "[message received] " + result; list.appendchild(listitem); }, abort(err) { console.log("sink error:", err); } }, queuingstrategy); sendmessage("hello, world.", writablestream); you can find the full code in our simple writer example.
How to check the security state of an XMLHTTPRequest over SSL - Web APIs
here is a an example javascript function that prints the security details of an xmlhttprequest sent over ssl.
... by setting the mozbackgroundrequest property of the request object and modifying the example appropriately, you can create your own alert dialog to handle ssl exceptions in your firefox extension or xulrunner application.
XMLHttpRequest: abort event - Web APIs
the abort event is fired when a request has been aborted, for example because the program called xmlhttprequest.abort().
... 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; margin: .5rem; } js const xhrbuttonsuccess = document.queryselector('.xhr.success'); const xhrbuttonerror = document.qu...
XMLHttpRequest.overrideMimeType() - Web APIs
this may be used, for example, to force a stream to be treated and parsed as "text/xml", even if the server does not report it as such.
... example this example specifies a mime type of "text/plain", overriding the server's stated type for the data being received.
XMLHttpRequest.send() - Web APIs
example: get var xhr = new xmlhttprequest(); xhr.open('get', '/server', true); xhr.onload = function () { // request finished.
...}; xhr.send(null); // xhr.send('string'); // xhr.send(new blob()); // xhr.send(new int8array()); // xhr.send(document); example: post var xhr = new xmlhttprequest(); xhr.open("post", '/server', true); //send the proper header information along with the request xhr.setrequestheader("content-type", "application/x-www-form-urlencoded"); xhr.onreadystatechange = function() { // call a function when the state changes.
XMLHttpRequest - Web APIs
unlike xmlhttprequest.status, this includes the entire text of the response message ("200 ok", for example).
... events abort fired when a request has been aborted, for example because the program called xmlhttprequest.abort().
XMLSerializer - Web APIs
examples serializing xml into a string the first, basic, example just serializes an entire document into a string containing xml.
... inserting nodes into a dom based on xml this example uses the element.insertadjacenthtml() method to insert a new dom node into the body of the document, based on xml created by serializing an element object.
XPathEvaluator.createExpression() - Web APIs
example the following example shows the use of the evaluate() method.
... html <div>xpath example</div> <div>number of &lt;div&gt;s: <output></output></div> javascript var xpath = "//div"; var evaluator = new xpathevaluator(); var expression = evaluator.createexpression("//div"); var result = expression.evaluate(document, xpathresult.ordered_node_snapshot_type); document.queryselector("output").textcontent = result.snapshotlength; result specifications specification status comment document object model (dom) level 3 xpath specificationthe definition of 'xpathevaluator.createexpression()' in that specification.
XPathEvaluator.evaluate() - Web APIs
example the following example shows the use of the evaluate() method.
... html <div>xpath example</div> <div>number of &lt;div&gt;s: <output></output></div> javascript var evaluator = new xpathevaluator(); var result = evaluator.evaluate("//div", document, null, xpathresult.ordered_node_snapshot_type); document.queryselector("output").textcontent = result.snapshotlength; result specifications specification status comment document object model (dom) level 3 xpath specificationthe definition of 'xpathevaluator.evaluate()' in that specification.
XPathEvaluator - Web APIs
example the following example shows the use of the xpathevaluator interface.
... html <div>xpath example</div> <div>number of &lt;div&gt;s: <output></output></div> javascript var xpath = "//div"; var evaluator = new xpathevaluator(); var expression = evaluator.createexpression("//div"); var result = expression.evaluate(document, xpathresult.ordered_node_snapshot_type); document.queryselector("output").textcontent = result.snapshotlength; result specifications specification status comment document object model (dom) level 3 xpath specificationthe definition of 'xpathevaluator' in that specification.
XPathExpression.evaluate() - Web APIs
example the following example shows the use of the evaluate() method.
... html <div>xpath example</div> <div>number of &lt;div&gt;s: <output></output></div> javascript var xpath = "//div"; var evaluator = new xpathevaluator(); var expression = evaluator.createexpression("//div"); var result = expression.evaluate(document, xpathresult.ordered_node_snapshot_type); document.queryselector("output").textcontent = result.snapshotlength; result specifications specification status comment document object model (dom) level 3 xpath specificationthe definition of 'xpathexpression.evaluate()' in that specification.
XPathExpression - Web APIs
example the following example shows the use of the xpathexpression interface.
... html <div>xpath example</div> <div>number of &lt;div&gt;s: <output></output></div> javascript var xpath = "//div"; var evaluator = new xpathevaluator(); var expression = evaluator.createexpression(xpath); var result = expression.evaluate(document, xpathresult.ordered_node_snapshot_type); document.queryselector("output").textcontent = result.snapshotlength; result specifications specification status comment document object model (dom) level 3 xpath specificationthe definition of 'xpathexpression' in that specification.
XPathResult.booleanValue - Web APIs
example the following example shows the use of the booleanvalue property.
... html <div>xpath example</div> <p>text is 'xpath example': <output></output></p> javascript var xpath = "//div/text() = 'xpath example'"; var result = document.evaluate(xpath, document, null, xpathresult.boolean_type, null); document.queryselector("output").textcontent = result.booleanvalue; result specifications specification status comment document object model (dom) level 3 xpath specificationthe definition of 'xpathresult.booleanvalue' in that specification.
XPathResult.invalidIteratorState - Web APIs
example the following example shows the use of the invaliditeratorstate property.
... html <div>xpath example</div> <p>iterator state: <output></output></p> javascript var xpath = "//div"; var result = document.evaluate(xpath, document, null, xpathresult.any_type, null); // invalidates the iterator state document.queryselector("div").remove(); document.queryselector("output").textcontent = result.invaliditeratorstate ?
XPathResult.iterateNext() - Web APIs
example the following example shows the use of the iteratenext() method.
... html <div>xpath example</div> <div>tag names of the matched nodes: <output></output></div> javascript var xpath = "//div"; var result = document.evaluate(xpath, document, null, xpathresult.any_type, null); var node = null; var tagnames = []; while(node = result.iteratenext()) { tagnames.push(node.localname); } document.queryselector("output").textcontent = tagnames.join(", "); result specifications specification status comment document object model (dom) level 3 xpath specificationthe definition of 'xpathresult.iteratenext()' in that specification.
XPathResult.numberValue - Web APIs
example the following example shows the use of the numbervalue property.
... html <div>xpath example</div> <div>number of &lt;div&gt;s: <output></output></div> javascript var xpath = "count(//div)"; var result = document.evaluate(xpath, document, null, xpathresult.number_type, null); document.queryselector("output").textcontent = result.numbervalue; result specifications specification status comment document object model (dom) level 3 xpath specificationthe definition of 'xpathresult.numbervalue' in that specification.
XPathResult.singleNodeValue - Web APIs
example the following example shows the use of the singlenodevalue property.
... html <div>xpath example</div> <div>tag name of the element having the text content 'xpath example': <output></output></div> javascript var xpath = "//*[text()='xpath example']"; var result = document.evaluate(xpath, document, null, xpathresult.first_ordered_node_type, null); document.queryselector("output").textcontent = result.singlenodevalue.localname; result specifications specification status comment document object model (dom) level 3 xpath specificationthe definition of 'xpathresult.singlenodevalue' in that specification.
XPathResult.snapshotItem() - Web APIs
example the following example shows the use of the snapshotitem() method.
... html <div>xpath example</div> <div>tag names of the matched nodes: <output></output></div> javascript var xpath = "//div"; var result = document.evaluate(xpath, document, null, xpathresult.ordered_node_snapshot_type, null); var node = null; var tagnames = []; for(var i = 0; i < result.snapshotlength; i++) { var node = result.snapshotitem(i); tagnames.push(node.localname); } document.queryselector("output").textcontent = tagnames.join(", "); result specifications specification status comment document object model (dom) level 3 xpath specificationthe definition of 'xpathresult.snapshotitem()' in that specification.
XPathResult.snapshotLength - Web APIs
example the following example shows the use of the snapshotlength property.
... html <div>xpath example</div> <div>number of matched nodes: <output></output></div> javascript var xpath = "//div"; var result = document.evaluate(xpath, document, null, xpathresult.ordered_node_snapshot_type, null); document.queryselector("output").textcontent = result.snapshotlength; result specifications specification status comment document object model (dom) level 3 xpath specificationthe definition of 'xpathresult.snapshotlength' in that specification.
XPathResult.stringValue - Web APIs
example the following example shows the use of the stringvalue property.
... html <div>xpath example</div> <div>text content of the &lt;div&gt; above: <output></output></div> javascript var xpath = "//div/text()"; var result = document.evaluate(xpath, document, null, xpathresult.string_type, null); document.queryselector("output").textcontent = result.stringvalue; result specifications specification status comment document object model (dom) level 3 xpath specificationthe definition of 'xpathresult.stringvalue' in that specification.
XPathResult - Web APIs
this is useful for example, in an xpath expression using the count() function.
...this is useful for example, in an xpath expression using the not() function.
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.
... viewerpose = xrframe.getviewerpose(xrreferencespace); if (viewerpose) { /* render the pose's views */ } to see a complete example, take a look at movement, orientation, and motion.
XRInputSource.handedness - Web APIs
this may indicate, for example, an input source which isn't hand-held, such as controls built into a headset or an input device attached to the head or body.
... 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 - Web APIs
in addition to these methods, you may use array notation to access items in the list by index for example, the snippet of code below calls a function handleinput(), passing into it the first item in the input source list, if the list isn't empty.
... 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.
XRPermissionDescriptor - Web APIs
examples the example below demonstrates performing the permission request for an application that requires the local-floor reference space in an immersive-vr environment.
... if the permissions api isn't available at all, this example simply assumes that webxr will report an appropriate error if permission isn't available, and tries to start up the webxr session using the same setupxr() function called by the granted case.
XRPose - Web APIs
WebAPIXRPose
see the article movement, orientation, and motion for further details and an example with thorough explanations of what's going on.
... example <<<--- todo: needs example --->>> specifications specification status comment webxr device apithe definition of 'xrpose' in that specification.
XRReferenceSpace - Web APIs
this can happen, for example, after the user recalibrates their xr device, or if the device automatically adjusts its origin after losing and regaining tracking.
...*/ }); the other situation in which you may need to acquire a new reference space is if you need to move the origin to a new position; this is commonly done, for example, when your project allows the user to move through the environment using input devices such as the keyboard, mouse, touchpad, or game controls that are not connected through the xr device.
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.onselectend - Web APIs
for example, this might include releasing a button or joystick.
...} example xrsession.onselectend = function(event) { console.log("the user has completed a primary action.") } specifications specification status comment webxr device apithe definition of 'xrsession.onselectend' in that specification.
XRSession.onselectstart - Web APIs
for example, this might include pressing a button or moving a joystick.
...} example xrsession.onselectstart = function(event) { console.log("the user has started a primary action, but might not have completed it.") } specifications specification status comment webxr device apithe definition of 'xrsession.onselectstart' in that specification.
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.
...that's because (in this example, at least) the handler for the squeeze event has already dropped the object into its new location and then cleared the value of heldobject to indicate that the user is no longer holding anything.
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.
XRSessionEvent - Web APIs
these events occur, for example, when the session ends or the visibility of its context changes.
... examples this example creates a listiener that watches for the visibility state of the session to change.
XRSystem: requestSession() - Web APIs
examples creating an immersive vr session the following example calls requestsession() requesting an "immersive-vr" session.
... xrsession.requestanimationframe(onxranimationframe); }).catch(function(error) { // "immersive-vr" sessions are not supported console.warn("'immersive-vr' isn't supported, or an error occurred activating vr!"); }); verifying webxr support and using a button to start vr mode the following example shows how to use both issessionsupported() and requestsession().
XRWebGLLayer.framebufferHeight - Web APIs
each of the framebuffer's attachments (pixel, depth, color, and/or stencil buffers, for example) are all this many pixels tall.
... examples this snippet simply fetches the framebuffer's width and height for later use.
XRWebGLLayer.framebufferWidth - Web APIs
each of the framebuffer's attachments (pixel, depth, color, and/or stencil buffers, for example) are all this many pixels wide.
... examples this snippet simply fetches the framebuffer's width and height for later use.
XRWebGLLayer - Web APIs
in this way, for example, the rendering of the left eye's point of view and of the right eye's point of view are each placed into the correct parts of the framebuffer.
... examples binding the layer to a webgl context this snippet, taken from drawing a frame in movement, orientation, and motion: a webxr example, shows how the xrwebgllayer is obtained from the xrsession object's rendering state and is then bound as the current rendering webgl framebuffer by calling the webgl bindframebuffer() function.
XRWebGLLayerInit.framebufferScaleFactor - Web APIs
for example, a value of 1.0 indicates that the frame buffer should be the same resolution as the actual display, while a value of 0.5 indicates that the frame buffer should be half the resolution of the display.
... example in this example, a new xrwebgllayer is created for a webxr session, xrsession, with a frame buffer whose resolution is half that of the default display resolution of the xr device.
ARIA live regions - Accessibility
<div id="clock" role="timer" aria-live="polite" aria-atomic="true"></div> note: as observed, setting/updating the innerhtml again would cause the whole text to be read again, whether or not you set aria-atomic="true", so the above clock example does not work as expected.
... a working example of a simple year control for better understanding: <div id="date-input"> <label>year: <input type="text" id="year" value="1990" onblur="change(event)"/> </label> </div> <div id="date-output" aria-live="polite"> the set year is: <span id="year-output">1990</span> </div> function change(event) { var yearout = document.getelementbyid("year-output"); switch (event.target.id) { case "year": yearout.innerhtml = event.target.value; break; default: return; } }; without aria-atomic="true" the screenreader announces only the changed value of year.
Using the 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-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" /> </f...
...orm> 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 link role - Accessibility
examples this example shows how to implement a fake link using a <span> element.
... html <h1>role="link" example</h1> <span data-href="https://mozilla.org" tabindex="0" id="link1" role="link" class="link"> fake accessible link created using a span </span> <p><a href="https://mozilla.org" target="_blank">actual real link</a></p> css span[role="link"] { color: blue; text-decoration: underline; cursor: pointer; } span[role="link"]:focus { outline: 1px dotted black; } javascript const spanelem...
Using the presentation role - Accessibility
for example, a table used for layout purposes could have the presentation role applied to the table element to remove any semantic meaning from the table element and any of its table related children elements, such as table headers and table data elements.
... 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 product combinations additional resources using aria - 2.9 use of role=presentation or ro...
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: alert role - Accessibility
for example, if a page loads with multiple visible alerts scattered throughout, none would be read because they are not dynamically triggered.
... examples the most basic way to trigger an alert is by adding role="alert" to an element that has display: none; by default.
ARIA: cell role - Accessibility
for example, a cell in the first row of the first header would likely have aria-rowindex="1" set, and cells in row 47 would have aria-rowindex="47", if aria-rowindex were needed due to not all rows being in the dom.
... 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" ari...
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 o...
...for example, a declaration of role="complementary" with an of aria-label="sidebar" may be announced redundantly as, "complementary sidebar".
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.
...for example, a declaration of role="contentinfo" with an of aria-label="footer" may be announced redundantly as, "contentinfo footer".
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 ...
...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="lastna...
...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.
ARIA: heading role - Accessibility
examples the following shows a typical page structure.
... best practices the best way to use this role is to not use it at all, and instead use the native heading tags <h1> through <h6> as shown in the example above.
Architecture - Accessibility
example take the following html code: <div>hello<a href="http://www.mozilla.org/access">my link<img src="image.gif">is cool</a>bye</div> both the <a> and <img> are hyperlinks also, both the <div> and <a> are hypertexts so the <a> is both a hypertext and a hyperlink, because it contains text and is contained within text.
...examples of objects not embedded in text are the child options in list boxes and combo boxes.
Accessibility Information for Web Authors - Accessibility
two panes are added at the bottom of the view source code window: the left pane contains the errors and warnings (with their correspondent line number) and the right pane identifies the checkpoint along with an example and a clickable link to the reference/guideline.
...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).
Mobile accessibility checklist - Accessibility
wcag 2.1: orientation examples of when an orientation is esssential is a piano application or a bank cheque.
...for example, playing a game or a piano application.
Custom properties (--*): CSS variables - CSS: Cascading Style Sheets
WebCSS--*
property names that are prefixed with --, like --example-name, represent custom properties that contain a value that can be used in other declarations using the var() function.
... formal syntax <declaration-value> example html <p id="firstparagraph">this paragraph should have a blue background and yellow text.</p> <p id="secondparagraph">this paragraph should have a yellow background and blue text.</p> <div id="container"> <p id="thirdparagraph">this paragraph should have a green background and yellow text.</p> </div> css :root { --first-color: #488cff; --second-color: #ffff8c; } #firstparagraph { bac...
-moz-image-rect - CSS: Cascading Style Sheets
description this property allows you to, for example, use different parts of one larger image as backgrounds in different parts of your content.
... examples this example loads an image and uses it in four segments to draw the firefox logo in four <div> blocks.
-webkit-mask-repeat-x - CSS: Cascading Style Sheets
example: an image with an original width of 260px, repeated three times, might stretch until each repetition is 300px wide, and then another image will be added.
... 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'), url('mask2.png'); -webkit-mask-repeat-x: repeat, space; } each image is matched with the corresponding repeat style, from first specified to last.
-webkit-mask-repeat-y - CSS: Cascading Style Sheets
example: an image with an original height of 260px, repeated three times, might stretch until each repetition is 300px high, and then another image will be added.
... 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'), url('mask2.png'); -webkit-mask-repeat-y: repeat, space; } each image is matched with the corresponding repeat style, from first sp...
::-webkit-inner-spin-button - CSS: Cascading Style Sheets
syntax ::-webkit-inner-spin-button examples these examples work only in browsers based on webkit and blink.
... changing the cursor in the spin controls in this example, the css cursor is changed to pointer whenever the cursor is positioned over the inner part of the input's spin controls.
::-webkit-outer-spin-button - CSS: Cascading Style Sheets
syntax ::-webkit-outer-spin-button examples these examples only works on browsers based on webkit or blink.
... hiding the spinner this example uses input::-webkit-outer-spin-button to find <input> elements' spinner widgets and set their -webkit-appearance to none, thus hiding them.
::-webkit-progress-inner-element - CSS: Cascading Style Sheets
syntax ::-webkit-progress-inner-element examples these examples work only on blink and webkit.
... adding a black border around the progress bar in this example, a 2px black border is added around the progress bar.
::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.
... you can see this example in action or view or remix the code on glitch.
::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>.
...em vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat.</p> css p { width: 500px; line-height: 1.5; } h2 + p::first-letter { color: white; background-color: black; border-radius: 2px; box-shadow: 3px 3px 0 red; font-size: 250%; padding: 6px 3px; margin-right: 6px; float: left; } result effect on special punctuation and non-latin characters this example illustrates the effect of ::first-letter on special punctuation and non-latin characters.
::placeholder - CSS: Cascading Style Sheets
<label for="user-email">your email address</label> <span id="user-email-hint" class="input-hint">example: jane@sample.com</span> <input id="user-email" aria-describedby="user-email-hint" name="email" type="email"> placeholders in form fields are harmful — nielsen norman group windows high contrast mode placeholder text will appear with the same styling as user-entered text content when rendered in windows high contrast mode.
... 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 '::p...
:checked - CSS: Cascading Style Sheets
WebCSS:checked
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="op...
...:checked + label { color: red; } /* radio element, when checked */ input[type="radio"]:checked { box-shadow: 0 0 0 3px orange; } /* checkbox element, when checked */ input[type="checkbox"]:checked { box-shadow: 0 0 0 3px hotpink; } /* option elements, when selected */ option:checked { box-shadow: 0 0 0 3px lime; color: red; } result toggling elements with a hidden checkbox this example utilizes the :checked pseudo-class to let the user toggle content based on the state of a checkbox, all without using javascript.
:defined - CSS: Cascading Style Sheets
WebCSS:defined
/* 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).
...ple-custom', class extends htmlelement { constructor() { super(); let divelem = document.createelement('div'); divelem.textcontent = this.getattribute('text'); let shadowroot = this.attachshadow({mode: 'open'}) .appendchild(divelem); } }) then insert a copy of this element into the document, along with a standard <p>: <simple-custom text="custom element example text"></simple-custom> <p>standard paragraph example text</p> in the css we first include the following rules: // give the two elements distinctive backgrounds p { background: yellow; } simple-custom { background: cyan; } // both the custom and the built-in element are given italic text :defined { font-style: italic; } then provide the following two rules to hide any instances of our ...
:focus-within - CSS: Cascading Style Sheets
(this includes descendants in shadow trees.) /* selects a <div> when one of its descendants is focused */ div:focus-within { background: cyan; } this selector is useful, to take a common example, for highlighting an entire <form> container when the user focuses on one of its <input> fields.
... syntax :focus-within examples in this example, the form will receive special coloring styles when either text input receives focus.
:host() - CSS: Cascading Style Sheets
WebCSS:host()
'='<attr-modifier> = i | s examples selectively styling shadow hosts the following snippets are taken from our host-selectors example (see it live also).
... in this example we have a simple custom element — <context-span> — that you can wrap around text: <h1>host selectors <a href="#"><context-span>example</context-span></a></h1> inside the element's constructor, we create style and span elements, fill the span with the content of the custom element, and fill the style element with some css rules: let style = document.createelement('style'); let span = document.createelement('span'); span.textcontent = this.textcontent; const shadowroot = this.attachshadow({mode: 'open'}); shadowroot.appendchild(style); shadowroot.appendchild(span); style.textcontent = 'span:hover { text-decoration: underline; }' + ':host-context(h1) { font-style: italic; }' + ':host-context(h1):after { content: " - no links in heade...
:host - CSS: Cascading Style Sheets
WebCSS:host
/* 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).
... in this example we have a simple custom element — <context-span> — that you can wrap around text: <h1>host selectors <a href="#"><context-span>example</context-span></a></h1> inside the element's constructor, we create style and span elements, fill the span with the content of the custom element, and fill the style element with some css rules: let style = document.createelement('style'); let span = document.createelement('span'); span.textcontent = this.textcontent; const shadowroot = this.attachshadow({mode: 'open'}); shadowroot.appendchild(style); shadowroot.appendchild(span); style.textcontent = 'span:hover { text-decoration: underline; }' + ':host-context(h1) { font-style: italic; }' + ':host-context(h1):after { content: " - no links in heade...
:left - CSS: Cascading Style Sheets
WebCSS:left
for example, if the first page has a major writing direction of left-to-right then it will be a :right page; if it has a major writing direction of right-to-left then it will be a :left page.
... 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.
:link - CSS: Cascading Style Sheets
WebCSS:link
syntax :link examples by default, most browsers apply a special color value to visited links.
... thus, the links in this example will probably have special font colors only before you visit them.
: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.
... html <input id="input1" placeholder="name, rank, and serial number"> <br><br> <input id="input2" placeholder="name, rank, and serial number"> css #input2:placeholder-shown { text-overflow: ellipsis; } result customized input field the following example highlights the branch and id code fields with a custom style.
: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.
... we do just this in the example below.
: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.
... we do just this in the example below.
:right - CSS: Cascading Style Sheets
WebCSS:right
for example, if the first page has a major writing direction of left-to-right then it will be a :right page; if it has a major writing direction of right-to-left then it will be a :left page.
... 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.
speak-as - CSS: Cascading Style Sheets
for example, an author can specify a counter symbol to be either spoken as its numerical value or just represented with an audio cue.
... 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 ...
font-family - CSS: Cascading Style Sheets
syntax /* <string> values */ font-family: "font family"; font-family: 'another font family'; /* <custom-ident> value */ font-family: examplefont; values <family-name> specifies the name of the font family.
... 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.
src - CSS: Cascading Style Sheets
WebCSS@font-facesrc
syntax /* <url> values */ src: url(https://somewebsite.com/path/to/font.woff); /* absolute url */ src: url(path/to/font.woff); /* relative url */ src: url(path/to/font.woff) format("woff"); /* explicit format */ src: url('path/to/font.woff'); /* quoted url */ src: url(path/to/svgfont.svg#example); /* fragment identifying font */ /* <font-face-name> values */ src: local(font); /* unquoted name */ src: local(some font); /* name containing space */ src: local("font"); /* quoted name */ /* multiple items */ src: local(font), url(path/to/font.svg) format("svg"), url(path/to/font.woff) format("woff"), url(path/to/font.otf) format("opentype"); values <url>...
...| 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.
-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.
... example: @media (-webkit-min-device-pixel-ratio: 2), /* webkit-based browsers */ (min--moz-device-pixel-ratio: 2), /* older firefox browsers (prior to firefox 16) */ (min-resolution: 2dppx), /* the standard way */ (min-resolution: 192dpi) /* dppx fallback */ note: see this csswg article for compatibility good practices regarding resolution and dppx.
-webkit-transition - CSS: Cascading Style Sheets
syntax @media (-webkit-transition) { /* css to use if transitions are supported */ } examples use @supports instead do not use the -webkit-transition media feature.
... instead, test for transition support using the css @supports at-rule, like this: @supports (transition: initial) { /* css to use if transitions are supported */ } obsolete example before this became obsolete, you could use -webkit-transition in your css like this: @media (-webkit-transition) { /* css to use if transitions are supported */ } specifications not part of any standard.
aspect-ratio - CSS: Cascading Style Sheets
examples the example below is contained in an <iframe>, which creates its own viewport.
...</div> css /* minimum aspect ratio */ @media (min-aspect-ratio: 8/5) { div { background: #9af; /* blue */ } } /* maximum aspect ratio */ @media (max-aspect-ratio: 3/2) { div { background: #9ff; /* cyan */ } } /* exact aspect ratio, put it at the bottom to avoid override*/ @media (aspect-ratio: 1/1) { div { background: #f9a; /* red */ } } _example used iframe and dataurl to enable this iframe could resize html <label id="wf" for="w">width:165</label> <input id="w" name="w" type="range" min="100" max="250" step="5" value="165"> <label id="hf" for="w">height:165</label> <input id="h" name="h" type="range" min="100" max="250" step="5" value="165"> <iframe id="outer" src="data:text/html,<style> @media (min-aspect-ratio: 8/5) { div { backgr...
color - CSS: Cascading Style Sheets
WebCSS@mediacolor
for example, if a display uses 5 bits for blue and red and 6 bits for green, then the device is considered to use 5 bits per color component.
... examples html <p>this text should be black on non-color devices, red on devices with a low number of colors, and greenish on devices with a high number of colors.</p> css p { color: black; } /* any color device */ @media (color) { p { color: red; } } /* any color device with at least 8 bits per color component */ @media (min-color: 8) { p { color: #24ba13; } } result specifications specification status comment media queries level 4the definition of 'color' in that specification.
grid - CSS: Cascading Style Sheets
WebCSS@mediagrid
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.
prefers-reduced-data - CSS: Cascading Style Sheets
examples note: no browser currently implements this feature so the following example will not work.
... in this example the montserrat-regular.woff2 font file will neither be preloaded nor downloaded if the user prefers reduced data, in this case the "system font stack" will serve as the fallback font: html <head> <link rel="preload" href="fonts/montserrat-regular.woff2" as="font" media="(prefers-reduced-data: no-preference)" crossorigin> <link rel="stylesheet" href="style.css"> </head> css @media (prefers-reduced-data: no-preference) { @font-face { font-family: montserrat; font-style: normal; font-weight: 400; font-display: swap; /* latin */ src: local('montserrat regular'), local('montserrat-regular'), url('fonts/montserrat-regular.woff2') format('woff2'); unicode-range: u+0000-00ff, u+0131, u+0152-0153, u+02bb-02bc, u+02c6, ...
prefers-reduced-motion - CSS: Cascading Style Sheets
important: an embedded example at the bottom of this page has a scaling movement that may be problematic for some readers.
... examples this example has a scaling animation by default.
prefers-reduced-transparency - CSS: Cascading Style Sheets
examples note: no browser currently implements this feature so the following example will not work.
... this example has an annoying transparency effect by default.
width - CSS: Cascading Style Sheets
WebCSS@viewportwidth
syntax /* an example with one viewport value: */ @viewport { width: 320px; } /* an example with two viewport values: */ @viewport { width: 320px, 120px; } values auto the used value is calculated from the other css descriptors' values.
...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.
Resizing background images with background-size - CSS: Cascading Style Sheets
try resizing the example below to see this in action.
...try resizing the example below to see this in action.
Introduction to formatting contexts - CSS: Cascading Style Sheets
bfc creation examples let's have a look at a couple of these in order to see the effect creating a new bfc.
... in the example below, we have a floated element inside a <div> with a border applied.
CSS Fonts - CSS: Cascading Style Sheets
WebCSSCSS Fonts
basic example the following example shows a simple use of basic font properties to style a paragraph of text.
...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.
Consistent list indentation - CSS: Cascading Style Sheets
for example, if you declare that lists have no left margin, they move over in internet explorer, but sit stubbornly in place in gecko-based browsers.this article will help you understand the problems that can occur and how to avoid them.
... gecko, on the other hand, sets a left padding of 40 pixels for the <ul> element, so given the exact same styles as were used to produce figure 5, loading the example into a gecko-based browser gives us figure 6.
Using z-index - CSS: Cascading Style Sheets
in the following example, the layers' stacking order is rearranged using z-index.
... source code for the example html <div id="abs1"> <b>div #1</b> <br />position: absolute; <br />z-index: 5; </div> <div id="rel1"> <b>div #2</b> <br />position: relative; <br />z-index: 3; </div> <div id="rel2"> <b>div #3</b> <br />position: relative; <br />z-index: 2; </div> <div id="abs2"> <b>div #4</b> <br />position: absolute; <br />z-index: 1; </div> <div id="sta1"> <b>div #5</b> <br />no positioning <br />z-index: 8; </div> css div { padding: 10px; opacity: 0.7; text-align: center; } b { font-family: sans-serif; } #abs1 { z-index: 5; position: absolute; width: 150px; height: 350px; top: 10px; left: 10px; border: 1px dashed #900; background-color: ...
Stacking with floated blocks - CSS: Cascading Style Sheets
floating blocks are placed between non-positioned blocks and positioned blocks: the background and borders of the root element descendant non-positioned blocks, in order of appearance in the html floating blocks descendant positioned elements, in order of appearance in the html actually, as you can see in the example below, the background and border of the non-positioned block (div #4) is completely unaffected by floating blocks, but the content is affected.
... source code for the example html <div id="abs1"> <b>div #1</b><br />position: absolute;</div> <div id="flo1"> <b>div #2</b><br />float: left;</div> <div id="flo2"> <b>div #3</b><br />float: right;</div> <br /> <div id="sta1"> <b>div #4</b><br />no positioning</div> <div id="abs2"> <b>div #5</b><br />position: absolute;</div> css div { padding: 10px; text-align: center; } b { font-family: sans-seri...
Stacking without the z-index property - CSS: Cascading Style Sheets
in the example below, elements #1 through #4 are positioned elements.
... source code for the example html <div id="abs1" class="absolute"> <b>div #1</b><br />position: absolute;</div> <div id="rel1" class="relative"> <b>div #2</b><br />position: relative;</div> <div id="rel2" class="relative"> <b>div #3</b><br />position: relative;</div> <div id="abs2" class="absolute"> <b>div #4</b><br />position: absolute;</div> <div id="sta1" class="static"> <b>div #5</b><br />position: static;</div> css b { font-family: sans-serif; } div { padding: 10px; border: 1px dashed; text-align: center; } .static { position: static; height: 80px; background-color: #ffc; border-color: #996; } .absolute { position: absolute; width: 150px...
Understanding CSS z-index - CSS: Cascading Style Sheets
this article will try to explain those rules, with some simplification and several examples.
... stacking context example 1: 2-level html hierarchy, z-index on the last level stacking context example 2: 2-level html hierarchy, z-index on all levels stacking context example 3: 3-level html hierarchy, z-index on the second level original document information author(s): paolo lombardi this article is the english translation of an article i wrote in italian for yappy.
List group with badges - CSS: Cascading Style Sheets
recipe download this example choices made flexbox makes this particular pattern straightforward and also makes it easy to make changes to the layout.
...in the live example, if you remove this property and you will see the badge move to the end of the text on items with text shorter than the one line.
Recipe: Media objects - CSS: Cascading Style Sheets
the recipe download this example choices made i have chosen to use grid layout for the media object as it allows me to control the layout in two dimensions when i need to.
... download this example once floated elements become grid items the float no longer applies so you don’t need to do anything special to clear the float.
Using Media Queries for Accessibility - CSS: Cascading Style Sheets
example this example has an annoying animation unless you turn on reduce motion in your accessibility preferences.
... example 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.
Privacy and the :visited selector - CSS: Cascading Style Sheets
if you use a sibling selector such as :visited + span, the adjacent element (span in this example) will be styled as if the link were unvisited.
... here is an example of how to use styles with the aforementioned restrictions: :link { outline: 1px dotted blue; background-color: white; /* the default value of background-color is `transparent`.
Pseudo-classes - CSS: Cascading Style Sheets
for example, :hover can be used to change a button's color when the user's pointer hovers over it.
... /* any button over which the user's pointer is hovering */ button:hover { color: blue; } pseudo-classes let you apply a style to an element not only in relation to the content of the document tree, but also in relation to external factors like the history of the navigator (:visited, for example), the status of its content (like :checked on certain form elements), or the position of the mouse (like :hover, which lets you know if the mouse is over an element or not).
Actual value - CSS: Cascading Style Sheets
for example, a user agent that can only render borders with a whole-number pixel width may round the thickness of the border to the nearest integer.
... next, the computed value is calculated according to the specification (for example, a span with position: absolute will have its computed display changed to block).
box-align - CSS: Cascading Style Sheets
WebCSSbox-align
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...
...ildren to the horizontal center of this box */ box-align: center; /* as specified */ -moz-box-align: center; /* mozilla */ -webkit-box-align: center; /* webkit */ /* pack children to the bottom of this box */ box-pack: end; /* as specified */ -moz-box-pack: end; /* mozilla */ -webkit-box-pack: end; /* webkit */ } div.example > p { /* make children narrower than their parent, so there is room for the box-align */ width: 200px; } </style> </head> <body> <div class="example"> <p>i will be second from the bottom of div.example, centered horizontally.</p> <p>i will be on the bottom of div.example, centered horizontally.</p> </div> </body> </html> specifications not part of any standard.
box-flex - CSS: Cascading Style Sheets
WebCSSbox-flex
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 b...
...lack; } div.example > p:nth-child(2) { -moz-box-flex: 0; /* mozilla */ -webkit-box-flex: 0; /* webkit */ border: 1px solid black; } </style> </head> <body> <div class="example"> <p>i will expand to fill extra space</p> <p>i will not expand</p> </div> </body> </html> specifications not part of any standard.
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.
... html <div class="example"> <p>i will be to the left of my sibling.</p> <p>i will be to the right of my sibling.</p> </div> css div.example { display: -moz-box; /* mozilla */ display: -webkit-box; /* webkit */ display: box; /* as specified */ /* children should be oriented vertically */ -moz-box-orient: horizontal; /* mozilla */ -webkit-box-orient: horizontal; /* webkit */ box-orient: horizontal; /* as specified */ } result specifications not part of any standard.
box-pack - CSS: Cascading Style Sheets
WebCSSbox-pack
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; /* ...
...mozilla */ -webkit-box-orient: vertical; /* webkit */ /* align children to the horizontal center of this box */ -moz-box-align: center; /* mozilla */ -webkit-box-align: center; /* webkit */ /* pack children to the bottom of this box */ -moz-box-pack: end; /* mozilla */ -webkit-box-pack: end; /* webkit */ } div.example p { /* make children narrower than their parent, so there is room for the box-align */ width: 200px; } <div class="example"> <p>i will be second from the bottom of div.example, centered horizontally.</p> <p>i will be on the bottom of div.example, centered horizontally.</p> </div> specifications not part of any standard.
counters() - CSS: Cascading Style Sheets
WebCSScounters
non-latin characters must be encoded using their unicode escape sequences: for example, \000a9 represents the copyright symbol.
...)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; } li { counter-increment: listcounter; } li::marker { content: counters(listcounter, '.', upper-roman) ') '; } li::before { content: counters(listcounter, ".") " == " counters(listcounter, ".", lower-roman) ; } resu...
<dimension> - CSS: Cascading Style Sheets
WebCSSdimension
the <dimension> css data type represents a <number> with a unit attached to it, for example 10px.
... 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: none html <p>visible text</p> <p class="secret">invisible text</p> css p.secret { display: none; } result display: contents in this example the outer <div> has a 2-pixel red border and a width of 300px.
<display-inside> - CSS: Cascading Style Sheets
this will result in expected behavior; for example if you specify an element to be display: grid, you would expect that the box created on the grid container would be a block level box.
... examples in this example the parent box has been given display: flow-root and so establishes a new bfc and contains the floated item.
<display-listitem> - CSS: Cascading Style Sheets
the list-item keyword causes the element to generate a ::marker pseudo-element with the content specified by its list-style properties (for example a bullet point) together with a principal box of the specified type for its own contents.
... 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
this will result in expected behavior; for example if you specify an element to be block, you would expect that the children of that element would participate in block and inline normal flow layout.
... 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
WebCSSenv
) 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.
...</p> p { width: 300px; border: 2px solid red; padding: env(safe-area-inset-top, 50px) env(safe-area-inset-right, 50px) env(safe-area-inset-bottom, 50px) env(safe-area-inset-left, 50px); } example values padding: env(safe-area-inset-bottom, 50px); /* zero for all rectangular user agents */ padding: env(safe-area-inset-bottom, 50px); /* 50px because ua properties are case sensitive */ padding: env(x, 50px 20px); /* as if padding: '50px 20px' were set because x is not a valid environment variable */ padding: env(x, 50px, 20px); /* ignored because '50px, 20px' is not a valid padding value an...
font-size-adjust - CSS: Cascading Style Sheets
for example, a style sheet that specifies: font-size: 14px; font-size-adjust: 0.5; ...
...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-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.
... html <div class="container"> <p class="condensed">an elephantine lizard</p> <p class="normal">an elephantine lizard</p> <p class="expanded">an elephantine lizard</p> </div> css /* this example uses the league mono variable font, developed by tyler finck (https://www.tylerfinck.com/) 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 { src: url('https://mdn.mozillademos.org/files/16014/leaguemonovariable.ttf'); font-family:'leaguemonovariable'; font-style: normal; font-stretch: 1% 500%; /* required by chrome */ } .container { border: 10px solid #f5f9fa; padding: 0 1rem; font: 1.5rem 'leaguemonovariable', sans-serif; } .condensed { font-stretch: 50%; } .normal { fo...
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.
... you can find a few free versions for testing purposes, for example from fontsgeek.com.
image-rendering - CSS: Cascading Style Sheets
for example, if the natural size of an image is 100×100px, but its actual dimensions are 200×200px (or 50×50px), then the image will be upscaled (or downscaled) using the algorithm specified by image-rendering.
... 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.
inherit - CSS: Cascading Style Sheets
WebCSSinherit
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.
... for example, if one of them were the child of a div matched by the rule ...
<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.
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-outset: 1rem; chromium-based browsers support an outdated version of this property — mask-box-image-outset — with a prefix: -webkit-mask-box-image-outset: 1rem; note: the mask-border page features a working example (using the out-of-date prefixed border mask properties supported in chromium), so you can get an idea of the effect.
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-repeat: round; chromium-based browsers support an outdated version of this property — mask-box-image-repeat — with a prefix: -webkit-mask-box-image-repeat: round; note: the mask-border page features a working example (using the out-of-date prefixed border mask properties supported in chromium), so you can get an idea of the effect.
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-slice: 30 fill; chromium-based browsers support an outdated version of this property — mask-box-image-slice — with a prefix: -webkit-mask-box-image-slice: 30 fill; note: the mask-border page features a working example (using the out-of-date prefixed border mask properties supported in chromium), so you can get an idea of the effect.
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-source: url(image.jpg); chromium-based browsers support an outdated version of this property — mask-box-image-source — with a prefix: -webkit-mask-box-image-source: url(image.jpg); note: the mask-border page features a working example (using the out-of-date prefixed border mask properties supported in chromium), so you can get an idea of the effect.
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-width: 30 fill; chromium-based browsers support an outdated version of this property — mask-box-image-width — with a prefix: -webkit-mask-box-image-width: 20px; note: the mask-border page features a working example (using the out-of-date prefixed border mask properties supported in chromium), so you can get an idea of the effect.
paint() - CSS: Cascading Style Sheets
WebCSSpaint
parameters optional additional parameters to pass to the paintworklet examples you can pass additional arguments via the css paint() function.
... in this example, we passed two arguments: whether the background-image on a group of list items is filled or just has a stroke outline, and the width of that outline: <ul> <li>item 1</li> <li>item 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 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); } ...
scroll-margin-block-end - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
scroll-margin-block-start - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
scroll-margin-block - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
scroll-margin-bottom - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
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.
...it would work just as well here to only set a scroll margin on that one edge, for example with scroll-margin-inline: 0 1rem, or scroll-margin-inline-end: 1rem.
scroll-margin-left - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
scroll-margin-right - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
scroll-margin-top - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
scroll-padding-block-end - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
scroll-padding-block-start - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
scroll-padding-block - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
scroll-padding-bottom - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
scroll-padding-inline-end - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
scroll-padding-inline-start - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
scroll-padding-inline - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
scroll-padding-left - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
scroll-padding-right - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
scroll-padding-top - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
scroll-padding - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
text-combine-upright - CSS: Cascading Style Sheets
] examples digits the digits value requires less markup than the all value when digits are being combined, but it is currently not very widely supported by browsers.
... html <p lang="ja" class="exampletext">平成20年4月16日に</p> css .exampletext { writing-mode: vertical-lr; text-combine-upright: digits 2; font: 36px serif; } results screenshotlive sample all the all value requires markup around every piece of horizontal text, but it is currently supported by more browsers than the digits value.
text-emphasis-position - CSS: Cascading Style Sheets
in japanese for example, the preferred position is over right.
... 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.
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> ...
...+++++*/ /* if i remove this rule the pen won't work properly on chrome for mac, ff, safari will still work properly on chrome for pc & opera*/ transform-box: fill-box; /*alternatively i can use transform-origin:15px 15px;*/ /*+++++++++++++++++++++++++++*/ animation: rotatebox 3s linear infinite; } @keyframes rotatebox { to { transform: rotate(360deg); } full credit for this example goes to pogany; see this codepen for a live version.
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 whi...
...for example, if you rotate before translating, the translation will be along the new axis of rotation!
translate() - CSS: Cascading Style Sheets
for example, translate(2) is equivalent to translate(2, 0).
... 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...
unicode-bidi - CSS: Cascading Style Sheets
for example, if a block of content contains both left-to-right and right-to-left text, the user-agent uses a complex unicode algorithm to decide how to display the text.
... 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.
will-change - CSS: Cascading Style Sheets
/* keyword values */ will-change: auto; will-change: scroll-position; will-change: contents; will-change: transform; /* example of <custom-ident> */ will-change: opacity; /* example of <custom-ident> */ will-change: left, top; /* example of two <animateable-feature> */ /* global values */ will-change: inherit; will-change: initial; will-change: unset; proper usage of this property can be a bit tricky: don't apply will-change to too many elements.
... .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.
Ajax - Developer guides
WebGuideAJAX
documentation getting started this article guides you through the ajax basics and gives you two simple hands-on examples to get you started.
... pure-ajax navigation example this article provides a working (minimalist) example of a pure-ajax website composed only of three pages.
Creating a cross-browser video player - Developer guides
working example our example video player displays a clip from an open source movie called tears of steel, and includes typical video controls.
... note: you can see the example running live, or check out the source code on github.
Mutation events - Developer guides
cross-browser support these events are not implemented consistently across different browsers, for example: ie prior to version 9 didn't support the mutation events at all and does not implement some of them correctly in version 9 (for example, domnodeinserted) webkit doesn't support domattrmodified (see webkit bug 8191 and the workaround) "mutation name events", i.e.
... 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 ...
Event developer guide - Developer guides
WebGuideEvents
the device on which the web browser is running can trigger events, for example due to a change in its position and orientation in the real world, as discussed partially by the page on orientation coordinate systems and the page on the use of 3d transforms.
... the window in which the browser is displayed can trigger events; for example, change size if the user maximizes the window or otherwise changes it.
Using HTML sections and outlines - Developer guides
for example, <div class="navigation"> does not suggest any meaning about its content to a browser; only a human reading the html source can divine the meaning of a class like navigation.
...a book, for example, may be divided up into sections with related articles.
Mobile-friendliness - Developer guides
a great example of this is alaska air’s website.
...for example, it is absolutely critical to keep in mind which browsers and devices you will target when picking a mobile strategy.
Parsing and serializing XML - Developer guides
parsing strings into dom trees this example converts an xml fragment in a string into a dom tree using a domparser: var smystring = '<a id="a"><b id="b">hey!</b></a>'; var oparser = new domparser(); var odom = oparser.parsefromstring(smystring, "application/xml"); // print the name of the root element or error message console.log(odom.documentelement.nodename == "parsererror" ?
...le parsing" : odom.documentelement.nodename); parsing url-addressable resources into dom trees using xmlhttprequest here is sample code that reads and parses a url-addressable xml file into a dom tree: var xhr = new xmlhttprequest(); xhr.onload = function() { dump(xhr.responsexml.documentelement.nodename); } xhr.onerror = function() { dump("error while getting xml."); } xhr.open("get", "example.xml"); xhr.responsetype = "document"; xhr.send(); the value returned in the xhr object's responsexml field is a document constructed by parsing the xml.
HTML attribute: crossorigin - HTML: Hypertext Markup Language
example: crossorigin with the script element you can use the following <script> element to tell a browser to execute the https://example.com/example-framework.js script without sending user-credentials.
... <script src="https://example.com/example-framework.js" crossorigin="anonymous"></script> example: webmanifest with credentials the use-credentials value must be used when fetching a manifest that requires credentials, even if the file is from the same origin.
HTML attribute: max - HTML: Hypertext Markup Language
WebHTMLAttributesmax
syntax syntax for max values by input type input type syntax example date yyyy-mm-dd <input type="date" max="2019-12-25" step="1"> month yyyy-mm <input type="month" max="2019-12" step="12"> week yyyy-w## <input type="week" max="2019-w23" step=""> time hh:mm <input type="time" max="17:00" step="900"> datetime-local yyyy-mm-ddthh:mm <input type="datetime-local" min="2019-12-25t23:59"> ...
... syntax for max values for other elements input type syntax example <progress> <number> <progress id="file" max="100" value="70"> 70% </progress> <meter> <number> <meter id="fuel" min="0" max="100" low="33" high="66" optimum="80" value="40"> at 40/100</meter> ...
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.c...
...choose the images you want to upload: </label> <input type="file" id="uploads" name="uploads" accept=".jpg, .jpeg, .png, .svg, .gif" multiple> </p> <p> <label for="text">pick a text file to upload: </label> <input type="file" id="text" name="text" accept=".txt"> </p> <p> <input type="submit" value="submit"> </p> </form> note the difference in appearance between the example with multiple set and the other file input without.
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-...
... the example below restricts the value to 4-8 characters and requires that it contain only lower-case letters.
HTML attribute: readonly - HTML: Hypertext Markup Language
example html <div class="group"> <input type="textbox" value="some value" readonly="readonly"/> <label>textbox</label> </div> <div class="group"> <input type="date" value="2020-01-01" readonly="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</legend> <p><label> <input type="radio" name="radio" value="regular"> regular </label></p> <p><label> <input type="radio" name="radio" value="readonly" readonly> readonly </label></p> <p><label>...
HTML attribute: step - HTML: Hypertext Markup Language
WebHTMLAttributesstep
default values for step input type value example date 1 (day) <input type="date" min="2019-12-25" step="1"> month 1 (month) <input type="month" min="2019-12" step="12"> week 1 (week) <input type="week" min="2019-w23" step="2"> time 60 (seconds) <input type="time" min="09:00" step="900"> datetime-local 1 (day) <input type="datetime-local" min="019-12-25t19:30" st...
...for example, if we have <input type="number" min="10" step="2"> any even integer, 10 or great, is valid.
DASH Adaptive Streaming for HTML 5 Video - HTML: Hypertext Markup Language
for example: the file in.video can be any container with at least one audio and one video stream that can be decoded by ffmpeg, create the audio using: ffmpeg -i in.video -vn -acodec libvorbis -ab 128k -dash 1 my_audio.webm create each video variant.
...the -adaptation_sets argument assigns them into adaptation sets; for example, this creates one set (0) that contains the streams 0, 1, 2 and 3 (the videos), and another set (1) that contains only stream 4, the audio stream.
<base>: The Document Base URL element - HTML: Hypertext Markup Language
WebHTMLElementbase
for example: given <base href="https://example.com"> ...and this link: <a href="#anchor">anker</a> ...the link points to https://example.com/#anchor.
...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.
<dialog>: The Dialog element - HTML: Hypertext Markup Language
WebHTMLElementdialog
for example, to dim unreachable content behind the modal dialog.
... examples simple example <dialog open> <p>greetings, one and all!</p> </dialog> advanced example this example opens a pop-up dialog box that contains a form, when the "update details" button is clicked.
<keygen> - HTML: Hypertext Markup Language
WebHTMLElementkeygen
autofocus this boolean attribute lets you specify that the control should have input focus when the page loads, unless the user overrides it, for example by typing in a different control.
... here is an example form submission as it would be delivered to a cgi program by the http server: commonname=john+doe&email=doe@foo.com&org=foobar+computing+corp.& orgunit=bureau+of+bureaucracy&locality=anytown&state=california&country=us& key=mihfmhewxdanbgkqhkig9w0baqefaanladbiakeanx0tiljromuue%2bptwbre6xfv%0awtkqbsshxk5zhcuwcwyvcniq9b82qhjdoacdd34rqfcaind46fxkqunb0mvkzqid%0aaqabfhfnb3ppbgxhsxnneuzyawvuz...
<noembed>: The Embed Fallback element (Obsolete) - HTML: Hypertext Markup Language
WebHTMLElementnoembed
examples the message inside <noembed> tag will appear only when your browser does not support <embed> tag.
... show an alternative content <embed type="vide/webm" src="/media/examples/flower.mp4" width="200" height="200"> <noembed> <h1>alternative content</h1> </noembed> </embed> ...
<script>: The Script element - HTML: Hypertext Markup Language
WebHTMLElementscript
examples basic usage these examples show how to import (an external) script using the <script> element.
... <script src="javascript.js"></script> and the following examples show how to put (an inline) script inside the <script> element.
<slot> - HTML: Hypertext Markup Language
WebHTMLElementslot
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: 2...
...italic } </style> <details> <summary> <code class="name">&lt;<slot name="element-name">need name</slot>&gt;</code> <i class="desc"><slot name="description">need description</slot></i> </summary> <div class="attributes"> <h4>attributes</h4> <slot name="attributes"><p>none</p></slot> </div> </details> <hr> </template> note: you can see this complete example in action at element-details (see it running live).
accesskey - HTML: Hypertext Markup Language
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
contextmenu - HTML: Hypertext Markup Language
here are some implementation examples, including nested menus.
... example html <body contextmenu="share"> <menu type="context" id="share"> <menu label="share"> <menuitem label="twitter" onclick="shareviatwitter()"></menuitem> <menuitem label="facebook" onclick="shareviafacebook()"></menuitem> </menu> </menu> <ol> <li> anywhere in the example you can share the page on twitter and facebook using the share menu from your context menu.
dir - HTML: Hypertext Markup Language
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
id - HTML: Hypertext Markup Language
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
itemref - HTML: Hypertext Markup Language
for example, it allows authors to mark up data in a table so that each column defines a separate item while keeping the properties in the cells.
... example html <div itemscope id="amanda" itemref="a b"></div> <p id="a">name: <span itemprop="name">amanda</span> </p> <div id="b" itemprop="band" itemscope itemref="c"></div> <div id="c"> <p>band: <span itemprop="name">jazz band</span> </p> <p>size: <span itemprop="size">12</span> players</p> </div> structured data (in json-ld format) { "@id": "amanda", "name": "amanda", "band": { "@id": "b", "name": "jazz band", "size": 12 } } result specifications specification status comment html microdatathe definition of 'itemref' in that specification.
itemtype - HTML: Hypertext Markup Language
for example, musicevent indicates a concert performance, with startdate and location properties specifying the concert's key details.
... simple example html <div itemscope itemtype="http://schema.org/product"> <span itemprop="brand">acme</span> <span itemprop="name">executive anvil</span> </div> structured data itemscope itemtype schema.org product itemprop name executive anvil itemprop brand [thing] itemprop name acme example html <div itemscope itemtype="http://schema.or...
spellcheck - HTML: Hypertext Markup Language
the source for this interactive example is stored in a github repository.
... if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
Data URLs - HTTP
a few examples: data:,hello%2c%20world!
...for example, the opera 11 browser limited urls to 65535 characters long which limits data urls to 65529 characters (65529 characters being the length of the encoded data, not the source, if you use the plain data:, without specifying a mime type).
Reason: CORS header 'Access-Control-Allow-Origin' missing - HTTP
for example, to allow a site at https://amazing.site to access the resource using cors, the header should be: access-control-allow-origin: https://amazing.site you can also configure a site to allow any site to access it by using the * wildcard.
... to allow any site to make cors requests without using the * wildcard (for example, to enable credentials), your server must read the value of the request's origin header and use that value to set access-control-allow-origin, and must also set a vary: origin header to indicate that some headers are being set dynamically depending on the origin.
Connection management in HTTP/1.x - HTTP
for example, instead of having all resources on the same domain, say www.example.com, it could split over several domains, www1.example.com, www2.example.com, www3.example.com.
... each of these domains resolve to the same server, and the web browser will open 6 connections to each (in our example, boosting the connections to 18).
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.
Access-Control-Request-Method - HTTP
header type request header forbidden header name yes syntax access-control-request-method: <method> directives <method> one of the http request methods, for example get, post, or delete.
... examples access-control-request-method: post specifications specification status comment fetchthe definition of 'access-control-request-method' in that specification.
Allow - HTTP
WebHTTPHeadersAllow
an empty allow header indicates that the resource allows no request methods, which might occur temporarily for a given resource, for example.
... 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
WebHTTPHeadersAlt-Svc
examples include h2 for http/2 and h3-25 for draft 25 of the http/3 protocol.
... example alt-svc: h2=":443"; ma=2592000; alt-svc: h2=":443"; ma=2592000; persist=1 alt-svc: h2="alt.example.com:443", h2=":443" alt-svc: h3-25=":443"; ma=3600, h2=":443"; ma=3600 specifications specification status comment rfc 7838 ietf rfc initial definition.
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.
... this includes static files that are served by the application such as images, css files and javascript files, for example.
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:.
... for example, to disallow nonsecure http images: content-security-policy: img-src https: specifications specification status comment mixed contentthe definition of 'block-all-mixed-content' in that specification.
CSP: plugin-types - HTTP
examples disallowing plugins to disallow all plugins, the object-src directive should be set to 'none' which will disallow plugins.
... <meta http-equiv="content-security-policy" content="object-src 'none'"> allowing flash content the content security policy content-security-policy: plugin-types application/x-shockwave-flash will allow to load flash objects: <object data="https://example.com/flash" type="application/x-shockwave-flash"></object> allowing java applets to load an <applet> you must specify application/x-java-applet: content-security-policy: plugin-types application/x-java-applet specifications specification status comment content security policy level 3the definition of 'plugin-types' in that specification.
CSP: referrer - HTTP
the document https://example.com/page.html will send the referrer https://example.com/.
... 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.
... report-to: { "group": "csp-endpoint", "max_age": 10886400, "endpoints": [ { "url": "https://example.com/csp-reports" } ] }, { "group": "hpkp-endpoint", "max_age": 10886400, "endpoints": [ { "url": "https://example.com/hpkp-reports" } ] } content-security-policy: ...; report-to csp-endpoint report-to: { "group": "endpoint-1", "max_age": 10886400, "endpoints": [ { "url": "https://example.com/reports" }, { "url": "https://backup.com/reports" } ] } content-security-policy: ...; report-to endpoint-1 ...
CSP: sandbox - HTTP
this will allow, for example, a third-party advertisement to be safely sandboxed without forcing the same restrictions upon a landing page.
... examples content-security-policy: sandbox allow-scripts; specifications specification status comment content security policy level 3the definition of 'sandbox' in that specification.
Cookie - HTTP
WebHTTPHeadersCookie
the cookie header is optional and may be omitted if, for example, the browser's privacy settings block cookies.
... examples cookie: phpsessid=298zf09hf012fh2; csrftoken=u32t4o3tb3gg43; _gat=1 specifications specification title rfc 6265, section 5.4: cookie http state management mechanism ...
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.
...for example, you can use the crossorigin attribute for this image from a third-party site: <img src="https://thirdparty.com/img.png" crossorigin> specifications specification html living standardthe definition of 'cross-origin-embedder-policy header' in that specification.
Expect-CT - HTTP
example the following example specifies enforcement of certificate transparency for 24 hours and reports violations to foo.example.
... expect-ct: max-age=86400, enforce, report-uri="https://foo.example/report" notes root cas manually added to the trust store override and suppress expect-ct reports/enforcement.
Feature-Policy - HTTP
<origin(s)>: the feature is allowed for specific origins (for example, https://example.com).
... example securecorp inc.
If-None-Match - HTTP
for example, two pages that differ by the date of generation in the footer would still be considered as identical.
... 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 ...
Index - HTTP
WebHTTPHeadersIndex
17 alt-svc draft, http, http header, needscompattable, needscontent, needsexample, reference the alt-svc header is used to list alternate ways to reach this website.
...the referer header allows servers to identify where people are visiting them from and may use that data for analytics, logging, or optimized caching, for example.
Public-Key-Pins-Report-Only - HTTP
example public-key-pins-report-only: pin-sha256="cupctazwkaasuywhhnedttwpy3obake3h2+sozs7sws="; pin-sha256="m8hztczm3eluxkcjr2s5p4hhybnf6lhkmjahkhpgpwe="; includesubdomains; report-uri="https://www.example.org/hpkp-report" in this example, pin-sha256="cupctazwkaasuywhhnedttwpy3obake3h2+sozs7sws=" pins the server's public key used in production.
...finally, report-uri="https://www.example.org/hpkp-report" explains where to report pin validation failures.
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.
... with save-data: on request: get /image.jpg http/1.0 host: example.com save-data: on response: http/1.0 200 ok content-length: 102832 vary: accept-encoding, save-data cache-control: public, max-age=31536000 content-type: image/jpeg [...] without save-data request: get /image.jpg http/1.0 host: example.com response: http/1.0 200 ok content-length: 481770 vary: accept-encoding, save-data cache-control: public, max-age=31536000 content-type: image/jpeg [...] specifications specification title draft-grigorik-http-client-hints-03, section 7: save-data http client hints ...
SameSite cookies - HTTP
set-cookie: flavor=choco; samesite=lax example: rewriteengine on rewritebase "/" rewritecond "%{http_host}" "^example\.org$" [nc] rewriterule "^(.*)" "https://www.example.org/index.html" [r=301,l,qsa] rewriterule "^(.*)\.ht$" "index.php?nav=$1 [nc,l,qsa,co=rewriterule;01;https://www.example.org;30/;samesite=none;secure] rewriterule "^(.*)\.htm$" "index.php?nav=$1 [nc,l,qsa,co=rewriterule;02;https://www.examp...
...le.org;30/;samesite=none;secure] rewriterule "^(.*)\.html$" "index.php?nav=$1 [nc,l,qsa,co=rewriterule;03;https://www.example.org;30/;samesite=none;secure] [...] rewriterule "^admin/(.*)\.html$" "admin/index.php?nav=$1 [nc,l,qsa,co=rewriterule;09;https://www.example.org:30/;samesite=strict;secure] specifications specification title rfc 6265, section 4.1: set-cookie http state management mechanism draft-ietf-httpbis-rfc6265bis-05 cookie prefixes, same-site cookies, and strict secure cookies ...
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.
... for example, when generating a large html table resulting from a database query or when transmitting large images.
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.
... location: https://example.com/ vary: upgrade-insecure-requests specifications specification status comment upgrade insecure requeststhe definition of 'upgrade-insecure-requests' in that specification.
Vary - HTTP
WebHTTPHeadersVary
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.
... for example, if you are serving different content to mobile users, it can help you to avoid that a cache may mistakenly serve a desktop version of your site to your mobile users.
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.
POST - HTTP
WebHTTPMethodsPOST
request has body yes successful response has body yes safe no idempotent no cacheable only if freshness information is included allowed in html forms yes syntax post /test example a simple form using the default application/x-www-form-urlencoded content type: post /test http/1.1 host: foo.example content-type: application/x-www-form-urlencoded content-length: 27 field1=value1&field2=value2 a form using the multipart/form-data content type: post /test http/1.1 host: foo.example content-type: multipart/form-data;boundary="boundary" --boundary content-disposition: form-...
...data; name="field1" value1 --boundary content-disposition: form-data; name="field2"; filename="example.txt" value2 --boundary-- specifications specification title rfc 7231, section 4.3.3: post hypertext transfer protocol (http/1.1): semantics and content rfc 2046, section 5.1.1: common syntax multipurpose internet mail extensions (mime) part two: media types ...
404 Not Found - HTTP
WebHTTPStatus404
apache servers can be configured using an .htaccess file and a code snippet like the following example.
... errordocument 404 /notfound.html for an example of a custom 404 page, see mdn's 404 page.
412 Precondition Failed - HTTP
WebHTTPStatus412
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.
... for example, when editing mdn, the current wiki content is hashed and put into an etag in the response: etag: "33a64df551425fcc55e4d42a148795d9f25f89d4" when saving changes to a wiki page (posting data), the post request will contain the if-match header containing the etag values to check freshness against.
451 Unavailable For Legal Reasons - HTTP
WebHTTPStatus451
status 451 unavailable for legal reasons example this example response is taken from the ietf rfc (see below) and contains a reference to monty python's life of brian.
... http/1.1 451 unavailable for legal reasons link: <https://spqr.example.org/legislatione>; rel="blocked-by" content-type: text/html <html> <head><title>unavailable for legal reasons</title></head> <body> <h1>unavailable for legal reasons</h1> <p>this request may not be serviced in the roman province of judea due to the lex julia majestatis, which disallows access to resources hosted on servers deemed to be ...
Concurrency model and the event loop - JavaScript
here is an example that demonstrates this concept (settimeout does not run immediately after its timer expires): const s = new date().getseconds(); settimeout(function() { // prints out "2", meaning that the callback is not called immediately after 500 milliseconds.
...in the example below, the message ''this is just a message'' will be written to the console before the message in the callback gets processed, because the delay is the minimum time required for the runtime to process the request (not a guaranteed time).
JavaScript technologies overview - JavaScript
this core language is also used in non-browser environments, for example in node.js.
... the html specification also defines restrictions on documents; for example, it requires all children of a <ul> element, which represents an unordered list, to be <li> elements, as those represent list items.
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.
...in the following example this refers to the derived class (not the base class) when we try to call derived.publicstaticmethod2(), and thus exhibits the same "provenance restriction" as mentioned above: class base { static #privatestaticmethod() { return 42; } static publicstaticmethod1() { return base.#privatestaticmethod(); } static publicstaticmethod2() { return this.#privat...
RangeError: radix must be an integer - JavaScript
for example, the decimal (base 10) number 169 is represented in hexadecimal (base 16) as a9.
... 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) ...
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.
TypeError: can't redefine non-configurable property "x" - JavaScript
however, for example, when using object.defineproperty(), the property isn't configurable by default.
... examples non-configurable properties created by object.defineproperty the object.defineproperty() creates non-configurable properties if you haven't specified them as configurable.
TypeError: setting getter-only property "x" - JavaScript
examples property with no setter the example below shows how to set a getter for a property.
...re', { get: function() { console.log('get!'); return temperature; } }); } var arc = new archiver(); arc.temperature; // 'get!' arc.temperature = 30; // typeerror: setting getter-only property "temperature" to fix this error, you will either need to remove line 16, where there is an attempt to set the temperature property, or you will need to implement a setter for it, for example like this: "use strict"; function archiver() { var temperature = null; var archive = []; object.defineproperty(this, 'temperature', { get: function() { console.log('get!'); return temperature; }, set: function(value) { temperature = value; archive.push({ val: temperature }); } }); this.getarchive = function() { return archive; }; } var arc = ...
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: invalid assignment to const "x" - JavaScript
examples invalid redeclaration assigning a value to the same constant name in the same block-scope will throw.
...should this constant appear in this scope or was it meant to appear in a function, for example?
SyntaxError: a declaration in the head of a for-of loop can't have an initializer - JavaScript
examples invalid for-of loop let iterable = [10, 20, 30]; for (let value = 50 of iterable) { console.log(value); } // syntaxerror: a declaration in the head of a for-of loop can't // have an initializer valid for-of loop you need to remove the initializer (value = 50) in the head of the for-of loop.
... maybe you intended to make 50 an offset value, in that case you could add it to the loop body, for example.
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 tha...
...t use a lot of different parenthesis and curly brackets, for example.
SyntaxError: missing } after property list - JavaScript
might be in fact a missing curly bracket, but could also be a missing comma, for example.
... examples forgotten comma oftentimes, there is a missing comma in your object initializer code: var obj = { a: 1, b: { myprop: 2 } c: 3 }; correct would be: var obj = { a: 1, b: { myprop: 2 }, c: 3 }; ...
SyntaxError: missing name after . operator - JavaScript
please see the examples below.
... examples property access property accessors in javascript use either the dot (.) or square brackets ([]), but not both.
SyntaxError: missing ) after argument list - JavaScript
this might be a typo, a missing operator, or an unescaped string, for example.
... examples because there is no "+" operator to concatenate the string, javascript expects the argument for the log function to be just "pi: ".
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.
...for example: if (done === true) { console.log("we are done!"); } ...
SyntaxError: missing ; before statement - JavaScript
examples unescaped strings this error can occur easily when not escaping strings properly and the javascript engine is expecting the end of your string already.
... for example: var foo = 'tom's bar'; // syntaxerror: missing ; before statement you can use double quotes, or escape the apostrophe: var foo = "tom's bar"; var foo = 'tom\'s bar'; declaring properties with var you cannot declare properties of an object or array with a var declaration.
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 pass...
...ed you can fix this by setting null as the prototype, for example: var obj = object.create(null); var obj = object.setprototypeof({}, null); ...
TypeError: can't delete non-configurable array element - JavaScript
however, for example, when using object.defineproperty(), the property isn't configurable by default.
... examples non-configurable properties created by object.defineproperty the object.defineproperty() creates non-configurable properties by default if you haven't specified them as configurable.
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.
... var colorenum = { red: 0, green: 1, blue: 2 }; var list = ["potatoes", "rice", "fries"]; update older browsers if you are using an older browser that does not yet implement let or class, for example, you should update to a more recent browser version that does support these new language features.
InternalError: too much recursion - JavaScript
examples this recursive function runs 10 times, as per the exit condition.
... set name(name){ this.name = name; // recursive call } in this example when the setter is triggered, it is told to do the same thing again: to set the same property that it is meant to handle.
ReferenceError: assignment to undeclared variable "x" - JavaScript
for more details and examples, see the var reference page.
... examples invalid cases in this case, the variable "bar" is an undeclared variable.
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.
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 expres...
...this doesn't work: function greeter() { german: function () { return "moin"; } } // syntaxerror: function statement requires a name this would work, for example: function greeter() { german: function g() { return "moin"; } } object methods if you intended to create a method of an object, you will need to create an object.
TypeError: cannot use 'in' operator to search for 'x' in 'y' - JavaScript
examples searching in strings unlike in other programming languages (e.g.
... "hello" in "hello world"; // typeerror: cannot use 'in' operator to search for 'hello' in 'hello world' instead you will need to use string.prototype.indexof(), for example.
AggregateError - JavaScript
it is thrown when multiple errors need to be reported by an operation, for example by promise.any(), when all promises passed to it reject.
... 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 { throw new aggregateerror([ new error("some error"), ], 'hello'); } catch (e) { console.log(e instanceof aggregateerror); // true console.log(e.message...
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.
Array.prototype.unshift() - JavaScript
hence, calling unshift with n arguments once, or calling it n times with 1 argument (with a loop, for example), don't yield the same results.
... 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, -6], [-5], [-4, -3], -2, -1, 0, 1, 2 ] specifications specification ecmascript (ecma-262)the definition of 'array.prototype.unshift' in that specifica...
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].
...rator.next().value; // "b" iterator.next()["value"]; // "c" iterator.next(); // object { value: "d", done: false } iterator.next(); // object { value: "e", done: false } iterator.next(); // object { value: undefined, done: true } iteraror.next().value; // undefined one-use: the array iterator object is one use or temporary object example: var arr = ['a', 'b', 'c', 'd', 'e']; var iterator = arr.values(); for (let letter of iterator) { console.log(letter); } //"a" "b" "c" "d" "e" for (let letter of iterator) { console.log(letter); } // undefined reason: when next().done=true or currentindex>length the for..of loop ends.
ArrayBuffer - JavaScript
you can also get an array buffer from existing data, for example from a base64 string or from a local file.
... 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
each must be a string that corresponds to a valid javascript identifier or a list of such strings separated with a comma; for example "x", "thevalue", or "a,b".
... 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 - JavaScript
all properties and methods of atomics are static (as is the case with the math object, for example).
... 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.
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.
Error.prototype.fileName - JavaScript
if called from a debugger context, the firefox developer tools for example, "debugger eval code" is returned.
... 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.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.
...for example: (newname(message ,filename,linenumber)) where these attributes correspond to the respective properties of the error instance.
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 =...
... */ release() { this.#registry.unregister(this); // ^^^^−−−−− unregister token } } this example shows registering a target object using a different object as its unregister token: { // ^^^^−−−−− held value console.error( `the \`release\` method was never called for the \`thingy\` for the file "${file.name}"` ); }; #registry = new finalizationregistry(this.#cleanup); /** * constructs a `thingy` instance for the given file.
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.
... // for example: function hello() { console.log("hello, world!"); } hello.tosource(); // results in: "function hello() { console.log(\"hello, world!\"); }" specifications not part of any standard.
GeneratorFunction - JavaScript
each must be a string that corresponds to a valid javascript identifier or a list of such strings separated with a comma; for example "x", "thevalue", or "a,b".
... 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.
InternalError() constructor - JavaScript
for example: "internalerror: too much recursion".
...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.
InternalError - JavaScript
example cases are mostly when something is too large, e.g.: "too many switch cases", "too many parentheses in regular expression", "array initializer too large", "too much recursion".
... examples too much recursion this recursive function runs 10 times, as per the exit condition.
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.
... for example, set the hourcycle property of the configuration object to your desired hour cycle type, and then pass it into the constructor: let us12hour = new intl.locale("en-us", {hourcycle: "h12"}); console.log(us12hour.hourcycle); // prints "h12" specifications specification ecmascript internationalization api (ecma-402) ...
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-c...
...a-gregory-hc-24"); console.log(japan.tostring()); // prints out "ja-jp-u-ca-gregory-hc-h24" console.log(japan.basename); // prints out "ja-jp" example with options that override input string // input string indicates language as dutch and region as belgium, // but options object overrides the region and sets it to the netherlands let dutch = new intl.locale("nl-latn-be", {region: "nl"}); console.log(dutch.basename); // prints out "nl-latn-nl" specifications specification ecmascript internationalization api (ecma-402) ...
Intl.Locale.prototype.numeric - JavaScript
for example, the string "a-21" will be considered less than "a-123".
... examples setting the numeric value via the locale string in the unicode locale string spec, the values that numeric represents correspond to the key kn.
Intl.Locale.prototype.region - JavaScript
for example, english is spoken in the united kingdom and the united states of america, but there are differences in spelling and other language conventions between those two countries.
... 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 - 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.
... for example, set the hourcycle property of the configuration object to your desired hour cycle type, and then pass it into the constructor: let us12hour = new intl.locale("en-us", {hourcycle: "h12"}); console.log(us12hour.hourcycle); // prints "h12" specifications specification ecmascript internationalization api (ecma-402) ...
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.
...for example by using array.prototype.map(), arrow functions, a switch statement, template literals, and array.prototype.reduce().
JSON - JavaScript
consider this example where json.parse() parses the string as json and eval executes the string as javascript: let code = '"\u2028\u2029"' json.parse(code) // evaluates to "\u2028\u2029" in all engines eval(code) // throws a syntaxerror in old engines other differences include allowing only double-quoted strings and having no provisions for undefined or comments.
... 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 ...
Map() constructor - JavaScript
(for example, arrays with two elements, such as [[ 1, 'one' ],[ 2, 'two' ]].) each key-value pair is added to the new map.
... 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 associa...
...even though every nan is not equal to itself (nan !== nan is true), the following example works because nans are indistinguishable from each other: let mymap = new map() mymap.set(nan, 'not a number') mymap.get(nan) // "not a number" let othernan = number('foo') mymap.get(othernan) // "not a number" iterating map with for..of maps can be iterated using a for..of loop: let mymap = new map() mymap.set(0, 'zero') mymap.set(1, 'one') for (let [key, value] of mymap) { console.log...
Object.prototype.__proto__ - JavaScript
examples using __proto__ var circle = function () {}; var shape = {}; var circle = new circle(); // set the object prototype.
...this is for example purposes only.
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.any() - JavaScript
examples first to fulfil promise.any() resolves with the first promise to fulfil, even if a promise rejects first.
... const perr = new promise((resolve, reject) => { reject('always fails'); }); promise.any([perr]).catch((err) => { console.log(err); }) // expected output: "aggregateerror: no promise in promise.any was resolved" displaying the first image loaded in this example, we have a function that fetches an image and returns a blob.
Promise.prototype.finally() - JavaScript
so for example: unlike promise.resolve(2).then(() => {}, () => {}) (which will be resolved with undefined), promise.resolve(2).finally(() => {}) will be resolved with 2.
... 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.error(error); /* this line can also throw, e.g.
Proxy() constructor - JavaScript
for example, by defining get() you can provide a customised version of the target's property accessor.
... examples selectively proxy property accessors in this example the target has two properties, notproxied and proxied.
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 ...
... // example foo example specifications specification ecmascript (ecma-262)the definition of 'regexp.prototype.dotall' in that specification.
RegExp.$1-$9 - JavaScript
the example below illustrates this.
... 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.
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 - JavaScript
same-origin cross-origin-embedder-policy: require-corp to check if cross origin isolation has been successful, you can test against the crossoriginisolated property available to window and worker contexts: if (crossoriginisolated) { // post sharedarraybuffer } else { // do something else } see also planned changes to shared memory which is starting to roll out to browsers (firefox 79, for example.) always use the new operator to create a sharedarraybuffer sharedarraybuffer constructors are required to be constructed with a new operator.
... 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.queryselecto...
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 ...
...attribute and manipulate it more generically, for example: document.getelementbyid('yourelemid').style.fontsize = '2em'; specifications specification ecmascript (ecma-262)the definition of 'string.prototype.big' in that specification.
String.prototype.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...
...'s style attribute and manipulate it more generically, for example: document.getelementbyid('yourelemid').style.fontsize = '0.7em'; specifications specification ecmascript (ecma-262)the definition of 'string.prototype.fontsize' in that specification.
String.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.
...// for example, 'test' is treated as ['t', 'e', 's', 't'].
WebAssembly.Global() constructor - JavaScript
examples creating a new global instance the following example shows a new global instance being created using the webassembly.global() constructor.
...estreaming(fetch('global.wasm'), { js: { global } }) .then(({instance}) => { asserteq("getting initial value from wasm", instance.exports.getglobal(), 0); global.value = 42; asserteq("getting js-updated value from wasm", instance.exports.getglobal(), 42); instance.exports.incglobal(); asserteq("getting wasm-updated value from js", global.value, 43); }); note: you can see the example running live on github; see also the source code.
WebAssembly.Global - JavaScript
examples creating a new global instance the following example shows a new global instance being created using the webassembly.global() constructor.
...estreaming(fetch('global.wasm'), { js: { global } }) .then(({instance}) => { asserteq("getting initial value from wasm", instance.exports.getglobal(), 0); global.value = 42; asserteq("getting js-updated value from wasm", instance.exports.getglobal(), 42); instance.exports.incglobal(); asserteq("getting wasm-updated value from js", global.value, 43); }); note: you can see the example running live on github; see also the source code.
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 w...
...ebassembly.module(bytes); let instance = new webassembly.instance(mod, importobject); instance.exports.exported_func(); }) however, the preferred way to get an instance is through the asynchronous webassembly.instantiatestreaming() function, for example like this: const importobject = { imports: { imported_func: function(arg) { console.log(arg); } } }; webassembly.instantiatestreaming(fetch('simple.wasm'), importobject) .then(obj => obj.instance.exports.exported_func()); specifications specification webassembly javascript interfacethe definition of 'instance' in that specification.
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.
... var importobject = { imports: { imported_func: function(arg) { console.log(arg); } } }; webassembly.instantiatestreaming(fetch('simple.wasm'), importobject) .then(obj => obj.instance.exports.exported_func()); note: you can also find this example as instantiate-streaming.html on github (view it live also).
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 w...
...ebassembly.module(bytes); let instance = new webassembly.instance(mod, importobject); instance.exports.exported_func(); }) the preferred way to get an instance is asynchronously, for example using the webassembly.instantiatestreaming() function like this: const importobject = { imports: { imported_func: function(arg) { console.log(arg); } } }; webassembly.instantiatestreaming(fetch('simple.wasm'), importobject) .then(obj => obj.instance.exports.exported_func()); this also demonstrates how the exports property is used to access exported functions.
WebAssembly.Table() constructor - JavaScript
examples creating a new webassembly table instance the following example (see table2.html source code and live version) creates a new webassembly table instance with an initial size of 2 elements.
... this example shows that we're creating and accessing the table from javascript, but the same table is visible and callable inside the wasm instance too.
WebAssembly.Table.prototype.set() - JavaScript
examples using table.set the following example (see table2.html source code and live version) creates a new webassembly table instance with an initial size of 2 references.
... this example shows that we're creating and accessing the table from javascript, but the same table is visible and callable inside the wasm instance too.
WebAssembly.Table - JavaScript
examples creating a new webassembly table instance the following example (see table2.html source code and live version) creates a new webassembly table instance with an initial size of 2 elements.
... this example shows that we're creating and accessing the table from javascript, but the same table is visible and callable inside the wasm instance too.
super - JavaScript
examples using super in classes this code snippet is taken from the classes sample (live demo).
...in this example, two objects define a method.
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.
...when iterating arrays for example with array.prototype.foreach() or array.prototype.map(), array holes are skipped.
related_applications - Web app manifests
type array mandatory no the related_applications field is an array of objects specifying native applications that are installable by, or accessible to, the underlying platform — for example, a native android application obtainable through the google play store.
... 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 platform the platform on which the application can be found.
<mi> - MathML
WebMathMLElementmi
the following values are allowed: normal (default value for more than one character) ; example bold ; example italic (default value for a single character) ; 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"> &pi; </mi> </math> specifications specification status comment mathml 3.0the definition of 'mi' in that specification.
<mo> - MathML
WebMathMLElementmo
the following values are allowed: normal (default value) ; example bold ; example 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> <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...
<ms> - MathML
WebMathMLElementms
the following values are allowed: normal (default value) ; example bold ; example 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> <ms lquote="„" rquote="“"> abc </ms> </math> specifications specification status comment mathml 3.0the definition of 'ms' in that specification.
<mtext> - MathML
WebMathMLElementmtext
the following values are allowed: normal (default value) ; example bold ; example 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 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.
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.
Digital audio concepts - Web media technologies
in this example, the blue line represents the samples taken from the audio waveform, which is black.
... for example, consider a stereo audio clip (that is, two audio channels) with a sample size of 16 bits (2 bytes), recorded at 48 khz: 2×2bytessample×48000samplessecond=192000bytessecond=192kbps2 \times 2\frac { bytes }{ sample } \times 48000\frac { samples }{ second } = 192000\frac { bytes }{ second } = 192 kbps at 192 kbps, lower-end networks are already going to be strained just by a single audio stream...
Guide to streaming audio and video - Web media technologies
for example, because many web sites' mobile-specific content assume that mobile browsers support hls, firefox for android does as well, in order to avoid strange compatibility errors from occurring due to this assumption being incorrect.
...for example, hls lets the server stream a video with multiple audio streams which the user can choose from, in order to hear their own language.
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.
... an example: margin versus transform in this section we'll see how the waterfall can highlight the difference between animating using margin and animating using transform.
Lazy loading - Web Performance
a practical example would be when, you land on the home page of an e-commerce site which has a link to a cart page/section and all its resources (js, css, images...) are downloaded only when the user navigates to that cart page.
...most of those images are off-screen (non-critical), requiring user interaction (an example being scroll) in order to view them.
Performance Monitoring: RUM vs synthetic monitoring - Web Performance
an example of synthetic monitoring is webpagetest.org.
...for example, but it isn't reflective of the actual experience of users, especially the long tail.
Progressive web apps (PWAs)
progressive loadingin previous articles we covered apis that help us make our js13kpwa example a progressive web app: service workers, web manifests, notifications and push.
... core pwa guides the following guides show you what need to do to implement a pwa, by examining a simple example and showing you how all the pieces work.
alignment-baseline - SVG: Scalable Vector Graphics
for example, this allows alphabetic baselines in roman text to stay aligned across font size changes.
... example <svg width="300" height="120" viewbox="0 0 300 120" xmlns="http://www.w3.org/2000/svg"> <!-- materialisation of anchors --> <path d="m60,10 l60,110 m30,10 l300,10 m30,65 l300,65 m30,110 l300,110 " stroke="grey" /> <!-- anchors in action --> <text alignment-baseline="hanging" x="60" y="10">a hanging</text>...
baseProfile - SVG: Scalable Vector Graphics
for example, the value of the attribute could be used by an authoring tool to warn the user when they are modifying the document beyond the scope of the specified base profile.
... only one element is using this attribute: <svg> context notes value profile name default value none animatable no example <svg width="120" height="120" version="1.1" xmlns="http://www.w3.org/2000/svg" baseprofile="full"> ...
class - SVG: Scalable Vector Graphics
WebSVGAttributeclass
for example, a <list-of-lengths> is represented in the svg dom using an svglengthlist or svganimatedlengthlist object.
... example <html> <body> <svg width="120" height="220" viewport="0 0 120 120" version="1.1" xmlns="http://www.w3.org/2000/svg"> <style type="text/css" > <![cdata[ rect.rectclass { stroke: #000066; fill: #00cc00; } circle.circleclass { stroke: #006600; fill: #cc0000; } ]]> </style> <rect class="rectclass" x="10" y="10" width="100" height="100"/> <circle class="circleclass" cx="40" cy="50" r="26"/> </svg> </body> </html> elements the following elements can use the class attribute: ...
fill-rule - SVG: Scalable Vector Graphics
example html,body,svg { height:100% } <svg viewbox="-10 -10 320 120" xmlns="http://www.w3.org/2000/svg"> <!-- effect of nonzero fill rule on crossing path segments --> <polygon fill-rule="nonzero" stroke="red" points="50,0 21,90 98,35 2,35 79,90"/> <!-- effect of nonzero fill rule on a shape inside a shape with the path segment moving in the same direction (both squares drawn...
... example html,body,svg { height:100% } <svg viewbox="-10 -10 320 120" xmlns="http://www.w3.org/2000/svg"> <!-- effect of evenodd fill rule on crossing path segments --> <polygon fill-rule="evenodd" stroke="red" points="50,0 21,90 98,35 2,35 79,90"/> <!-- effect of evenodd fill rule on on a shape inside a shape with the path segment moving in the same direction (both squares dr...
paint-order - SVG: Scalable Vector Graphics
for example, using stroke is equivalent to stroke fill markers.
... example <svg xmlns="http://www.w3.org/2000/svg" width="400" height="200"> <lineargradient id="g" x1="0" y1="0" x2="0" y2="1"> <stop stop-color="#888"/> <stop stop-color="#ccc" offset="1"/> </lineargradient> <rect width="400" height="200" fill="url(#g)"/> <g fill="crimson" stroke="white" stroke-width="6" stroke-linejoin="round" text-anchor="middle" font-family="sans-serif" font-size="50px" font-weight="bold"> <text x="200" y="75">stroke over</text> <text x="200" y="150" paint-order="stroke" id="stroke-under">stroke under</text> </g> </svg> the example would be rendered as follows: the stroke under effect could be achieved via the following css property: #stroke-under { paint-order: stroke; } specifications specification status comment ...
points - SVG: Scalable Vector Graphics
WebSVGAttributepoints
value [ <number>+ ]# default value none animatable yes example html,body,svg { height:100% } <svg viewbox="-10 -10 120 120" xmlns="http://www.w3.org/2000/svg"> <!-- polyline is an open shape --> <polyline stroke="black" fill="none" points="50,0 21,90 98,35 2,35 79,90"/> </svg> polygon for <polygon>, points defines a list of points, each representing a vertex of the shape to be drawn.
... value [ <number>+ ]# default value none animatable yes example html,body,svg { height:100% } <svg viewbox="-10 -10 120 120" xmlns="http://www.w3.org/2000/svg"> <!-- polygon is an closed shape --> <polygon stroke="black" fill="none" points="50,0 21,90 98,35 2,35 79,90" /> </svg> specifications specification status comment scalable vector graphics (svg) 2the definition of 'points' in that specification.
preserveAspectRatio - SVG: Scalable Vector Graphics
example <svg viewbox="-1 -1 162 92" xmlns="http://www.w3.org/2000/svg"> <defs> <path id="smiley" d="m50,10 a40,40,1,1,1,50,90 a40,40,1,1,1,50,10 m30,40 q36,35,42,40 m58,40 q64,35,70,40 m30,60 q50,75,70,60 q50,75,30,60" /> </defs> <!-- (width>height) meet --> <svg preserveaspectratio="xmidymid meet" x="0" y="0" viewbox="0 0 100 100" width="20" height="10"><use href="#smiley" /></svg> <svg preserveaspe...
...dymid slice" x="135" y="0" viewbox="0 0 100 100" width="10" height="25"><use href="#smiley" /></svg> <svg preserveaspectratio="xmaxymid slice" x="150" y="0" viewbox="0 0 100 100" width="10" height="25"><use href="#smiley" /></svg> <!-- none --> <svg preserveaspectratio="none" x="0" y="30" viewbox="0 0 100 100" width="160" height="60"><use href="#smiley" /></svg> </svg> topexample html,body,svg { height:100% } <svg viewbox="-1 -1 162 92" xmlns="http://www.w3.org/2000/svg"> <defs> <path id="smiley" d="m50,10 a40,40,1,1,1,50,90 a40,40,1,1,1,50,10 m30,40 q36,35,42,40 m58,40 q64,35,70,40 m30,60 q50,75,70,60 q50,75,30,60" /> </defs> <!-- (width>height) meet --> <rect x="0" y="0" width="20" height="10"> <title>xmidymid meet</title> </rect> <svg viewbox="...
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" x...
... 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="...
systemLanguage - SVG: Scalable Vector Graphics
for example, content that is presented simultaneously in the original maori and english versions, would call for: <text systemlanguage="mi, en"><!-- content goes here --></text> however, just because multiple languages are present within the object on which the systemlanguage test attribute is placed, this does not mean that it is intended for multiple linguistic audiences.
... an example would be a beginner's language primer, such as "a first lesson in latin," which is clearly intended to be used by an english-literate audience.
textLength - SVG: Scalable Vector Graphics
example let's create a simple example that presents text you can resize using an <input> element of type "range".
... result here's what the example looks like.
unicode - SVG: Scalable Vector Graphics
WebSVGAttributeunicode
for example, if unicode="ffl", then the given glyph will be used to render the sequence of characters "f", "f", and "l".
...for example, unicode="ffl" could be expressed as xml character references in hexadecimal notation as unicode="&#x66;&#x66;&#x6c;" or in decimal notation as unicode="&#102;&#102;&#108;".
x - SVG: Scalable Vector Graphics
WebSVGAttributex
value list of (<length> | <percentage>) default value 0 animatable yes example html,body,svg { height:100% } <svg viewbox="0 0 200 100" xmlns="http://www.w3.org/2000/svg"> <!-- horizontal line to materialized the text base line --> <line x1="0" y1="40%" x2="100%" y2="40%" /> <line x1="0" y1="90%" x2="100%" y2="90%" /> <!-- vertical line to materialized the x positioning --> <line x1="25%" y1="0" x2="25%" y2="100%" /> <line x1="50%" y1="0" x2="50%" y2="100%"...
... value list of (<length> | <percentage>) default value none animatable yes example html,body,svg { height:100% } <svg viewbox="0 0 200 100" xmlns="http://www.w3.org/2000/svg"> <!-- horizontal line to materialized the text base line --> <line x1="0" y1="40%" x2="100%" y2="40%" /> <line x1="0" y1="90%" x2="100%" y2="90%" /> <!-- vertical line to materialized the x positioning --> <line x1="25%" y1="0" x2="25%" y2="100%" /> <line x1="50%" y1="0" x2="50%" y2="100%"...
x1 - SVG: Scalable Vector Graphics
WebSVGAttributex1
value <length> | <percentage> default value 0 animatable yes example html,body,svg { height:100% } <svg viewbox="0 0 10 10" xmlns="http://www.w3.org/2000/svg"> <line x1="1" x2="5" y1="1" y2="9" stroke="red" /> <line x1="5" x2="5" y1="1" y2="9" stroke="green" /> <line x1="9" x2="5" y1="1" y2="9" stroke="blue" /> </svg> lineargradient for <lineargradient>, x1 defines the x coordinate of the starting point of the gradient vector used to map the grad...
...the exact behavior of this attribute is influenced by the gradientunits attributs value <length> | <percentage> default value 0% animatable yes example html,body,svg { height:100% } <svg viewbox="0 0 20 10" xmlns="http://www.w3.org/2000/svg"> <!-- by default the gradient vector start at the left bounding limit of the shape it is applied to --> <lineargradient x1="0%" id="g0"> <stop offset="0" stop-color="black" /> <stop offset="100%" stop-color="red" /> </lineargradient> <rect x="1" y="1" width="8" height="8" fill="url(#g0)" /> <!-- here the gradient vector start at 80% of the left bounding limit of the shape it is applied to --> <lineargradient x1="80%" id="g1"> <stop offset="0" stop-c...
x2 - SVG: Scalable Vector Graphics
WebSVGAttributex2
value <length> | <percentage> default value 0 animatable yes example html,body,svg { height:100% } <svg viewbox="0 0 10 10" xmlns="http://www.w3.org/2000/svg"> <line x1="5" x2="1" y1="1" y2="9" stroke="red" /> <line x1="5" x2="5" y1="1" y2="9" stroke="green" /> <line x1="5" x2="9" y1="1" y2="9" stroke="blue" /> </svg> lineargradient for <lineargradient>, x2 defines the x coordinate of the ending point of the gradient vector used to map the gradie...
...the exact behavior of this attribute is influenced by the gradientunits attributs value <length> | <percentage> default value 100% animatable yes example html,body,svg { height:100% } <svg viewbox="0 0 20 10" xmlns="http://www.w3.org/2000/svg"> <!-- by default the gradient vector end at the right bounding limit of the shape it is applied to --> <lineargradient x2="100%" id="g0"> <stop offset="0" stop-color="black" /> <stop offset="100%" stop-color="red" /> </lineargradient> <rect x="1" y="1" width="8" height="8" fill="url(#g0)" /> <!-- here the gradient vector start at 20% of the left bounding limit of the shape it is applied to --> <lineargradient x2="20%" id="g1"> <stop offset="0" stop-...
y - SVG: Scalable Vector Graphics
WebSVGAttributey
value list of (<length> | <percentage>) default value 0 animatable yes example html,body,svg { height:100% } <svg viewbox="0 0 200 100" xmlns="http://www.w3.org/2000/svg"> <!-- horizontal line to materialized the text base line --> <line x1="0" y1="40%" x2="100%" y2="40%" /> <line x1="0" y1="60%" x2="100%" y2="60%" /> <line x1="0" y1="80%" x2="100%" y2="80%" /> <!-- vertical line to materialized the x positioning --> <line x1="5%" y1="0" x2="5%" y2="100%"...
... value list of (<length> | <percentage>) default value none animatable yes example html,body,svg { height:100% } <svg viewbox="0 0 200 100" xmlns="http://www.w3.org/2000/svg"> <!-- horizontal line to materialized the text base line --> <line x1="0" y1="40%" x2="100%" y2="40%" /> <line x1="0" y1="60%" x2="100%" y2="60%" /> <line x1="0" y1="80%" x2="100%" y2="80%" /> <!-- vertical line to materialized the x positioning --> <line x1="5%" y1="0" x2="5%" y2="100%"...
y1 - SVG: Scalable Vector Graphics
WebSVGAttributey1
value <length> | <percentage> default value 0 animatable yes example html,body,svg { height:100% } <svg viewbox="0 0 10 10" xmlns="http://www.w3.org/2000/svg"> <line x1="1" x2="9" y1="1" y2="5" stroke="red" /> <line x1="1" x2="9" y1="5" y2="5" stroke="green" /> <line x1="1" x2="9" y1="9" y2="5" stroke="blue" /> </svg> lineargradient for <lineargradient>, y1 defines the y coordinate of the starting point of the gradient vector used to map the gradi...
...the exact behavior of this attribute is influenced by the gradientunits attributs value <length> | <percentage> default value 0% animatable yes example html,body,svg { height:100% } <svg viewbox="0 0 20 10" xmlns="http://www.w3.org/2000/svg"> <!-- by default the gradient vector start at the top left corner of the bounding box of the shape it is applied to.
y2 - SVG: Scalable Vector Graphics
WebSVGAttributey2
value <length> | <percentage> default value 0 animatable yes example html,body,svg { height:100% } <svg viewbox="0 0 10 10" xmlns="http://www.w3.org/2000/svg"> <line x1="1" x2="9" y1="5" y2="1" stroke="red" /> <line x1="1" x2="9" y1="5" y2="5" stroke="green" /> <line x1="1" x2="9" y1="5" y2="9" stroke="blue" /> </svg> lineargradient for <lineargradient>, y2 defines the y coordinate of the ending point of the gradient vector used to map the gradien...
...the exact behavior of this attribute is influenced by the gradientunits attributs value <length> | <percentage> default value 0% animatable yes example html,body,svg { height:100% } <svg viewbox="0 0 20 10" xmlns="http://www.w3.org/2000/svg"> <!-- by default the gradient vector end at the top right corner of the bounding box of the shape it is applied to.
<feGaussianBlur> - SVG: Scalable Vector Graphics
example simple example svg <svg width="230" height="120" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> <filter id="blurme"> <fegaussianblur in="sourcegraphic" stddeviation="5" /> </filter> <circle cx="60" cy="60" r="50" fill="green" /> <circle cx="170" cy="60" r="50" fill="green" filter="url(#blurme)" /> </svg> result screenshotlive sample...
... drop shadow example svg <svg width="120" height="120" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> <filter id="dropshadow"> <fegaussianblur in="sourcealpha" stddeviation="3" /> <feoffset dx="2" dy="4" /> <femerge> <femergenode /> <femergenode in="sourcegraphic" /> </femerge> </filter> <circle cx="60" cy="60" r="50" fill="green" filter="url(#dropshadow)" /> </svg> result screenshotlive sample specifications specification status comment filter effects module level 1the definition of '<fegaussianblur>' in that specification.
<metadata> - SVG: Scalable Vector Graphics
WebSVGElementmetadata
example <svg width="400" viewbox="0 0 400 300" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> <metadata> <rdf:rdf xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:connect="http://www.w3.org/1999/08/29-svg-connections-in-rdf#"> <rdf:description about="#cablea"> <connect:ends rdf:resource="#socket1"/> <connect:ends rdf...
...t:ends> </rdf:description> <rdf:description about="#hub"> <connect:ends rdf:resource="#socket1"/> <connect:ends rdf:resource="#socket2"/> <connect:ends rdf:resource="#socket3"/> <connect:ends rdf:resource="#socket4"/> <connect:ends rdf:resource="#socket5"/> </rdf:description> </rdf:rdf> </metadata> <title>network</title> <desc>an example of a computer network based on a hub.</desc> <style> svg { /* default styles to be inherited */ fill: white; stroke: black; } text { fill: black; stroke: none; } path { fill: none; } </style> <!-- define symbols used in the svg --> <defs> <!-- hubplug symbol.
SVG: Scalable Vector Graphics
WebSVG
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.
Features restricted to secure contexts - Web security
api chrome/opera edge safari firefox async clipboard api 66 not supported not supported 63 background sync (see syncmanager, for example) 49 not supported not supported not supported cache-control: immutable not supported 15 11 49 credential management api 51 not supported not supported not supported generic sensor api 67 not supported not supported not supported payment request api (and basic card payment).
...ing api supported not supported not supported behind flag since fx 65 service workers 40 17 11.1 44 storage api 55 not supported not supported 51 web authentication api 65 in preview (17) in development 60 web bluetooth 56 not supported not supported not supported web midi (see midiaccess, for example) 43 not supported not supported not supported web crypto api 60 79 not supported 75 secure context restrictions that vary by browser some browsers may decide to disable certain apis in non-secure contexts or apply other restrictions/security measures, despite the spec not requiring them.
How to turn off form autocompletion - Web security
however, some data submitted in forms either are not useful in the future (for example, a one-time pin) or contain sensitive information (for example, a unique government identifier or credit card security code).
...for example, firefox version 67 (see bug 1119063) stopped autofilling in this case; however, firefox 70 (see bug 1565407) can suggest securely-generated passwords, but does not autofill a saved password.
Web security
typically, it's used to tell if two requests came from the same browser — keeping a user logged-in, for example.
... subresource integrity subresource integrity (sri) is a security feature that enables browsers to verify that resources they fetch (for example, from a cdn) are delivered without unexpected manipulation.
translate - XPath
example <xsl:value-of select="translate('the quick brown fox.', 'abcdefghijklmnopqrstuvwxyz', 'abcdefghijklmnopqrstuvwxyz')" /> output the quick brown fox.
... example <xsl:value-of select="translate('the quick brown fox.', 'brown', 'red')" /> output the quick red fdx.
XSLT elements reference - XSLT: Extensible Stylesheet Language Transformations
WebXSLTElement
it consists of any non-instruction element that should be copied as-is to the result document, for example, an <hr> element in an html conversion stylesheet.
...for example, assume that a variable "image-dir" is defined as follows: <xsl:variable name="image-dir">/images</xsl:variable> the expression to be evaluated is placed inside curly brackets: <img src="{$image-dir}/mygraphic.jpg"/> this would result in the following: <img src="/images/mygraphic.jpg"/> the element annotations that follow include a description, a syntax listing, a list of required and optio...
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" s...
... 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.
Using the Mozilla JavaScript interface to XSL Transformations - XSLT: Extensible Stylesheet Language Transformations
var testtransform = document.implementation.createdocument("", "test", null); // just an example to get a transform into a script as a dom // xmldocument.load is asynchronous, so all processing happens in the // onload handler testtransform.addeventlistener("load", onload, false); testtransform.load("test-transform.xml"); function onload() { processor.importstylesheet(testtransform); } xsltprocessor.importstylesheet() requires one argument, a dom node.
...see the xslt/javascript interface in gecko for an example.
Loading and running WebAssembly code - WebAssembly
see second overload example.
... the final code looks like this: request = new xmlhttprequest(); request.open('get', 'simple.wasm'); request.responsetype = 'arraybuffer'; request.send(); request.onload = function() { var bytes = request.response; webassembly.instantiate(bytes, importobject).then(results => { results.instance.exports.exported_func(); }); }; note: you can see an example of this in action in xhr-wasm.html.
Compiling from Rust to WebAssembly - WebAssembly
open this file, and change its contents to look like this: [package] name = "hello-wasm" version = "0.1.0" authors = ["your name <you@example.com>"] description = "a sample project with wasm-pack" license = "mit/apache-2.0" repository = "https://github.com/yourgithubusername/hello-wasm" [lib] crate-type = ["cdylib"] [dependencies] wasm-bindgen = "0.2" fill in your own repository and use the same info that git uses for the authors field.
...reate webpack.config.js and put the following in it: const path = require('path'); module.exports = { entry: "./index.js", output: { path: path.resolve(__dirname, "dist"), filename: "index.js", }, mode: "development" }; now we need an html file; create index.html and give it the following contents: <!doctype html> <html> <head> <meta charset="utf-8"> <title>hello-wasm example</title> </head> <body> <script src="./index.js"></script> </body> </html> finally, create the index.js referenced in the html file and give it these contents: const js = import("./node_modules/hello-wasm/hello_wasm.js"); js.then(js => { js.greet("webassembly"); }); note that you need to fill in your npm username again.
2015 MDN Fellowship Program - Archive of obsolete content
you may propose your own subject area (examples: virtual reality on the web, network security, css, etc.) or we will work with you to match you to the best subject based on your background and mozilla priorities.
Navigator.mozNotification - Archive of obsolete content
see displaying notifications for an example.
Navigator - Archive of obsolete content
see displaying notifications for an example.
Cross-domain Content Scripts - Archive of obsolete content
in particular, they can't: access content hosted in an iframe, if that content is served from a different domain make cross-domain xmlhttprequests however, you can enable these features for specific domains by adding them to your add-on's package.json under the "cross-domain-content" key, which itself lives under the "permissions" key: "permissions": { "cross-domain-content": ["http://example.org/", "http://example.com/"] } the domains listed must include the scheme and fully qualified domain name, and these must exactly match the domains serving the content - so in the example above, the content script will not be allowed to access content served from https://example.com/.
Classes and Inheritance - Archive of obsolete content
the constructor property is supposed to be non-configurable, non-enumberable, and non-writable, so the correct way to define it is as follows: circle.prototype = object.create(shape.prototype, { constructor: { value: circle } }); overriding methods as a final example, we show how to override the stub implementation of the method draw in shape with a more specialized one in circle.
Content Processes - Archive of obsolete content
the xray wrappers we saw earlier are an example of such a security wrapper.
Program ID - Archive of obsolete content
for example: addons.mozilla.org uses it to distinguish between new add-ons and updates to existing add-ons, and the simple-storage module uses it to figure out which stored data belongs to which add-on.
Guides - Archive of obsolete content
porting example a walkthrough of porting a relatively simple xul-based add-on to the sdk.
notifications - Archive of obsolete content
here's a typical example.
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 s...
chrome - Archive of obsolete content
you can see an example of using this api in the xul migration guide.
content/loader - Archive of obsolete content
example: the following code creates a wrapper on a hidden frame that reloads a web page in the frame every time the contenturl property is changed: var hiddenframes = require("sdk/frame/hidden-frame"); var { loader } = require("sdk/content/content"); var pageloader = loader.compose({ constructor: function pageloader(options) { options = options || {}; if (options.contenturl) this.conten...
content/symbiont - Archive of obsolete content
this._frame = getmyframe(); this._init(options) } }); see the panel module for a real-world example of usage of this module.
core/heritage - Archive of obsolete content
also, idiomatic sdk code does not uses optional new keywords, but you're free to use it in your add-on code: var fluffy = dog('fluffy'); // instatiation fluffy instanceof dog // => true fluffy instanceof class // => true as you could notice from example above classes created via class function by default inherits from a class itself.
event/core - Archive of obsolete content
for example, the tabs module emits an open event when a new tab is opened.
event/target - Archive of obsolete content
for example, a panel instance emits an show event when the panel is shown.
frame/hidden-frame - Archive of obsolete content
equire("sdk/frame/hidden-frame"); let hiddenframe = hiddenframes.add(hiddenframes.hiddenframe({ onready: function() { this.element.contentwindow.location = "http://www.mozilla.org/"; let self = this; this.element.addeventlistener("domcontentloaded", function() { console.log(self.element.contentdocument.title); }, true, true); } })); see the panel module for a real-world example of usage of this module.
loader/sandbox - Archive of obsolete content
usage create a sandbox to create a sandbox: const { sandbox, evaluate, load } = require("sdk/loader/sandbox"); let scope = sandbox('http://example.com'); the argument passed to the sandbox defines its privileges.
places/favicon - Archive of obsolete content
let { getfavicon } = require("sdk/places/favicon"); // string example getfavicon("http://mozilla.org").then(function (url) { console.log(url); // http://mozorg.cdn.mozilla.net/media/img/favicon.ico }); // tab example require("sdk/tabs").open({ url: "http://mozilla.org", onready: function (tab) { getfavicon(tab).then(function (url) { console.log(url); // http://mozorg.cdn.mozilla.net/media/img/favicon.ico }); } }); // an optional callback can...
places/history - Archive of obsolete content
example let { search } = require("sdk/places/history"); // simple query search( { url: "https://developers.mozilla.org/*" }, { sort: "visitcount" } ).on("end", function (results) { // results is an array of objects containing // data about visits to any site on developers.mozilla.org // ordered by visit count }); // complex query // the query objects are or'd together // let's say we want to retrieve all visits from before a week ago // with the query of 'ruby', but from last week onwards, we want // all results with 'ja...
preferences/event-target - Archive of obsolete content
example var { prefstarget } = require("sdk/preferences/event-target"); // listen to the same branch which reqire("sdk/simple-prefs") does var target = prefstarget({ branchname: "extensions." + require("sdk/self").preferencesbranch + "." }); target.once("test", function(prefname) { console.log(prefname) // logs "test" console.log(target.prefs[name]) // logs true }); target.once("", function() { ...
ui/toolbar - Archive of obsolete content
for example, this code is equivalent to once(): var { toolbar } = require("sdk/ui/toolbar"); var { frame } = require("sdk/ui/frame"); var frame = new frame({ url: "./frame.html" }); var toolbar = toolbar({ title: "my toolbar", items: [frame] }); toolbar.on("show", showing); toolbar.on("hide", hiding); function showing(e) { console.log("showing: " + e.title); toolbar.removelistener("show", show...
util/collection - Archive of obsolete content
for example, the following 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').leng...
Low-Level APIs - Archive of obsolete content
in many cases these modules have simpler, more restricted analogs among the "high-level apis" (for example, windows or request).
console - Archive of obsolete content
for example, if the logging level is set to "info", then calls to info(), log(), warn(), and error() will all result in output being written.
package.json - Archive of obsolete content
firefox: firefox desktop fennec: firefox for android thunderbird: thunderbird seamonkey: seamonkey any application uuid example: "engines": { "firefox": ">= 38.0a1", "fennec": ">= 38.0a1" } fullname note: this is deprecated along with cfx; it's not available when using jpm.
Adding a Button to the Toolbar - Archive of obsolete content
specifying the icon the icon property may specify a single icon or a collection of icons in different sizes, as in the example above.
Annotator - Archive of obsolete content
if you want to refer to the complete add-on you can find it under the examples directory in the sdk.
Chrome Authority - Archive of obsolete content
for example, none of the following code will be matched by the manifest scanner, leading to exceptions at runtime, when the require() call is prohibited from importing the named modules: // all of these will fail!
Listen for Page Load - Archive of obsolete content
the script adds a red border to the tab's document: require("sdk/tabs").on("ready", runscript); function runscript(tab) { tab.attach({ contentscript: "if (document.body) document.body.style.border = '5px solid red';" }); } (this example is only to show the idea: to implement something like this, you should instead use page-mod, and specify "*" as the match-pattern.) learning more to learn more about working with tabs in the sdk, see the tabs api reference.
Logging - Archive of obsolete content
the following add-on logs the html content of every tab the user loads, by calling console.log() inside a content script: require("sdk/tabs").on("ready", function(tab) { tab.attach({ contentscript: "console.log(document.body.innerhtml);" }); }); console output if you are running your add-on from the command line (for example, executing jpm run or jpm test) then the console's messages appear in the command shell you used.
Developing for Firefox Mobile - Archive of obsolete content
for example, on mac os x or linux you can use a command like the one below to filter only the lines of console output: adb logcat | grep console you can experiment with different filter strings on adb logcat to focus in on the lines relevant to you.
Unit Testing - Archive of obsolete content
to show the module in use, edit the "index.js" file as follows: var base64 = require("./base64"); var button = require("sdk/ui/button/action").actionbutton({ id: "base64", label: "base64", icon: "./icon-16.png", onclick: function() { encoded = base64.btoa("hello"); console.log(encoded); decoded = base64.atob(encoded); console.log(decoded); } }); to run this example you'll also have to have an icon file named "icon-16.png" saved in your add-ons "data" directory.
Using third-party modules (jpm) - Archive of obsolete content
in your add-on code, you can require() modules by passing a path to the module starting from, but not including "node_modules": var menuitems = require("menuitem"); details create a new directory called, for example, "my-menuitem", navigate to it, type "jpm init" and accept all the defaults: mkdir my-menuitem cd my-menuitem jpm init install the menuitem package from npm: npm install menuitem --save this will install the package in the current directory, under a directory called "node_modules".
Canvas code snippets - Archive of obsolete content
this can be very useful to compare for example if a user has painted over another area as explained in this blog post.
Customizing the download progress bar - Archive of obsolete content
this example illustrates how to customize the progress bar displayed for a given download in the downloads window.
Downloading Files - Archive of obsolete content
for example, with empty dummy methods if you are not interested about the progress.
SVG General - Archive of obsolete content
here are some examples of using it: var circle = makesvg("circle", {id: "circle1", cx: "60", cy: "60", r: "50"}); var img = makesvg("image", {id: "img1", x: "110", y: "110", width: "100", height: "100", svghref: "bubbles.png"}); var text = makesvg("text", {id: "text1", x: "60", y: "60"}); text.textcontent = "hello world"; ...
Tabbox - Archive of obsolete content
examples: .tabs-closebutton { list-style-image: url(http://mozilla.org/favicon.ico); } .tabs-closebutton { list-style-image: url("chrome://global/skin/icons/close.gif"); } ...
Delayed Execution - Archive of obsolete content
some example usages include: const timer = components.constructor("@mozilla.org/timer;1", "nsitimer", "initwithcallback"); function delay(timeout, func) { let timer = new timer(function () { // remove the reference so that it can be reaped.
XPath - Archive of obsolete content
notes and sample code for xpath and ajax (the following was moved from document.evaluate) obj.evaluate(xpathexpression,contextnode,namespaceresolver,resulttype,result); //obj and contextnode should be the same object, if context is a ajax xml object (example: returnedxml) this should be used as : returnedxml.evaluate(xpathexpression,returnedxml,namespaceresolver,returntype,result); //contextnode should be used in the one in which it was created //add by mooring 2008-11-15 16:00 china var xhr = new ajax('post','demo.xml',parsexml,'xml'); //ajax is a class written by javascript which return responsexml object to parsexml function function parsexml(obj)//obj is the returnxml object now { if(!obj.documentelement) { alert("your browser does't support this script!"); return; }...
Communication between HTML and your extension - Archive of obsolete content
some of the events only apply to certain types of elements so i included trying to modify the result of the ajax request to be of the appropriate element type (img, which supports "onload," rather than span, which doesn't, for example).
Default Preferences - Archive of obsolete content
inside your file you set preferences using the pref() function: pref("name", "value") example: pref('extensions.defaultprefs.example.int', 1); pref('extensions.defaultprefs.example.float', 0.1); pref('extensions.defaultprefs.example.string', 'fadf'); pref('extensions.defaultprefs.example.bool', true); notice that unlike when you're reading preferences, writing default preferences uses the same function no matter the data type of the preference.
Deploying a Plugin as an Extension - Archive of obsolete content
for example: <em:updateurl><http://www.rhapsody.com/update.rdf></em:updateurl> this url specifies an rdf file that can be used to tell firefox that there are updates available for your extension.
Enhanced Extension Installation - Archive of obsolete content
it forces its items to be located in different places on the user's disk - some vendors wish to keep all of their installed content within c:\program files\foo\ for example.
Extension Packaging - Archive of obsolete content
in the apache http server, this can be done by adding the following directive to the configuration file or .htaccess: addtype application/x-xpinstall .xpi install extension files directly if you know the location of the application (if you are installing an extension as part of the application installer, for example), you can install the extension files directly to <appdir>/extensions/<extensionid>.
Hiding browser chrome - Archive of obsolete content
this is done, for example, by the about:addons page.
Jetpack Processes - Archive of obsolete content
sample code for example code, check out the unit tests.
Listening to events in Firefox extensions - Archive of obsolete content
in order to listen to events from all browsers, including those not currently being displayed, the following example can be used: var tabsprogresslistener = { // add tabs progress listener implementation here } gbrowser.addtabsprogresslistener(tabsprogresslistener); this lets you receive events related to all tabs.
Chapter 1: Introduction to Extensions - Archive of obsolete content
what you can do with extensions let's look at what features extensions can add, and some actual examples of extensions.
Introduction - Archive of obsolete content
in most cases we'll provide code samples that you can easily copy and adapt to your needs, as well as some working example extensions.
Local Storage - Archive of obsolete content
an nsifile doesn't necessarily represent an existing file, as in the previous examples.
Extensions support in SeaMonkey 2 - Archive of obsolete content
for example, if you overlay some chrome before the status bar, like this: <vbox id="browser-bottombox"> <something insertbefore="status-bar" /> </vbox> use the following technique to make your overlay work on both seamonkey 2 and firefox 3: <window id="main-window"> <vbox id="browser-bottombox" insertbefore="status-bar"> <something insertbefore="status-bar" /> </vbox> </window> thunderbird 3 ...
Signing an extension - Archive of obsolete content
here's an example of verisign: nss-certutil -m -n "verisign class 3 public primary certification authority" -t "c,c,c" -d .
Using Dependent Libraries In Extension Components - Archive of obsolete content
extensions with binary components sometimes need to depend on other shared libraries (for example, libraries provided by a third party).
Underscores in class and ID Names - Archive of obsolete content
for example, a function whose job is to "get the length of a string" might be called get_string_length, and a variable representing the number of people who voted republican might be voted_republican.
XUL user interfaces - Archive of obsolete content
for example, xul provides specialized windows like dialogs and wizards, as well as status bars, menus, tool bars, and even browsers.
Beginner tutorials - Archive of obsolete content
this technical note examines the use of underscores in css, and why they should be generally avoided in most circumstances.xml datathis page contains an example of how you can use css with xml data.xul user interfacesthis page illustrates mozilla's specialized language for creating user interfaces.
Creating a status bar extension - Archive of obsolete content
<?xml version="1.0"?> <rdf xmlns="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:em="http://www.mozilla.org/2004/em-rdf#"> <description about="urn:mozilla:install-manifest"> <em:id>status-bar-sample-1@example.com</em:id> <em:version>1.0</em:version> <em:type>2</em:type> <!-- front end metadata --> <em:name>status bar sample 1</em:name> <em:description>sample static status bar panel</em:description> <em:creator>my name</em:creator> <em:homepageurl>http://developer.mozilla.org/en/docs/creating_a_status_bar_extension</em:homepageurl> <!-- describe the firefox versions we suppor...
MozOrientation - Archive of obsolete content
r ff3.6+ if (!evt.gamma && !evt.beta) { evt.gamma = -(evt.x * (180 / math.pi)); evt.beta = -(evt.y * (180 / math.pi)); } // use evt.gamma, evt.beta, and evt.alpha // according to dev.w3.org/geo/api/spec-source-orientation } window.addeventlistener('deviceorientation', orientationhandler, false); window.addeventlistener('mozorientation', orientationhandler, false); example window.addeventlistener("mozorientation", dofunc, true); the example below simply displays the raw accelerometer data in the browser window as the events arrive.
chargingchange - Archive of obsolete content
example navigator.getbattery().then(function(battery) { console.log("battery charging?
chargingtimechange - Archive of obsolete content
example navigator.getbattery().then(function(battery) { console.log("battery charging time: " + battery.chargingtime + " seconds"); battery.addeventlistener('chargingtimechange', function() { console.log("battery charging time: " + battery.chargingtime + " seconds"); }); }); related events chargingchange dischargingtimechange levelchange ...
dischargingtimechange - Archive of obsolete content
example navigator.getbattery().then(function(battery) { console.log("battery discharging time: " + battery.dischargingtime + " seconds"); battery.addeventlistener('dischargingtimechange', function() { console.log("battery discharging time: " + battery.dischargingtime + " seconds"); }); }); related events chargingchange dischargingtimechange levelchange ...
levelchange - Archive of obsolete content
example navigator.getbattery().then(function(battery) { console.log("battery level: " + battery.level * 100 + " %"); battery.addeventlistener('levelchange', function() { console.log("battery level: " + battery.level * 100 + " %"); }); }); related events chargingchange chargingtimechange dischargingtimechange ...
Getting the page URL in NPAPI plugin - Archive of obsolete content
bool b2 = npn_getproperty( m_pnpinstance, locationobj, identifier, &variantvalue ); this code is just a rough example.
Environment variables affecting crash reporting - Archive of obsolete content
you can use this if you would rather use the jit debugger on windows with the symbol server, for example.
Working with BFCache - Archive of obsolete content
the script that's running when the window is frozen runs to completion, as it would if it were being closed, for example.
Autodial for Windows NT - Archive of obsolete content
whenever an internet address cannot be reached, because of a dns lookup failure for example, the system will try to dial.
How Mozilla finds its configuration files - Archive of obsolete content
usage: ./writemozprofile.pl < registry.xml >registry.dat a ready-to-use registry.dat file pointing to h:\mozilla a registry.xml file pointing to h:\mozilla an example of a prefs.js file (to put into the user's h:\mozilla directory).
How Thunderbird and Firefox find their configuration files - Archive of obsolete content
here is an example of what this may look like: [general] startwithlastprofile=1 [profile0] name=default isrelative=1 path=profiles/default.uda if you want to point this to a location of your choice (for example h:\thunderbird), you need to perform to changes: set isrelative to be 0 update the path to point to the desired place.
Locked config settings - Archive of obsolete content
and to decode mozilla.cfg files: moz-byteshift.pl -s -13 <mozilla.cfg >mozilla.cfg.txt example of an unencoded file: mozilla.cfg.txt.
Automatically Handle Failed Asserts in Debug Builds - Archive of obsolete content
as an example, consider the following failed assertion: assertion: no document: 'mdocument != nsnull', file d:/cvs-1.11.4/mozilla/content/xul/content/src/nsxulelement.cpp, line 3173 (note that i have my source tree in d:/cvs-1.11.4/mozilla) if you have a dword in hkcu\software\mozilla.org\windbgdlg\ named "d:/cvs-1.11.5/mozilla/content/xul/content/src/nsxulelement.cpp," (with the comma - matches are whole-word...
Bonsai - Archive of obsolete content
start at the main bonsai query page or seamonkey tree control page here are some example queries that will give you a taste of what bonsai is capable of: today's checkins to the mozilla source mainline.
Chromeless - Archive of obsolete content
for example, prism applications could not read/write files directly from/to the computer's file system.
Compiling The npruntime Sample Plugin in Visual Studio - Archive of obsolete content
add the npapi sdk include path (example : c:\npapi-sdk\headers) to project properties|(all configurations)|c++|general|additional include directories.
Conclusion - Archive of obsolete content
for example, you need to change chrome://navigator/content/navigator.xul to chrome://browser/content/browser.xul.
Making a Mozilla installation modifiable - Archive of obsolete content
if you have perl on your system, you can do this with the following command: perl -pi.orig -e 's/(jar:)|(\/[^.\/]+\.jar!)//g' chrome.rdf installed-chrome.txt for example, to convert the url jar:resource:/chrome/comm.jar!/content/necko/, change it to resource:/chrome/content/necko/.
Creating a Mozilla Extension - Archive of obsolete content
a mozilla extension is an installable enhancement to the mozilla browser that provides additional functionality (for example linky, which adds an item to the context menu for opening multiple links in a document or selection).
Getting Started - Archive of obsolete content
as an example, let's change the standard button.
Creating a hybrid CD - Archive of obsolete content
# example filename mapping file used by mkhybrid for hfs # # extn xlate creator type comment .hqx ascii 'sitx' 'text' "binhex file" .zip raw 'sitx' 'zip ' "zip file" .gz raw 'sitx' 'zip ' "gzip file" .tgz raw 'sitx' 'zip ' "tar.gz gzip file" .tar raw 'sitx' 'tarf' "tar file" .tif raw '8bim' 'tiff' "photoshop tiff image" ...
Creating a Skin for Mozilla - Archive of obsolete content
you cannot change what happens when the user right clicks on an image, but you can change the look of the right click menu (make it blue with pink polka dots, for example).
Creating a Skin for Firefox/Getting Started - Archive of obsolete content
as an example, let's change the standard button.
Installing Dehydra - Archive of obsolete content
to run dehydra manually using g++, add the -fplugin and -fplugin-arg-gcc_dehydra-script/-fplugin-arg-gcc_treehydra-script flags to specify the location of the plugin and the location of the analysis script: g++ -quiet -fplugin=$home/dehydra/gcc_dehydra.so -fplugin-arg-gcc_dehydra-script=$dehydra_script \ -fshort-wchar $cppfile -s -o /dev/null for example, in the tests directory created by the installation procedure, i can run a dehydra script 'a.js' on a mozilla file like this: g++ -quiet -fplugin=../gcc_dehydra.so \ -fplugin-arg=a.js -fshort-wchar -fpreprocessed \ /home/dmandelin/builds/dehydra-gcc/browser/app/nsbrowserapp.ii -o /dev/null the -fshort-wchar is required for running against firefox, but not necessarily for other codebases.
Dehydra - Archive of obsolete content
documentation installing dehydra download, installation and dependency info for dehydra using dehydra examples for getting started writing analysis scripts.
Download Manager improvements in Firefox 3 - Archive of obsolete content
examples monitoring downloads an example showing how to use the new download manager apis to create a download log window that shows all past and present downloads and their status, including the start and end times of the downloads, the download speed, and more.
Drag and drop events - Archive of obsolete content
you can see an example of these events in action here: view source view example see also ^: drag and drop html 5 working draft: drag and drop nsidragservice ...
Downloading Nightly or Trunk Builds - Archive of obsolete content
for example "shiretoko" is used for firefox 3.5.
Layout FAQ - Archive of obsolete content
inline(span)(0)@035ffa04 next=035ffc48 next-continuation=035ffc48 {0,7,330,285} [content=0359ed50] [sc=035ff990]< text(0)@035ffa8c[0,4,t] next=035ffb1c {0,0,330,285} [state=41600020] sc=035ffa3c pst=:-moz-non-element< "\nabc" > frame(br)(1)@035ffb1c {330,225,0,0} [state=00000020] [content=035aebf0] > > the linebox is used to contain everything on a single line: example how do you fix inconsistent float behavior in firefox involving a two column layout using display:table and floating div elements?
Code snippets - Archive of obsolete content
"); function getpath(path) { let r = new resource(weave.service.storageurl + path); let g = r.get(); return [g, r]; }; let [g, r] = getpath("meta/global"); r.put(g); delete and restore a record components.utils.import("resource://services-sync/main.js"); components.utils.import("resource://services-sync/resource.js"); components.utils.import("resource://services-sync/record.js"); // for example: let id = "iasokuozpixz" let collection = "bookmarks"; let resource = new resource(weave.service.storageurl + collection + "/" + id); let del = new cryptowrapper(collection, id); del.deleted = true; del.encrypt(); // save the old value.
Syncing custom preferences - Archive of obsolete content
for example, if your add-on had a pref called extension.frobnaz.foobar, to have it synced, create a bool preference called services.sync.prefs.sync.extension.frobnaz.foobar and set it to true.
Isp Data - Archive of obsolete content
getting started first take a look at the number of examples available: http://infosec.ufl.edu/tbird/gatorlink.xml mailnews/base/ispdata/aol.rdf see the thunderbird isp hooks for more details.
importUserCertificates - Archive of obsolete content
for example, "john smith's verisign class 3 digital id" or "john smith's ford id certificate".
Basics - Archive of obsolete content
urlurl to be openedstring jetpack.tabs.open("http://www.example.com/"); ...
Me - Archive of obsolete content
ArchiveMozillaJetpackMetaMe
inside the function, this is the jetpack's content.function example jetpack.me.onfirstrun(function(){ jetpack.notifications.show("oh boy, i'm installed!");}); ...
Settings - Archive of obsolete content
here is an example manifest definition: var manifest = { settings: [ { name: "twitter", type: "group", label: "twitter", settings: [ { name: "username", type: "text", label: "username" }, { name: "password", type: "password", label: "password" } ] }, { name: "facebook", type: "group", label: "facebook", settings: [ { name: "...
Settings - Archive of obsolete content
here is an example manifest definition: var manifest = { settings: [ { name: "twitter", type: "group", label: "twitter", settings: [ { name: "username", type: "text", label: "username" }, { name: "password", type: "password", label: "password" } ] }, { name: "facebook", type: "group", label: "facebook", settings: [ { name: "...
Clipboard Test - Archive of obsolete content
the api is fairly straightforward; examples can be found here.
Tabs - Archive of obsolete content
ArchiveMozillaJetpackUITabs
urlurl to be openedstring jetpack.tabs.open("http://www.example.com/"); blah(lengthstringfocusedstringtostringstringpopstringpushstringreversestringshiftstringsortstringsplicestringunshiftstring)this is some default text lengththe number of open tabsstring focusedthe current tab in your browserstring tostringstuffstring popstuffstring pushstuffstring reversestuffstring shiftstuffstring sortstuffstring splicestuffstring unshiftstuffstring onready()when the ...
slideBar - Archive of obsolete content
content for the featurehtml/xml urlurl to load content for the featureuri widthwidth of the content area and the selected slide sizeint persistdefault slide behavior when being selectedbool autoreloadautomatically reload content on selectbool onclickcallback when the icon is clickedfunction onselectcallback when the feature is selectedfunction onreadycallback when featured is loadedfunction an example: jetpack.slidebar.append({ url: "http://mozilla.com", width: 150, onclick: function(slide){ slide.icon.src = "chrome://branding/content/icon48.png"; }}); ...
statusBar - Archive of obsolete content
example jetpack.statusbar.append({ html: 'hello <i>world</i>!', onready: function(widget){ $(widget).click(function(){ jetpack.tabs.open("http://www.jogkey.de"); }); } }); ...
Jetpack - Archive of obsolete content
get started visit the getting started tutorial download the add-on sdk (formerly called the jetpack sdk) documentation check out the documentation, including tutorials, examples, guides, and api reference join the jetpack community follow jetpack on the mozilla add-ons blog report a bug check out the open bugs discuss jetpack grab the source code join us in #jetpack on irc.mozilla.org ...
Metro browser chrome tests - Archive of obsolete content
for example, to run a specific test the command would be: ./mach mochitest-metro browser/metro/base/tests/mochitest/(testfile) writing browser chrome tests metro browser chrome tests make use of a common framework for defining and running tests.
Monitoring downloads - Archive of obsolete content
since this is a simple example, it's a one-shot log window; it doesn't monitor for further changes to the log.
Mozilla Crypto FAQ - Archive of obsolete content
this form of licensing was chosen to allow the released personal security manager and network security services source code to be used in as many contexts as possible; for example, the psm and nss code can be used in mozilla under mpl terms, and can also be used in gnu and other projects under gpl terms.
NSC_SetPIN - Archive of obsolete content
return value ckr_ok examples #include <assert.h> see also fc_setpin ...
How to Write and Land Nanojit Patches - Archive of obsolete content
see https://bugzilla.mozilla.org/show_bug.cgi?id=529900 for an example.
Plug-n-Hack - Archive of obsolete content
for example, to configure a browser to use an intercepting proxy that can handle https traffic, the user must typically: configure their browser to proxy via the tool configure the tool to proxy via their corporate proxy import the tool’s ssl certificate into their browser if any of these steps are carried out incorrectly then the browser will typically fail to connect to any website – debugging ...
Porting NSPR to Unix Platforms - Archive of obsolete content
i use the netbsd port i recently received as an example to illustrate the mechanical part of the porting process.
Configuration - Archive of obsolete content
example here is an example of a webapp.ini profile: [parameters] name=gmail id=google.mail@developer.mozilla.org uri=https://mail.google.com icon=gmail status=yes location=no sidebar=no navigation=no ...
Installer - Archive of obsolete content
one interesting side effect is that after this change, you can select a link to a .webapp file in a web page and you get it run by prism - in ie this runs anywhere, but this won't work in firefox unless the webapp is being issued with an appropriate mime type on the server: application/x-webapp works (see an example ).
Proxy UI - Archive of obsolete content
for example, firefox 3: [ ] no proxy [ ] auto-detect proxy settings for this network [ ] manual proxy configuration: [ ] automatic proxy configuration url: behavior default value: "no proxy" is selected all other "type" radio buttons are enabled, but not selected.
Running Windows Debug Builds Downloaded From Tinderbox - Archive of obsolete content
to run tests of the tests package you can, for example, run the reftests as follows: python reftest/runreftest.py --appname=firefox/firefox.exe --utility-path=bin --extra-profile-file=bin/plugins reftest/tests/layout/reftests/reftest.list ...
Safely loading URIs - Archive of obsolete content
for example, loading some file: uris can hang the browser or even crash the operating system in some cases.
open - Archive of obsolete content
examples example: using open in the following example, myfile is a file object: myfile.open("read", "text"); see also ...
Table Layout Regression Tests - Archive of obsolete content
for example ac_add_options --enable-extensions=all.
Tamarin Acceptance Test Template - Archive of obsolete content
addtestcase is a function that is defined * in shell.as and takes three arguments: * - a string representation of what is being tested * - the expected result * - the actual result * * for example, a test might look like this: * * var helloworld = "hello world"; * * addtestcase( * "var helloworld = 'hello world'", // description of the test * "hello world", // expected result * helloworld ); // actual result * */ // add your tests here var helloworld = "hello world"; addtestcase( "var helloworld = 'hello world'", "hello world", hellowo...
Actionscript Performance Tests - Archive of obsolete content
for example if the mean is 100 and the 95% confidence interval is 2%, 95% of the expected values should fall between 98 and 102.
TraceVis - Archive of obsolete content
the blog post linked above has examples of this output and how to analyze it.
Using gdb on wimpy computers - Archive of obsolete content
here's an example: [blizzard@gunhead mozilla]$ cd dist/bin/ [blizzard@gunhead bin]$ ./mozilla -g .//run-mozilla.sh -g ./mozilla-bin mozilla_five_home=/home/blizzard/src/mozilla/mozilla/dist/bin ld_library_path=/home/blizzard/src/mozilla/mozilla/dist/bin shlib_path=/home/blizzard/src/mozilla/mozilla/dist/bin libpath=/home/blizzard/src/mozilla/mozilla/dist/bin moz_program=./mozilla-bin ...
Using Breakpoints in Venkman - Archive of obsolete content
the onflipx function in figure 1, for example, uses the variable newsign to figure out what image to use for the fish.
Venkman - Archive of obsolete content
documentation venkman introduction an overview and some practical examples of using the javascript debugger in web development.
DOM Interfaces - Archive of obsolete content
no return value example the following snippet checks to see if any anonymous child of "element" is itself an element.
Event Handlers - Archive of obsolete content
examples of common keys in the list are shift and control.
XBL - Archive of obsolete content
for example, names of the elements are different.
Creating XPI Installer Modules - Archive of obsolete content
in the package you create in this tutorial, for example, all of the resources are located under the content/ subdirectory, but they could just as easily have been archived directly at the top--along with skin and locale resources, if you wanted.
Mac stub installer - Archive of obsolete content
for example, see the xpcom section that lists all the shared libraries as seen in dist.
Unix stub installer - Archive of obsolete content
for example, see the xpcom section that lists all the shared libraries as seen in dist.
Windows stub installer - Archive of obsolete content
for example, see the xpcom section that lists all the shared libraries as seen in dist.
File.macAlias - Archive of obsolete content
file.macalias in this example, a mac alias is created for software (applecd audio player) that is installed locally.
File.windowsShortcut - Archive of obsolete content
file.windowsshortcut in this example, the windowsshortcut method is used to add a shortcut in the program directory ("program" is a keyword for the directory in which the program itself is installed, for example, c:\program files\netscape\netscape 6\" on windows) to windows software (misc.exe) that is installed in the "windows" directory.
InstallTrigger.installChrome - Archive of obsolete content
when a user clicks the link "install the new blue theme" in the example below, xpinstall downloads, registers, and installs the theme contained in newblue.xpi to the user's profile directory.
InstallTrigger.startSoftwareUpdate - Archive of obsolete content
installtrigger.startsoftwareupdate this is a very simple example of the installtrigger object's principal method, startsoftwareupdate, which takes a string representing the path to the xpi and installs that xpi on the local machine.
Windows Install - Archive of obsolete content
windows install example this example shows the installation of a xpi in which user profile information is contained.
dirGetParent - Archive of obsolete content
example f = getfolder("program", "mynewdirectory"); err = file.dircreate(f); err = file.getparent(f) // returns "program" ...
execute - Archive of obsolete content
example f = getfolder("program", "mytexteditor.exe"); err = file.execute(f, "myfile.txt"); // indicates that 'myfile.txt' will be // opened in the editor ...
exists - Archive of obsolete content
example f = getfolder( "program", "sample.txt" ); if ( file.exists(f) ) // do something with the file ...
isFile - Archive of obsolete content
example f = getfolder( "program", "sample.txt" ); if ( file.isfile(f) ) // the object represents a file ...
macAlias - Archive of obsolete content
example see file.macalias in the script examples chapter.
modDate - Archive of obsolete content
example f = getfolder("program"); filesource = getfolder(f, "myfile.txt"); err = file.moddate(filesource); see moddatechanged for an example of comparing the dates of two files.
move - Archive of obsolete content
example source = getfolder("program", "file.txt"); dest = getfolder("chrome"); err = file.move(source, dest); ...
windowsGetShortName - Archive of obsolete content
example flongfilepath = getfolder(fprogram, "longfilename.file"); sshortfilepath = file.windowsgetshortname(flongfilepath); if(sshortfilepath) { // do something } ...
windowsRegisterServer - Archive of obsolete content
example filecdtool = getfolder("file:///", faod + "cdtool.dll"); err = file.windowsregisterserver(filecdtool); ...
windowsShortcut - Archive of obsolete content
example see file.windowsshortcut in the script examples chapter.
compareTo - Archive of obsolete content
llowing constants are defined and available for checking the value returned by compareto: installversion.major_diff installversion.minor_diff installversion.rel_diff installversion.bld_diff installversion.equal installversion.major_diff_minus installversion.minor_diff_minus installversion.rel_diff_minus installversion.bld_diff_minus example this code uses the compareto method to determine whether or not version 3.2.1 of the royal airways software has been previously installed: existingvi = installtrigger.getversion("/royalairways/royalsw"); if ( existingvi.compareto("3.2.1") <= 0 ) { // ...
toString - Archive of obsolete content
to get the version number out of an installversion object in order to compare it with other versions, you can call tostring() and get back the version as a string in the format "maj.min.rev.bld." example var vi = new installversion(); vi.init("999.888.777.666"); //random string vistring = vi.tostring(); ...
addFile - Archive of obsolete content
example var xpisrc = "file.txt"; initinstall("adding a file", "addfile", "1.0.1.7", 1); f = getfolder("program"); setpackagefolder(f); addfile(xpisrc); if (0 == getlasterror()) performinstall(); else cancelinstall(); ...
cancelInstall - Archive of obsolete content
example use the following code to abort or to finalize an installation, based on a variable you set earlier in your code: initinstall("royal airways tripplanner","/royalairways/ tripplanner","1.0.0.0"); ...
confirm - Archive of obsolete content
the following examples show the result of calling confirm() with three buttons 0='a', 1='b' and 2='c'.
execute - Archive of obsolete content
the following line, for example, passes the "-c" command-line parameter to the executable: err = file.execute(myfile, "-c", true); when you want to pass more than one parameter to the executable itself, however, you must format the args string in a particular way so that the parameters can be broken up and passed separately as required.
getLastError - Archive of obsolete content
example the following example calls getlasterror after a series of addfile calls: addfile("npplug", ...); addfile("/ms/shared/ctl3d.dll", ...); addfile("/nethelp/royalplug/royalhelp.html",...); err = getlasterror(); ...
getWinProfile - Archive of obsolete content
example to edit the win.ini file, you would create a winprofile object with this call: var mywinprofileobj = getwinprofile (getfolder("windows"), "win.ini"); ...
performInstall - Archive of obsolete content
example use the following code to abort or to finalize an installation, based on a variable you set earlier in your code: initinstall("royal airways tripplanner", "/royalairways/tripplanner", "1.0.0.0"); ...
resetError - Archive of obsolete content
example to reset the last error code to zero: reseterror(); ...
Properties - Archive of obsolete content
for example, the value could begin with "windows", "macintosh" or "x11" (for unix/linux).
getString - Archive of obsolete content
example to get the name of the wallpaper file from the desktop section of the win.ini file, use this call: ini = getwinprofile (getfolder("windows"), "win.ini"); var wallpapervalue = ini.getstring ("desktop", "wallpaper"); ...
writeString - Archive of obsolete content
example to set the name of the wallpaper file from the desktop section of the win.ini file, use this call: ini = getwinprofile (getfolder("windows"), "win.ini"); ini.writestring ("desktop", "wallpaper", "newpathname"); ...
enumKeys - Archive of obsolete content
the following example shows how to use enumkeys to find the plugins subdirectory below the various mozilla-based browser installations.
enumValueNames - Archive of obsolete content
the following brief example retrieves a key value using this method.
isKeyWritable - Archive of obsolete content
example winreg = getwinregistry(); if ( winreg != null ) { winreg.setrootkey ( winreg.hkey_local_machine ); if(winreg.iskeywritable("software")) { //iskeywritable returned true } else { //iskeywritable returned false } ...
keyExists - Archive of obsolete content
example winreg = getwinregistry(); if ( winreg != null ) { winreg.setrootkey( winreg.hkey_local_machine); if(winreg.keyexists("software\\mozilla")) { //keyexists returned true } else { //keyexists returned false } } ...
setRootKey - Archive of obsolete content
the values you can use are: hkey_classes_root hkey_current_user hkey_local_machine hkey_users example to use the hkey_users section, use these statements: winreg = getwinregistry(); winreg.setrootkey(winreg.hkey_users); ...
valueExists - Archive of obsolete content
example winreg = getwinregistry(); if ( winreg != null ) { winreg.setrootkey( winreg.hkey_local_machine); if(winreg.valueexists("software\\mozilla", "value name")) { //valueexists returned true } else { //valueexists returned false } } ...
XPInstall API reference - Archive of obsolete content
ethods createkey deletekey deletevalue enumkeys enumvaluenames getvalue getvaluenumber getvaluestring iskeywritable keyexists setrootkey setvalue setvaluenumber setvaluestring valueexists winregvalue constructor other information return codes see complete list examples trigger scripts and install scripts code samples file.macalias file.windowsshortcut install.adddirectory install.addfile installtrigger.installchrome installtrigger.startsoftwareupdate windows install ...
XPInstall - Archive of obsolete content
learn xpi installer scripting by example this article uses the installer script from browser.xpi install package as the basis for discussing xpi installations in general.
autocompletepopup - Archive of obsolete content
examples how to enable autocomplete (form fill) in a browser element.
command - Archive of obsolete content
example <command id="cmd_openhelp" oncommand="alert('help');"/> <button label="help" command="cmd_openhelp"/> <button label="more help" command="cmd_openhelp"/> see also command element, oncommand and commandset ...
commandupdater - Archive of obsolete content
for example, since the cut command is only valid when something is selected, a command updater might be used when the select event occurs.
crop - Archive of obsolete content
ArchiveMozillaXULAttributecrop
for example, for a menuitem in a menu you can add the following css rule when you want to use the value none: menupopup > menuitem, menupopup > menu { max-width: none; } ...
cycler - Archive of obsolete content
this is used, for example, in a mail window, for a column that indicates that the message is read or unread with a small mark in the cell.
defaultset - Archive of obsolete content
for example, back-button,forward-button,print-button.
dlgtype - Archive of obsolete content
for example, if the dlgtype is set to accept, the button will replace the dialog box's accept button, which is usually labeled ok.
href - Archive of obsolete content
ArchiveMozillaXULAttributehref
<label href="http://example.com" class="text-link" value="click here to go to example.com"/> ...
id - Archive of obsolete content
ArchiveMozillaXULAttributeid
example <button id="foo" label="click me" oncommand="dosomething()"/> <script> function dosomething(){ var mybutton = document.getelementbyid('foo'); mybutton.setattribute('label','the button was pressed'); } </script> a more abstract version of the above would be a <button id="foo" label="click me" oncommand="setwidgetlabel(this, 'i was pressed')"/> <script> function setwidgetlabel(idname, newcaption){ document.getelementbyid( idname.id ).setattribute('label',newcaption) } </script> not specifying the id attribute for a window or a prefwind...
image - Archive of obsolete content
example <menuitem label="foo" class="menuitem-iconic" image="something.png"/> see also image element ...
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('mycheckbo...
menuitem.name - Archive of obsolete content
example <toolbox> <menubar id="planets-menubar"> <menu id="planet-menu" label="planet"> <menupopup> <menuitem id="jupiter" label="jupiter" type="radio" name="planet"/> <menuitem id="saturn" label="saturn" type="radio" name="planet" checked="true"/> <menuitem id="uranus" label="uranus" type="radio" name="planet"/> </menupopup> </menu> </menubar> </toolbox> see also name and menus in the xul tutorial ...
mousethrough - Archive of obsolete content
in the following example, the image appears above the button, yet the mousethrough attribute specified on the image causes mouse events to be ignored on the image and instead fall through to the button.
onchange - Archive of obsolete content
window, document, or any of the functions/objects/variables bound to the window object event object example <?xml version="1.0"?> <?xml-stylesheet href="chrome://global/skin/" type="text/css"?> <window id="findfile-window" title="find files" orient="horizontal" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <script type="text/javascript"> function myfunction(e){ /* do something cool here or just say the below */ alert(e.target.nodename); ...
onclick - Archive of obsolete content
example <image src="hello.png" onclick="alert('hi')"/> see also click dom element ...
oncommand - Archive of obsolete content
example 1: in-line code <button label="click me" oncommand="alert('hi')"/> example 2: function with source argument <button label="click me" oncommand="dosomeprocessing(event.target)"/> and here is the definition of the function: function dosomeprocessing(source) { alert("source: " + source); return true; } see also command element ...
oninput - Archive of obsolete content
example <!-- this sets the label's text to the textbox value on each keystroke.
onpopuphidden - Archive of obsolete content
example: <menupopup id="top" onpopuphidden="console.log('the onpopuphidden method of id=top was called.');"> <menuitem label="item 1"/> <menuitem label="item 2"/> <menu id="submenu1" label="submenu 1"> <menupopup id="submenu1-popup"> <menuitem label="submenu1 item 1"/> <menuitem label="submenu1 item 2"/> </menupopup> </menu> <menu id="submenu2" label="submenu 1"> <menupopup id="submenu2-popup"> <menuitem label="submenu2 item 1"/> <menuitem label="submenu2 it...
panel.flip - Archive of obsolete content
for example, if the menu doesn't have room to open downward, it flips to open upward instead; this is a vertical flip.
panel.type - Archive of obsolete content
for example, the site identity panel that appears when you click on the favicon in the url bar in firefox is an arrow panel: note: the arrow will draw as long as the panel doesn't overlap the anchor.
popup.position - Archive of obsolete content
for more details, including examples, please see popup positioning see also position ...
popupanchor - Archive of obsolete content
panchortype: one of the values belowpopupanchor is an optional attribute for specifying where popup content should be anchored on the element.noneno anchortopleftanchor to the top left cornertoprightanchor to the top right cornerbottomleftanchor to the bottom left cornerbottomrightanchor to the bottom right cornersyntax<element popupanchor="none | topleft | topright | bottomleft | bottomright" /> example<element id="edit-context" popup="editor-popup" popupanchor="topleft" popupalign="bottomright" /> notesthe popupanchor attribute can be used to specify that the popup content should come up anchored to one of the four corners of the content object (e.g., the button popping up the content).
preference.name - Archive of obsolete content
for example, the browser's home page is set with the preference browser.startup.homepage.
reserved - Archive of obsolete content
example here, the command to open a new browser window is reserved: <command id="cmd_newnavigator" oncommand="openbrowserwindow()" reserved="true"/> if the keyboard shortcut for that is accel-t, then this code will not work as expected, as compared to when it is run from web content: document.addeventlistener("keydown", handlekey, true); function handlekey(event) { // listen for the "new tab" shor...
right - Archive of obsolete content
for example, using right="-80" causes the stack to be enlarged 80 pixels to the right and the element's right edge to be at the same location as the right edge of the stack.
showcaret - Archive of obsolete content
examples <iframe id="content-body" src="http://www.mozilla.org/" showcaret="true"/> <browser src="http://www.mozilla.org" flex="1" showcaret="true"/> ...
sortResource - Archive of obsolete content
the key should be the full uri of the rdf resource to sort by, for example 'http://home.netscape.com/nc-rdf#name'.
src - Archive of obsolete content
ArchiveMozillaXULAttributesrc
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 ...
statustext - Archive of obsolete content
example <!-- sets the status message when mouse is over buttons --> <button label="connect" statustext="connect to remote server" onmouseover="setstatusmessage(this)" onmouseout="clearstatusmessage()"/> <button label="ping" statustext="ping the server" onmouseover="setstatusmessage(this)" onmouseout="clearstatusmessage()"/> <statusbar> <statusbarpanel id="mystatuspanel" label="" flex="1"/> <spacer flex="1"/> </s...
toolbarbutton.type - Archive of obsolete content
examples: type value <toolbarbutton > menu menu-button checkbox radio see also type ...
treecol.type - Archive of obsolete content
here is an example css style using the current theme's checkboxes: treechildren::-moz-tree-checkbox { /* unchecked checkbox treecells.
windowtype - Archive of obsolete content
this might be used, for example, to distinguish between a browser window and an editor window.
ValueChange - Archive of obsolete content
the valuechange event is executed when the value of an element, <progress> for example, has changed.
Uploading and Downloading Files - Archive of obsolete content
function uploadput(posturl, filepath) { var req = new xmlhttprequest(); req.open("put", posturl); req.setrequestheader("content-type", "text/plain"); req.onload = function(event) { alert(event.target.responsetext); } req.send(new file(filepath)); } in this example, a new input stream is created for a file, and is passed to the xmlhttprequest's send method.
onFindAgainCommand - Archive of obsolete content
you should specify true as the input parameter to perform a "find previous" operation, or false to perform a "find next." example typically, you'll simply bind this method to your "find next" and "find previous" commands, like this: <command name="cmd_find_previous" oncommand="gfindbar.onfindagaincommand(true);"/> <command name="cmd_find_next" oncommand="gfindbar.onfindagaincommand(false);"/> ...
startFind - Archive of obsolete content
example typically, you'll simply bind this method to your "find" command, like this: <command name="cmd_find" oncommand="gfindbar.startfind(gfindbar.find_normal);"/> ...
addTab - Archive of obsolete content
ArchiveMozillaXULMethodaddTab
see code snippets: tabbed browser for examples.
appendItem - Archive of obsolete content
example <script language="javascript"> function additemstolist(){ var list = document.getelementbyid('mymenulist'); // add item with just the label list.appenditem('one'); // add item with label and value list.appenditem('two', 999); // select the first item list.selectedindex = 0; } </script> <button label="add items" oncommand="additemstolist()"/> <menulist id="mymenulist"> <menupopup/> </menulist> see also insertitemat() removeitemat() ...
appendNotification - Archive of obsolete content
example: function testnotificationboxwithbuttons() { //create some common variables if they do not exist.
getNextItem - Archive of obsolete content
this example will return the item two rows after someitem: getnextitem ( someitem, 2 ); ...
getPreviousItem - Archive of obsolete content
this example will return the item five rows before someitem: getpreviousitem ( someitem, 5 ); ...
getSelectedItem - Archive of obsolete content
the item index is zero-based, thus this example will return the first selected item: getselecteditem(0).
insertItemAt - Archive of obsolete content
note: you cannot insert an item to an index that does not exist, eg: trying to insert an item at the end with element.getrowcount() + 1 example <!-- this example inserts at the selected item or appends, then selects the newly created item --> <script language="javascript"> function insertitemtolist(){ var mylistbox = document.getelementbyid('mylistbox'); // create a date to get some labels and values var somedate = new date(); if(mylistbox.selectedindex == -1){ // no item was selected in list so append to the end ...
showPopup - Archive of obsolete content
this is what you might do to show a popup below a button, for example.
Other Resources - Archive of obsolete content
links creating applications with mozilla xul periodic table online example of nearly every xul element.
PopupKeys - Archive of obsolete content
for example, focusing a textbox and opening the textbox's context menu keeps the focus within the textbox.
builder - Archive of obsolete content
for example, given a reference to a tree mytree, this example will rebuild its content: mytree.builder.rebuild(); ...
controllers - Archive of obsolete content
example <window id="controller-example" title="controller example" onload="init();" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <script> function init() { var list = document.getelementbyid("thelist"); var listcontroller = { supportscommand : function(cmd){ return (cmd == "cmd_delete"); }, iscommandenabled : function(cmd){ if (cmd == "cmd_delete") return (list.selecteditem != null); return false; }, docommand : function(cmd){ list.
itemCount - Archive of obsolete content
example var bucket = document.getelementbyid("attachmentbucket"); if(bucket.itemcount == 0) { dump("\n\n no attachments \n\n"); } else { dump("\n\n attachment exists \n\n"); } ...
name - Archive of obsolete content
ArchiveMozillaXULPropertyname
for example, the browser's home page is set with the preference browser.startup.homepage.
tag - Archive of obsolete content
ArchiveMozillaXULPropertytag
for example, by using a value of treechildren, the condition will only match when placing elements directly inside a treechildren tag.
RDF Query Syntax - Archive of obsolete content
you may find this a bit confusing, but this should become clearer later with more specific and practical examples.
Template Guide - Archive of obsolete content
basics of xul templates introduction rule compilation rdf template syntax result generation rdf query syntax actions recursive generation simple example bindings additional navigation filtering static content simple query syntax containment properties xml template syntax xml templates xml assignments sql template syntax sqlite templates common template syntax attribute substitution multiple rules using recursive templates building menus with templates special condition tests multiple queries using multiple queries to generate more results building trees with templates building trees building hierarchical trees template modifications template builder interface template and tree listeners rdf modifications additional topics sorting ...
Creating toolbar buttons (Customize Toolbar Window) - Archive of obsolete content
just add code like this to your overlay: <toolbarpalette id="browsertoolbarpalette"> <toolbarbutton id="myextension-button" class="toolbarbutton-1" label="&toolbarbutton.label;" tooltiptext="&toolbarbutton.tooltip;" oncommand="myextension.ontoolbarbuttoncommand(event);"/> </toolbarpalette> notes: the id of the palette (browsertoolbarpalette in the example) depends on the window (the parent window of the toolbar you wish to insert a button).
Toolbars - Archive of obsolete content
custom toolbar button another example of how to create a toolbar button, complete with a sample extension you can download and try.
Accesskey display rules - Archive of obsolete content
and also note that there are no spaces between the original labels and accesskey text in the above japanese example.
Using multiple DTDs - Archive of obsolete content
but there are situations where you want to use multiple dtds, for example to localize common widgets used in all your xul files, additionally to the ones specific to the file.
Widget Cheatsheet - Archive of obsolete content
see the periodic table of xul for more examples.
Window icons - Archive of obsolete content
older versions to support older applications, such as firefox 1.0, you need to copy the icons to app_dir/chrome/icons/default manually on the first start (example code).
XULBrowserWindow - Archive of obsolete content
see hiding browser chrome for details and an example.
XUL element attributes - Archive of obsolete content
the key should be the full uri of the rdf resource to sort by, for example 'http://home.netscape.com/nc-rdf#name'.
Accessibility/XUL Accessibility Reference - Archive of obsolete content
1"> <label control="butwrap1"> <!--wrapped label--> </label> </button> <button id='butwrap2'> <label control="butwrap2" value="<!--this-->" /> <label control="butwrap2" value="is" /> <label control="butwrap2" value="a" /> <label control="butwrap2" value="button" /> </button> <button image="images/img.xbm" tooltiptext="<!--button text-->"/> note that in the third example, only the first label is read browser jaws 7.10 issues to use a browser element with html, the type="content" attribute should be specified.
param - Archive of obsolete content
ArchiveMozillaXULparam
« xul reference home [ examples | attributes | properties | methods | related ] for sql templates, used to bind values to parameters specified within an sql statement.
queryset - Archive of obsolete content
« xul reference home [ examples | attributes | properties | methods | related ] a container for query elements when more than one query is used.
spinbuttons - Archive of obsolete content
« xul reference home [ examples | attributes | properties | methods | related ] spin buttons are two arrows, one to increase a value and one to decrease a value.
treecell - Archive of obsolete content
« xul reference home [ examples | attributes | properties | methods | related ] a single cell in a tree.
wizardpage - Archive of obsolete content
« xul reference home [ examples | attributes | properties | methods | related ] this element defines a page in a wizard.
Application Update - Archive of obsolete content
use what you need, %product%,%version%,%build_id%,%channel% for example pref("app.update.url", "https://yourserver.net/update/3/%product%/%version%/%build_id%/%build_target%/%locale%/%channel%/%os_version%/%distribution%/%distribution_version%/update.xml"); // url user can browse to manually if for some reason all update installation // attempts fail.
Building XULRunner - Archive of obsolete content
for example, to build xulrunner with the top of the tree: hg clone http://hg.mozilla.org/mozilla-central/ src cd src echo ".
Deploying XULRunner - Archive of obsolete content
an example of one such solution may be found in the article: creating a windows inno setup installer for xulrunner applications.
Using LDAP XPCOM with XULRunner - Archive of obsolete content
actually, the ldap interfaces are available (for exemple, components.interfaces.nsildapconnection is not null), but the components can't be loaded (for example, components.classes["@mozilla.org/network/ldap-connection;1"] is null).
Opening a Link in the Default Browser - Archive of obsolete content
this can be done using the nsiexternalprotocolservice interface: // first construct an nsiuri object using the ioservice var ioservice = components.classes["@mozilla.org/network/io-service;1"] .getservice(components.interfaces.nsiioservice); var uritoopen = ioservice.newuri("http://www.example.com/", null, null); var extps = components.classes["@mozilla.org/uriloader/external-protocol-service;1"] .getservice(components.interfaces.nsiexternalprotocolservice); // now, open it!
XULRunner tips - Archive of obsolete content
see firefox for example.
Using SOAP in XULRunner 1.9 - Archive of obsolete content
(there is a diff below.) you'll need: sasoapclient.js saxmlutils.js making a soap call var url = 'http://example.com/soap/'; var ns = 'http://example.com/soap/namespace'; var method = 'foo'; var params = { 'foo': 'bar', 'baz': 'bang' }; var callback = function(obj) { components.utils.reporterror(obj.tosource()); }; soapclient.proxy = url; var body = new soapobject(method); body.ns = ns; for (var k in params) { body.appendchild(new soapobject(k).val(params[k])); } var req = new soaprequest(u...
toolkit.defaultChromeFeatures - Archive of obsolete content
type: string specified by: default prefs of xulrunner applications default: "chrome,dialog=no,all" example: pref("toolkit.defaultchromefeatures", "chrome,resizable=no,dialog=no"); the toolkit.defaultchromefeatures preference allows simple xulrunner-based applications to specify what features are passed to window.open() when the main application window is opened.
toolkit.defaultChromeURI - Archive of obsolete content
type: string specified by: default prefs of xulrunner applications default: none example: pref("toolkit.defaultchromeuri", "chrome://myapp/content/"); the toolkit.defaultchromeuri preference allows simple xulrunner-based applications to open a new window when the application is launched.
calICalendarView - Archive of obsolete content
related interfaces calicalendarviewcontroller calidecoratedview example code both calendar-multiday-view and calendar-month-view show examples, albeit complex, of implementations of this interface.
calICalendarViewController - Archive of obsolete content
related interfaces calicalendarview calidecoratedview example code var myviewcontroller = { queryinterface: function(aiid) { if (!aiid.equals(components.interfaces.calicalendarviewcontroller) && !aiid.equals(components.interfaces.nsisupports)) { throw components.results.ns_error_no_interface; } return this; }, createnewevent: function (acalendar, astarttime, aendtime) { // if we're given ...
calIFileType - Archive of obsolete content
related interfaces caliimporter caliexporter example code see calhtmlexport.js.
Mozprocess - Archive of obsolete content
basic usage: process = processhandler(['command', '-line', 'arguments'], cwd=none, # working directory for cmd; defaults to none env={}, # environment to use for the process; defaults to os.environ ) exit_code = process.waitforfinish(timeout=60) # seconds see an example in https://github.com/mozilla/mozbase/b...profilepath.py processhandler may be subclassed to handle process timeouts (by overriding the ontimeout() method), process completion (by overriding onfinish()), and to process the command output (by overriding processoutputline()).
Mozprofile - Archive of obsolete content
example: from mozprofile import firefoxprofile # create new profile to pass to mozmill/mozrunner profile = firefoxprofile(addons=["adblock.xpi"]) setting preferences preferences can be set in several ways: using the api: you can pass preferences in to the profile class's constructor: obj = firefoxprofile(preferences=[("accessibility.typeaheadfind.flashbar", 0)]) using a json blob file: mozprofile --...
Mozrunner - Archive of obsolete content
example api usage: from mozrunner import firefoxrunner # start firefox on a new profile runner = firefoxrunner() runner.start() ...
reftest opportunities files - Archive of obsolete content
for example, if some html is in an unexpected place and is supposed to be ignored, then we can match against an html file that is missing that extra mark-up.
Format - Archive of obsolete content
this is an example of what a newsgroup summary should look like when completed.
2006-11-17 - Archive of obsolete content
how to access xyz.properties items more detail and code examples are provided in the posting.
Extentsions FAQ - Archive of obsolete content
can anyone recomment the best way to implement unit tests for an extension and are there any unit-tested extensions examples?
2006-12-01 - Archive of obsolete content
http://www.whitebeam.org is an example of open source server side javascript.
2006-10-20 - Archive of obsolete content
for example improving the left pane, so that user can switch between mail and calendar.
NPN_GetURL - Archive of obsolete content
for example, a null target does not make sense for some url types (such as mailto).
NPN_GetValue - Archive of obsolete content
sdenabledbool: tells whether smartupdate (former name: asd) is enabled; true=smartupdate enabled, false=not enabled npnvisofflinebool: tells whether offline mode is enabled; true=offline mode enabled, false=not enabled npnvtoolkit: npnvsupportsxembedbool: npnvwindownpobject: returns the npobject * pointer for the dom window object; see getting the page url in npapi plugin for a rough example npnvpluginelementnpobject: npnvsupportswindowless: tells whether the browser supports windowless plugins.
NPN_GetValueForURL - Archive of obsolete content
« gecko plugin api reference « browser side plug-in api summary provides information to a plugin which is associated with a given url, for example the cookies or preferred proxy.
NPN_MemAlloc - Archive of obsolete content
you only need to use npn_memflush in situations where you cannot use npn_memalloc, for example, when calling system methods that allocate memory indirectly.
NPN_MemFlush - Archive of obsolete content
description the plug-in calls npn_memflush() when it is not possible to call npn_memalloc(), for example, when calling system apis that indirectly allocate memory.
NPN_SetValue - Archive of obsolete content
the browser code reads this parameter as follows (nppvpluginwindowbool as an example): nperror np_export _setvalue(npp npp, nppvariable variable, void *value) { ...
NPP_NewStream - Archive of obsolete content
stream supports random access through calls to npn_requestread (for example, local files or http servers that support byte-range requests).
NPP_URLNotify - Archive of obsolete content
other possible reason codes are npres_user_break, indicating that the request was halted due to a user action (for example, clicking the stop button), and npres_network_err, indicating that the request could not be completed, perhaps because the url could not be found.
NPP_WriteReady - Archive of obsolete content
the browser can write a smaller amount of data if desired or necessary; for example, if only 8k of data is available in a network buffer.
NPSavedData - Archive of obsolete content
see instance destruction for a code example that shows how to use npsaveddata.
NPAPI plugin reference - Archive of obsolete content
npn_getvalueforurl provides information to a plugin which is associated with a given url, for example the cookies or preferred proxy.
Shipping a plugin as a Toolkit bundle - Archive of obsolete content
for example: plugins/ libplugin.so libplugin.dylib install manifest the install manifest describes the plugin to the user.
Supporting private browsing in plugins - Archive of obsolete content
for example, if private browsing mode is in effect, video player plugins should not record the urls of watched videos in their histories.
Plugins - Archive of obsolete content
for example, the adobe reader plugin lets the user open pdf files directly inside the browser, and the quicktime and realplayer plugins are used to play special format videos in a web page.
Getting Started - Archive of obsolete content
it guides you, step-by-step, through the basics of rss and shows you working examples in action.
Atomic RSS - Archive of obsolete content
ArchiveRSSModuleAtom
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
ArchiveRSSModuleSlash
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
ArchiveRSSVersion0.90
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> <...
title - Archive of obsolete content
netscape rss 0.91 revision 3 example <?xml version="1.0"?> <!doctype rss system "http://my.netscape.com/publish/formats/rss-0.91.dtd"> <rss version="0.91"> <channel> <title>advogato</title> <link>http://www.advogato.org/article/</link> <description>recent advogato articles</description> <language>en-us</language> <image> <link>http://www.advogato.org/</link> <title>advogato</title> ...
.htaccess ( hypertext access ) - Archive of obsolete content
redirect 301 / http://example.com/ # redirect the traffic to the directory to example.com , permanent redirect redirect 302 / http://example.com/ # redirect the traffic to the directory to example.com , temporary redirect blocking : htaccess also facilitates blocking traffic based on ip and ip range, also, use to block bad bots, rippers, and referrers; often used to restrict access by search engine spiders.
Confidentiality, Integrity, and Availability - Archive of obsolete content
another example of a failure of integrity is when you try to connect to a website and a malicious attacker between you and the website redirects your traffic to a different website.
Common Firefox theme issues and solutions - Archive of obsolete content
themes that use -moz-border-image and support both firefox 14 and newer as well as older versions of firefox need to use both the older and newer methodologies like the following example.
Creating a Skin for Firefox - Archive of obsolete content
you can't change what happens when the user right clicks on an image, but you can change the look of the right click menu (make it blue with pink polka dots, for example).
Theme changes in Firefox 3.5 - Archive of obsolete content
see this blog post for an example.
References - Archive of obsolete content
the webpage explains and proposes with small examples the best coding practices and most recommendable ways of developing problem-free javascript code.
-moz-border-bottom-colors - Archive of obsolete content
)where <alpha-value> = <number> | <percentage><hue> = <number> | <angle> example <div id="example">example</div> #example { padding: 20px; background-color: gray; border: 10px solid black; -moz-border-top-colors: #e00 #c30 #c50 #c60 #c70 #c80 #c90 #ca0 #cb0 #cc0; -moz-border-right-colors: red #f60 #f80 #f90 #fa0 #fb0 #fc0 #fd0 #fe0 #ff0; -moz-border-bottom-colors: red #f60 #f80 #f90 #fa0 #fb0 #fc0 #fd0 #fe0 #ff0; -moz-border-left-colors: #e00 #c30 #c50 #c60 #...
-moz-border-left-colors - Archive of obsolete content
)where <alpha-value> = <number> | <percentage><hue> = <number> | <angle> example <div id="example">example</div> #example { padding: 20px; background-color: gray; border: 10px solid black; -moz-border-top-colors: #e00 #c30 #c50 #c60 #c70 #c80 #c90 #ca0 #cb0 #cc0; -moz-border-right-colors: red #f60 #f80 #f90 #fa0 #fb0 #fc0 #fd0 #fe0 #ff0; -moz-border-bottom-colors: red #f60 #f80 #f90 #fa0 #fb0 #fc0 #fd0 #fe0 #ff0; -moz-border-left-colors: #e00 #c30 #c50 #c60 #...
-moz-border-right-colors - Archive of obsolete content
)where <alpha-value> = <number> | <percentage><hue> = <number> | <angle> example <div id="example">example</div> #example { padding: 20px; background-color: gray; border: 10px solid black; -moz-border-top-colors: #e00 #c30 #c50 #c60 #c70 #c80 #c90 #ca0 #cb0 #cc0; -moz-border-right-colors: red #f60 #f80 #f90 #fa0 #fb0 #fc0 #fd0 #fe0 #ff0; -moz-border-bottom-colors: red #f60 #f80 #f90 #fa0 #fb0 #fc0 #fd0 #fe0 #ff0; -moz-border-left-colors: #e00 #c30 #c50 #c60 #...
-moz-border-top-colors - Archive of obsolete content
)where <alpha-value> = <number> | <percentage><hue> = <number> | <angle> example <div id="example">example</div> #example { padding: 20px; background-color: gray; border: 10px solid black; -moz-border-top-colors: #e00 #c30 #c50 #c60 #c70 #c80 #c90 #ca0 #cb0 #cc0; -moz-border-right-colors: red #f60 #f80 #f90 #fa0 #fb0 #fc0 #fd0 #fe0 #ff0; -moz-border-bottom-colors: red #f60 #f80 #f90 #fa0 #fb0 #fc0 #fd0 #fe0 #ff0; -moz-border-left-colors: #e00 #c30 #c50 #c60 #...
-moz-text-blink - Archive of obsolete content
formal syntax none | blink example .example { -moz-text-blink: blink; } specifications this property was defined in an old draft of the css 3 text specification.
-moz-window-shadow - Archive of obsolete content
formal syntax default | menu | tooltip | sheet | none example .kui-panel { -moz-window-shadow: none; } ...
-ms-accelerator - Archive of obsolete content
formal syntax false | true examples this example uses the -ms-accelerator attribute in a <u> element to specify that the "n" in the <label> element is a keyboard shortcut.
-ms-content-zoom-snap-points - Archive of obsolete content
formal syntax snapinterval( <percentage>, <percentage> ) | snaplist( <percentage># ) examples this example demonstrates both types of values for the -ms-content-zoom-snap-points property.
-ms-scroll-chaining - Archive of obsolete content
formal syntax chained | none examples the following example illustrates the -ms-scroll-chaining property in use.
-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-shadow-color - Archive of obsolete content
)where <alpha-value> = <number> | <percentage><hue> = <number> | <angle> examples the following example shows how to create a style rule that sets the -ms-scrollbar-shadow-color property for a <textarea> element.
-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.
:-moz-system-metric(mac-graphite-theme) - Archive of obsolete content
examples demo ...
:-moz-system-metric(windows-default-theme) - Archive of obsolete content
example html content <p id="defaultthemes"> this paragraph should have a green background with luna/royale/zune/aero windows themes and red with other themes.
::-ms-browse - Archive of obsolete content
le border-top-width box-shadow box-sizing color cursor display (values block, inline-block, none) @font-face font-size font-style font-weight height margin-bottom margin-left margin-right margin-top opacity outline-color outline-style outline-width padding-bottom padding-left padding-right padding-top transform transform-origin visibility width syntax ::-ms-browse example html <label>select image: <input type="file"></label> css input[type="file"]::-ms-browse { color: red; background-color: yellow; } result output example specifications not part of any specification.
::-ms-clear - Archive of obsolete content
tyle border-top-width box-shadow box-sizing color cursor display (values block, inline-block, none) @font-face font-size font-style font-weight height margin-bottom margin-left margin-right margin-top opacity outline-color outline-style outline-width padding-bottom padding-left padding-right padding-top transform transform-origin visibility width syntax ::-ms-clear example html <form> <label for="firstname">first name:</label> <input type="text" id="firstname" name="firstname" placeholder="first name"> <br> <label for="lastname">last name:</label> <input type="text" id="lastname" name="lastname" placeholder="second name"> </form> css input, label { display: block; } input[type=text]::-ms-clear { color: red; /* this sets the cross color as red.
::-ms-fill - Archive of obsolete content
ckground-origin, background-repeat, and background-size border border-radius box-shadow box-sizing color cursor display (values block, inline-block, none) font height margin -ms-background-position-x -ms-background-position-y -ms-high-contrast-adjust opacity outline-color, outline-style, and outline-width padding transform and transform-origin visibility syntax ::-ms-fill example html <progress value="10" max="50"></progress> css progress::-ms-fill { background-color: orange; } result a progress bar using this style might look something like this: ...
::-ms-value - Archive of obsolete content
ck, inline-block, none) @font-face font-size font-style font-weight height margin-bottom margin-left margin-right margin-top -ms-background-position-x -ms-background-position-y -ms-high-contrast-adjust opacity outline-color outline-style outline-width padding-bottom padding-left padding-right padding-top transform transform-origin visibility width syntax ::-ms-value example input::-ms-value { color: lime; font-style: italic; } to disable the default styling: select::-ms-value { background-color: transparent; color: inherit; } specifications not part of any specification.
-moz-touch-enabled - Archive of obsolete content
media: media/visual accepts min/max prefixes: no example you might use this feature to render your buttons slightly larger if the user is on a touch-screen device, to make them more finger-friendly.
-moz-windows-accent-color-in-titlebar - Archive of obsolete content
media: media/visual accepts min/max prefixes: no example @media (-moz-windows-accent-color-in-titlebar: 1) { h1 { color: -moz-win-accentcolortext; } body { background-color: -moz-win-accentcolor; } } ...
azimuth - Archive of obsolete content
ArchiveWebCSSazimuth
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.
CSS - Archive of obsolete content
ArchiveWebCSS
for example, moving a child of the stack far to the right will widen the stack so the child remains visible.-moz-text-blinkthe -moz-text-blink non-standard mozilla css extension specifies the blink mode.-moz-window-shadowthe -moz-window-shadow css property specifies whether a window will have a shadow.
Introduction - Archive of obsolete content
for example, var a = 2; var b = 'bar'; var c = <foo {b}={a}>"hi"</foo>; creates a slightly different xml document: <foo bar="2">"hi"</foo>.
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(na...
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: ['...
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(per...
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 ca...
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.
Debug.msTraceAsyncCallbackStarting - Archive of obsolete content
example the following code provides an example of tracing an asynchronous call for a windows 8.x store app.
Debug.msTraceAsyncCallbackCompleted - Archive of obsolete content
example the following code provides an example of tracing an asynchronous call for a windows 8.x store app.
Debug.setNonUserCodeExceptions - Archive of obsolete content
example the following code shows how to set this property.
Debug - Archive of obsolete content
examples print the value of a variable this example uses the write function to display the value of the variable.
Enumerator.atEnd - Archive of obsolete content
example in following code, the atend method is used to determine if the end of a list of drives has been reached: function showdrives() { var s = ""; var bytespergb = 1024 * 1024 * 1024; var fso = new activexobject("scripting.filesystemobject"); var e = new enumerator(fso.drives); e.movefirst(); while (e.atend() == false) { var drv = e.item(); s += drv.pat...
Enumerator.item - Archive of obsolete content
example function showdrives() { var s = ""; var bytespergb = 1024 * 1024 * 1024; var fso = new activexobject("scripting.filesystemobject"); var e = new enumerator(fso.drives); e.movefirst(); while (e.atend() == false) { var drv = e.item(); s += drv.path + " - "; if (drv.isready) { var freegb = drv.freespace / bytespergb; ...
Enumerator.moveFirst - Archive of obsolete content
example in following example, the movefirst method is used to evaluate members of the drivescollection from the beginning of the list: function showdrives() { var s = ""; var bytespergb = 1024 * 1024 * 1024; var fso = new activexobject("scripting.filesystemobject"); var e = new enumerator(fso.drives); e.movefirst(); while (e.atend() == false) { var drv = e.item(); s += drv.p...
Enumerator.moveNext - Archive of obsolete content
example in following example, the movenext method is used to move to the next drive in the drives collection: function showdrives() { var s = ""; var bytespergb = 1024 * 1024 * 1024; var fso = new activexobject("scripting.filesystemobject"); var e = new enumerator(fso.drives); e.movefirst(); while (e.atend() == false) { var drv = e.item(); s += drv.path + ...
Enumerator - Archive of obsolete content
example the following code shows the usage of the enumerator object: var bytespergb = 1024 * 1024 * 1024; var fso = new activexobject("scripting.filesystemobject"); document.write(fso.drives); var e = new enumerator(fso.drives); var drivestring = ""; e.movefirst(); while (e.atend() == false) { var drv = e.item(); drivestring += drv.path + " - "; if (drv.isready){ var freegb = ...
Error.description - Archive of obsolete content
example the following example illustrates the use of the description property.
Error.stackTraceLimit - Archive of obsolete content
example the following example shows how to set and then get the stack trace limit.
ScriptEngine() - Archive of obsolete content
example the following example illustrates the use of the scriptengine function: if (window.scriptengine) { console.log(window.scriptengine()); } // output: jscript requirements supported in the following document modes: quirks, internet explorer 6 standards, internet explorer 7 standards, internet explorer 8 standards, internet explorer 9 standards, internet explorer 10 standards, internet explorer 11 standards.
ScriptEngineBuildVersion - Archive of obsolete content
example the following example illustrates the use of the scriptenginebuildversion function: if(window.scriptenginebuildversion) { console.log(window.scriptenginebuildversion()); } // output: <current build version> requirements supported in the following document modes: quirks, internet explorer 6 standards, internet explorer 7 standards, internet explorer 8 standards, internet explorer 9 standa...
ScriptEngineMajorVersion - Archive of obsolete content
example the following example illustrates the use of the scriptenginemajorversion function: if (window.scriptenginemajorversion) { console.log(window.scriptengine()); } output: <current major version> requirements supported in the following document modes: quirks, internet explorer 6 standards, internet explorer 7 standards, internet explorer 8 standards, internet explorer 9 standards, internet...
ScriptEngineMinorVersion - Archive of obsolete content
example the following example illustrates the use of the scriptengineminorversion function.
VBArray.getItem - Archive of obsolete content
example the following example consists of three parts.
VBArray.lbound - Archive of obsolete content
example the following example consists of three parts.
VBArray.ubound - Archive of obsolete content
example the following example consists of three parts.
VBArray - Archive of obsolete content
example the following example consists of three parts.
@cc_on - Archive of obsolete content
example the following example illustrates the use of the @cc_on statement.
@if - Archive of obsolete content
example the following example illustrates the use of the @if...@elif...@else...@end statement.
@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: !
Number.toInteger() - Archive of obsolete content
examples using tointeger number.tointeger(0.1); // 0 number.tointeger(1); // 1 number.tointeger(math.pi); // 3 number.tointeger(null); // 0 specifications not part of any standard.
Object.prototype.__count__ - Archive of obsolete content
syntax obj.__count__ examples { 1: 1 }.__count__ // 1 [].__count__ // 0 [1].__count__ // 1 [1, /* hole */, 2, 3].__count__ // 3 specifications not part of any standard.
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', {w...
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.obser...
Object.prototype.unwatch() - Archive of obsolete content
examples see watch().
Reflect.enumerate() - Archive of obsolete content
examples using reflect.enumerate() var obj = { x: 1, y: 2 }; for (var name of reflect.enumerate(obj)) { console.log(name); } // logs "x" and "y" specifications not part of any standard.
String.prototype.quote() - Archive of obsolete content
examples using quote in the table below the quote() method replaces any special characters and wraps the strings in double-quotes.
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.
for each...in - Archive of obsolete content
examples using for each...in warning: never use a loop like this on arrays.
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; }); ...
Sharp variables in JavaScript - Archive of obsolete content
examples multiple references var a = { foo:#1=[], bar:#1# }; a.foo.push("hello"); a.bar.push("there!"); alert(a.foo[1]); // "there!" you can avoid using sharp variables by breaking the declaration up into multiple lines.
StopIteration - Archive of obsolete content
examples stopiteration is thrown by iterator.
forEach - Archive of obsolete content
i've removed the lengthy example, while still linking to it and provided a much simpler and leaner implementation.
Window.importDialog() - Archive of obsolete content
example var dialog = importdialog(null, "chrome://myextension/content/dialog.xul", myobject); notes the xul passed to importdialog() is very similar to xul passed to window.opendialog(), with some limitations and caveats: only <dialog> top level elements are permitted.
Building Mozilla XForms - Archive of obsolete content
the following scheme usually works (replace {geckoversion} with the used gecko/toolkit version): <em:minversion>{geckoversion}.0</em:minversion> <em:maxversion>{geckoversion}.*</em:maxversion> for example, for the firefox 3.5 version of the extension, it might look like that: <em:minversion>1.9.1.0</em:minversion> <em:maxversion>1.9.1.*</em:maxversion> then zip the files again (or use an editor like vim that can edit files inside a zip archive).
Troubleshooting XForms Forms - Archive of obsolete content
if you are developing on your local machine using apache tomcat for example then add the following regular expression on a new line: ^http://localhost:8080/.* use the xforms buddy to view instance data the xforms buddy extension allows you to dynamically view model instance data while the xforms is running in the firefox browser.
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 Styling - Archive of obsolete content
=== example === here's a small example that shows equivalent styles for chiba and mozilla xforms.
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 t...
XForms Group Element - Archive of obsolete content
example <group ref="address"> <label>shipping address</label> <input ref="line_1"> <label>address line 1</label> </input> <input ref="line_2"> <label>address line 2</label> </input> <input ref="postcode"> <label>postcode</label> </input> </group> ...
XForms Message Element - Archive of obsolete content
example <xforms:trigger> <xforms:label>it's a button</xforms:label> <xforms:message level="modal" ev:event="domactivate">hello</xforms:message> </xforms:trigger> ...
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:cho...
XForms Switch Module - Archive of obsolete content
example <switch> <case id="in" selected="true"> <input ref="yourname"> <label>please tell me your name</label> <toggle ev:event="domactivate" case="out"/> </input> </case> <case id="out" selected="false"> <html:p>hello <output ref="yourname" /> <trigger id="editbutton"> <label>edit</label> <toggle ev:event="domactivate" case="in"/> </trigger> ...
Using XForms and PHP - Archive of obsolete content
returning xml data to either serve a page (with xforms in it) or to generate data used as instance data for xforms, the page needs to be served as xml, for example application/xhtml+xml.
XForms - Archive of obsolete content
xforms tutorial and cookbook xforms in wikibook format - over 50 examples tested with firefox.
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.
Popup Window Controls - Archive of obsolete content
example the example tag links to devedge-temp.mozilla.org this example illustrates detecting suppressed popup windows as well as an approach for replacing popup windows with inline html using innerhtml.
Web Standards - Archive of obsolete content
tools firebug extension web developer extension markup validation service (w3c) css validation service (w3c) examples mozilla 1.0 demos - showing off what can be done with web standards.
XQuery - Archive of obsolete content
a simple usage example is available.
XUL Parser in Python - Archive of obsolete content
for example, you could easily adapt this to: return the id values of all the elements take elements on the command line and only spell them out build new chrome subdirectories (i.e.
Using the DOM File API in chrome code - Extensions
for example, let's say your add-on needs to access a file in the user's profile.
bootstrap.js - Extensions
the example below contains the required methods in vsdoc format.
3D collision detection - Game development
if you have entities that will be rotating, you can either modify the dimensions of the bounding box so it still wraps the object, or opt to use another bounding geometry type, such as spheres (which are invariant to rotation.) the animated gif below shows a graphic example of an aabb that adapts its size to fit the rotating entity.
Building up a basic demo with A-Frame - Game development
the <script> element includes the a-frame framework in the page; we will write our example code inside the <body> element.
Building up a basic demo with PlayCanvas editor - Game development
when you are ready to continue with our tutorial, go to your canvas homepage — for example mine is https://playcanvas.com/end3r.
Building up a basic demo with PlayCanvas - Game development
note: check out the list of featured demos to find more examples.
asm.js - Game development
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.
Create the Canvas and draw on it - Game development
let's see an example piece of code that prints a red square on the canvas.
Finishing up - Game development
for example, we can offer more than one life to the player.
Paddle and keyboard controls - Game development
the ability to move the paddle left and right pressed buttons can be defined and initialized with boolean variables like in the example.
Animations and tweens - Game development
as an example, we will make the ball wobble when it hits something.
Load the assets and print them on screen - Game development
game.load.image('ball', 'img/ball.png'); } the first parameter we want to give the asset is the name that will be used across our game code — for example, in our ball variable name — so we need to make sure it is the same.
Player paddle and controls - Game development
in our case the world is the same as the canvas, but for other types of games, like side-scrollers for example, the world will be bigger, and you can tinker with it to create interesting effects.
Randomizing gameplay - Game development
be sure to check the ever growing list of examples and the official documentation, and visit the html5 gamedevs forums if you ever need any help.
Touch Event Horizon - Game development
this article is for touch event horizon and a game related to it touch gestures and events link the example game github repository live demo setting up the canvas counting the taps touchstart, touchend collecting the bonus touchmove future developments summary this tutorial shows how to use touch events to create a game on a <canvas>.
Visual-js game engine - Game development
online demo examples at : https://jsfiddle.net/user/zlatnaspirala/fiddles/ demo slot mashine basic demo at : https://jsfiddle.net/zlatnaspirala/7d0d8v6d/ help about new 2d part - implementation of matter.js based typescript .
Visual JS GE - Game development
you need to put your images in a folder, for example test_res/ , inside project_instance/res/.
Accessibility tree (AOM) - MDN Web Docs Glossary: Definitions of Web-related terms
for example, is it a button, a nav bar, or a list of items?
ARIA - MDN Web Docs Glossary: Definitions of Web-related terms
for example, you could add the attribute role="alert" to a <p> tag to notify a sight-challenged user that the information is important and time-sensitive (which you might otherwise convey through text color).
Abstraction - MDN Web Docs Glossary: Definitions of Web-related terms
example class implementabstraction { // method to set values of internal members set(x, y) { this.a = x; this.b = y; } display() { console.log('a = ' + this.a); console.log('b = ' + this.b); } } const obj = new implementabstraction(); obj.set(10, 20); obj.display(); // a = 10 // b = 20 learn more general knowledge abstraction on wikipedia ...
Algorithm - MDN Web Docs Glossary: Definitions of Web-related terms
for example: a cooking recipe is a simple algorithm for humans.
Alpha (alpha channel) - MDN Web Docs Glossary: Definitions of Web-related terms
for example, the color #8921f2 (also described as rgb(137, 33, 242) or hsl(270, 89%, 54)) is a nice shade of purple.
Asynchronous - MDN Web Docs Glossary: Definitions of Web-related terms
for example, the ajax (asynchronous javascript and xml) programming technique—now usually simply "ajax", even though json is usually used rather than xml in modern applications—is a mechanism that requests relatively small amounts of data from the server using http, with the result being returned when available rather than immediately.
Bandwidth - MDN Web Docs Glossary: Definitions of Web-related terms
it is usually measured in multiples of bits-per-second (bps), for example megabits-per-second (mbps) or gigabits-per-second (gbps).
Base64 - MDN Web Docs Glossary: Definitions of Web-related terms
for example, the string "a" with length === 1 gets encoded to "yq==" with length === 4 — a 300% increase.
BigInt - 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.
Block (CSS) - MDN Web Docs Glossary: Definitions of Web-related terms
for example, <p> is by default a block-level element, whereas <a> is an inline element — you can put several links next to one another in your html source and they will sit on the same line as one another in the rendered output.
Block (scripting) - MDN Web Docs Glossary: Definitions of Web-related terms
for example, you can put a block of statements after an if (condition) block, indicating that the interpreter should run the code inside the block if the condition is true, or skip the whole block if the condition is false.
Boolean - MDN Web Docs Glossary: Definitions of Web-related terms
for example, in javascript, boolean conditionals are often used to decide which sections of code to execute (such as in if statements) or repeat (such as in for loops).
CORS-safelisted response header - MDN Web Docs Glossary: Definitions of Web-related terms
by default, the safelist includes the following response headers: cache-control content-language content-type expires last-modified pragma examples extending the safelist you can extend the list of cors-safelisted response headers by using the access-control-expose-headers header: access-control-expose-headers: x-custom-header, content-length ...
CSRF - MDN Web Docs Glossary: Definitions of Web-related terms
this can be done, for example, by including malicious parameters in a url behind a link that purports to go somewhere else: <img src="https://www.example.com/index.php?action=delete&id=123"> for users who have modification permissions on https://www.example.com, the <img> element executes action on https://www.example.com without their noticing, even if the element is not at https://www.example.com.
CSS - MDN Web Docs Glossary: Definitions of Web-related terms
here is an example that makes every html paragraph yellow against a black background: /* the selector "p" indicates that all paragraphs in the document will be affected by that rule */ p { /* the "color" property defines the text color, in this case yellow.
Call stack - MDN Web Docs Glossary: Definitions of Web-related terms
example function greeting() { // [1] some codes here sayhi(); // [2] some codes here } function sayhi() { return "hi!"; } // invoke the `greeting` function greeting(); // [3] some codes here the code above would be executed like this: ignore all functions, until it reaches the greeting() function invocation.
Canonical order - MDN Web Docs Glossary: Definitions of Web-related terms
for example, background shorthand property values are made up of several background-* longhand properties.
Card sorting - MDN Web Docs Glossary: Definitions of Web-related terms
this can be used for example to work out what should go on each page of a website.
Compile - MDN Web Docs Glossary: Definitions of Web-related terms
the most famous, "gcc" is one example.
Computer Programming - MDN Web Docs Glossary: Definitions of Web-related terms
for example, a program that helps scientists with complex calculations, a database that stores huge amounts of data, a web site that allows people to download music, or animation software that allows people to create animated movies.
Continuous Media - MDN Web Docs Glossary: Definitions of Web-related terms
the most common examples of continuous media are audio and motion video.
Copyleft - MDN Web Docs Glossary: Definitions of Web-related terms
examples of copyleft licenses are the gnu gpl (for software) and the creative commons sa (share alike) licenses (for works of art).
DoS attack - MDN Web Docs Glossary: Definitions of Web-related terms
computers have limited resources, for example computation power or memory.
Denial of Service - MDN Web Docs Glossary: Definitions of Web-related terms
computers have limited resources, for example computation power or memory.
Deserialization - MDN Web Docs Glossary: Definitions of Web-related terms
in javascript, for example, you can deserialize a json string to an object by calling the function json.parse().
Domain - MDN Web Docs Glossary: Definitions of Web-related terms
for example, in "developer.mozilla.org": "org" is called a top-level domain.
Dynamic programming language - MDN Web Docs Glossary: Definitions of Web-related terms
for example, in javascript it is possible to change the type of a variable or add new properties or methods to an object while the program is running.
Encapsulation - MDN Web Docs Glossary: Definitions of Web-related terms
encapsulation is the packing of data and functions into one component (for example, a class) and then controlling access to that component to make a "blackbox" out of the object.
Endianness - MDN Web Docs Glossary: Definitions of Web-related terms
examples with the number 0x12345678 (i.e.
Entity header - MDN Web Docs Glossary: Definitions of Web-related terms
a few request headers after a get request: in the following example, content-length is an entity header, while host and user-agent are requests headers: post /myform.html http/1.1 host: developer.mozilla.org user-agent: mozilla/5.0 (macintosh; intel mac os x 10.9; rv:50.0) gecko/20100101 firefox/50.0 content-length: 128 learn more technical knowledge list of all http headers ...
Fallback alignment - MDN Web Docs Glossary: Definitions of Web-related terms
for example, if you specify justify-content: space-between there must be more than one alignment subject.
Falsy - MDN Web Docs Glossary: Definitions of Web-related terms
examples examples of falsy values in javascript (which are coerced to false in boolean contexts, and thus bypass the if block): if (false) if (null) if (undefined) if (0) if (-0) if (0n) if (nan) if ("") the logical and operator, && if the first object is falsy, it returns that object false && "dog" // ↪ false 0 && "dog" // ↪ 0 specifications specification ecmascript (...
Favicon - MDN Web Docs Glossary: Definitions of Web-related terms
when a familiar icon is seen in the browser's address bar, for example, it helps users know they are in the right place.
Gonk - MDN Web Docs Glossary: Definitions of Web-related terms
since firefox os has full control over gonk, we can expose interfaces to gecko that aren't accessible on other operating systems, for example the full telephony stack and display frame buffer.
Grid - MDN Web Docs Glossary: Definitions of Web-related terms
in the example below i have created an explicit grid of three columns and two rows.
Grid Cell - MDN Web Docs Glossary: Definitions of Web-related terms
in the example we have created a three column track grid.
Grid Tracks - MDN Web Docs Glossary: Definitions of Web-related terms
the example below demonstrates a grid with three column tracks, one of 200 pixels, the second of 1fr, the third of 3fr.
Guard - MDN Web Docs Glossary: Definitions of Web-related terms
for example, immutable guard means that headers can't be changed.
Gutters - MDN Web Docs Glossary: Definitions of Web-related terms
in the example below we have a three-column and two-row track grid, with 20-pixel gaps between column tracks and 20px-gaps between row tracks.
HTTP - MDN Web Docs Glossary: Definitions of Web-related terms
as part of a uri, the "http" within "http://example.com/" is called a "scheme".
HTTP header - MDN Web Docs Glossary: Definitions of Web-related terms
a basic request with one header: get /example.http http/1.1 host: example.com redirects have mandatory headers (location): 302 found location: /newpage.html a typical set of headers: 304 not modified access-control-allow-origin: * age: 2318192 cache-control: public, max-age=315360000 connection: keep-alive date: mon, 18 jul 2016 16:06:00 gmt server: apache vary: accept-encoding via: 1.1 3dc30c7222755f86e824b93feb8b5b8c.cloudfront.net (...
Hotlink - MDN Web Docs Glossary: Definitions of Web-related terms
for example, an image hosted on site1.com is shown directly on site2.com.
IIFE - MDN Web Docs Glossary: Definitions of Web-related terms
examples the function becomes a function expression which is immediately executed.
ITU - MDN Web Docs Glossary: Definitions of Web-related terms
for example, the itu and the moving picture experts group (mpeg) worked together to develop and publish, as well as to maintain, the various mpeg specifications, such as mpeg-2 (itu h.262), avc (itu h.264), and hevc (itu h.265).
Immutable - MDN Web Docs Glossary: Definitions of Web-related terms
an object can be immutable for various reasons, for example: to improve performance (no planning for the object's future changes) to reduce memory use (make object references instead of cloning the whole object) thread-safety (multiple threads can reference the same object without interfering with one other) learn more general knowledge immutable on wikipedia ...
Intrinsic Size - MDN Web Docs Glossary: Definitions of Web-related terms
for example, inline elements are sized intrinsically: width, height, and vertical margin and padding have no impact, though horizontal margin and padding do.
Layout viewport - MDN Web Docs Glossary: Definitions of Web-related terms
this becomes important, for example, on mobile devices, where a pinching gesture can usually be used to zoom in and out on a site's contents.
Ligature - MDN Web Docs Glossary: Definitions of Web-related terms
for example, in french "œ" is a ligature of "oe".
Local variable - MDN Web Docs Glossary: Definitions of Web-related terms
example var global = 5; //is a global variable function fun(){ var local = 10; //is a local variable } ...
Long task - MDN Web Docs Glossary: Definitions of Web-related terms
common examples include long running event handlers, expensive reflows and other re-renders, and work the browser does between different turns of the event loop that exceeds 50 ms.
Lossless compression - MDN Web Docs Glossary: Definitions of Web-related terms
examples of lossless compression include gzip, brotli, webp, and png, lossy compression, on the other hand, uses inexact approximations by discarding some data from the original file, making it an irreversible compression method.
MIME type - MDN Web Docs Glossary: Definitions of Web-related terms
a mime type (now properly called "media type", but also sometimes "content type") is a string sent along with a file indicating the type of the file (describing the content format, for example, a sound file might be labeled audio/ogg, or an image file image/png).
Media (CSS) - MDN Web Docs Glossary: Definitions of Web-related terms
learn more general knowledge using media queries technical reference media queries define a set of characteristics or parameters required to apply the css styles that are specified within the curly braces of the media query; for example: only applying certain css styles for devices below 768 pixels.
Metadata - MDN Web Docs Glossary: Definitions of Web-related terms
for example, an html document is data, but html can also contain metadata in its <head> element that describes the document — for example who wrote it, and its summary.
MitM - MDN Web Docs Glossary: Definitions of Web-related terms
for example, a wi-fi router can be compromised.
Mixin - MDN Web Docs Glossary: Definitions of Web-related terms
for example, the windoworworkerglobalscope mixin is used to provide methods and properties that need to be available on both the window and workerglobalscope interfaces.
Mutable - MDN Web Docs Glossary: Definitions of Web-related terms
lets understand this with an example: var immutablestring = "hello"; // in the above code, a new object with string value is created.
NaN - MDN Web Docs Glossary: Definitions of Web-related terms
for example, nans can represent infinity, result of division by zero, missing value, or the square root of a negative (which is imaginary, whereas a floating-point number is real).
Native - MDN Web Docs Glossary: Definitions of Web-related terms
an example of a native android app would be a mobile application written in java using the android toolchain.
Navigation directive - MDN Web Docs Glossary: Definitions of Web-related terms
csp navigation directives are used in a content-security-policy header and govern to which location a user can navigate to or submit a form to, for example.
Network throttling - MDN Web Docs Glossary: Definitions of Web-related terms
firefox's developer tools for example have a drop-down menu available in both the network monitor and responsive design mode containing network speed options (e.g.
Normative - MDN Web Docs Glossary: Definitions of Web-related terms
specifications might also contain sections that are marked as non-normative or informative, which means those are provided there for the purpose of helping the reader understand the specifications better or to showcase an example or best practice, which need not be followed as a rule.
Number - MDN Web Docs Glossary: Definitions of Web-related terms
in other programming languages different numeric types exist; for example, integers, floats, doubles, or bignums.
Operand - MDN Web Docs Glossary: Definitions of Web-related terms
for example, when you add two numbers, the numbers are the operand and "+" is the operator.
Operator - MDN Web Docs Glossary: Definitions of Web-related terms
for example, in javascript the addition operator ("+") adds numbers together and concatenates strings, whereas the "not" operator ("!") negates an expression — for example making a true statement return false.
PHP - MDN Web Docs Glossary: Definitions of Web-related terms
examples basic syntax // start of php code <?php // php code goes here ?> // end of php code printing data on screen <?php echo "hello world!"; ?> php variables ​​​​​​​​​​​​​​<?php // variables $nome='danilo'; $sobrenome='santos'; $pais='brasil'; $email='danilocarsan@gmailcom'; ​​​​​​​ // printing the variables echo $nome; echo $sobrenome; echo $pais; echo $email; ?> ...
Page prediction - MDN Web Docs Glossary: Definitions of Web-related terms
for example, as the user types in the address bar, the browser might send the current text in the address bar to the search engine before the user submits the request.
Parse - MDN Web Docs Glossary: Definitions of Web-related terms
parsing means analyzing and converting a program into an internal format that a runtime environment can actually run, for example the javascript engine inside browsers.
Polymorphism - MDN Web Docs Glossary: Definitions of Web-related terms
for example, integers, floats, and doubles are implicitly polymorphic: regardless of their different types, they can all be added, subtracted, multiplied, and so on.
Port - MDN Web Docs Glossary: Definitions of Web-related terms
for example, the default port for the http protocol is 80 and the default port for the https protocol is 443, so a http server waits for requests on those ports.
Proxy server - MDN Web Docs Glossary: Definitions of Web-related terms
a proxy intercepts requests and serves back responses; it may forward the requests, or not (for example in the case of a cache), and it may modify it (for example changing its headers, at the boundary between two networks).
Pseudo-class - MDN Web Docs Glossary: Definitions of Web-related terms
for example, the selector a:visited applies styles only to links that the user has already followed.
Pseudo-element - MDN Web Docs Glossary: Definitions of Web-related terms
for example, rather than putting the first letter of each paragraph in its own element, you can style them all with p::first-letter.
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.
Quaternion - MDN Web Docs Glossary: Definitions of Web-related terms
while mathematical quaternions are more involved than this, the unit quaternions (or rotational quaternions) used to represent rotation while using webgl or webxr, for example, are represented using the same syntax as a 3d point.
RGB - MDN Web Docs Glossary: Definitions of Web-related terms
in css they can be represented as a single 24-bit integer in hexadecimal notation (for example, #add8e6 is light blue), or in functional notation as three separate 8-bit integers (for example, rgb(46, 139, 87) is sea green).
Recursion - MDN Web Docs Glossary: Definitions of Web-related terms
examples recursive function calls itself until condition met the following python code defines a function that takes a number, prints it, and then calls itself again with the number's value -1.
Rendering engine - MDN Web Docs Glossary: Definitions of Web-related terms
examples of layout engines: blink, gecko, edgehtml, webkit.
Response header - MDN Web Docs Glossary: Definitions of Web-related terms
for example, the content-length header is an entity header referring to the size of the body of the response message.
Robots.txt - MDN Web Docs Glossary: Definitions of Web-related terms
for example, the site admin can forbid crawlers to visit a certain folder (and all the files therein contained) or to crawl a specific file, usually to prevent those files being indexed by other search engines.
SIMD - MDN Web Docs Glossary: Definitions of Web-related terms
simd allows one same operation to be performed on multiple data points resulting in data level parallelism and thus performance gains — for example, for 3d graphics and video processing, physics simulations or cryptography, and other domains.
SMPTE (Society of Motion Picture and Television Engineers) - MDN Web Docs Glossary: Definitions of Web-related terms
for example, smpte defines the standards used for digital cinema used by modern digital movie theaters.
SQL Injection - MDN Web Docs Glossary: Definitions of Web-related terms
hackers use a simple string called a magical string, for example: username: admin password: anything 'or'1'='1 after clicking on the login button, the sql query will work as follows: "select count(*) from users where username=' admin ' and password=' anything 'or'1'='1 ' "; just take a closer look at the above query's password section.
SRI - MDN Web Docs Glossary: Definitions of Web-related terms
subresource integrity (sri) is a security feature that enables browsers to verify that files they fetch (for example, from a cdn) are delivered without unexpected manipulation.
Serialization - MDN Web Docs Glossary: Definitions of Web-related terms
in javascript, for example, you can serialize an object to a json string by calling the function json.stringify().
Server - MDN Web Docs Glossary: Definitions of Web-related terms
for example: an internet-connected web server is sending a html file to your browser software so that you can read this page local area network server for file, name, mail, print, and fax minicomputers, mainframes, and super computers at data centers learn more general knowledge introduction to servers server (computing) on wikipedia ...
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...
Slug - MDN Web Docs Glossary: Definitions of Web-related terms
it may also just be the final component when a new document is created under a parent document; for example, this page's slug is glossary/slug .
Stacking context - MDN Web Docs Glossary: Definitions of Web-related terms
learn more general knowledge further explanation and example ...
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 mynotif...
Syntax - MDN Web Docs Glossary: Definitions of Web-related terms
although languages can share few similarities in terms of their syntaxes for example "operand operator operand" rule in javascript and python.
Syntax error - MDN Web Docs Glossary: Definitions of Web-related terms
for example, if you leave off a closing brace (}) when defining a javascript function, you trigger a syntax error.
Synthetic monitoring - MDN Web Docs Glossary: Definitions of Web-related terms
examples of popular synthetic monitoring tools include webpagetest and lighthouse.
TOFU - MDN Web Docs Glossary: Definitions of Web-related terms
to do that, clients will look for identifiers (for example public keys) stored locally.
Tree shaking - MDN Web Docs Glossary: Definitions of Web-related terms
this is important for preparing code that is production ready, for example with clean structures and minimal file size.
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.
Type conversion - MDN Web Docs Glossary: Definitions of Web-related terms
for example, given the instruction 5+2.0, the floating point 2.0 is implicitly typecasted into an integer, but given the instruction number("0x11"), the string "0x11" is explicitly typecasted as the number 17.
Type coercion - MDN Web Docs Glossary: Definitions of Web-related terms
examples const value1 = '5'; const value2 = 9; let sum = value1 + value2; console.log(sum); in the above example, javascript has coerced the 9 from a number into a string and then concatenated the two values together, resulting in a string of 59.
URL - MDN Web Docs Glossary: Definitions of Web-related terms
your browser displays urls in its address bar, for example: https://developer.mozilla.org some browsers display only the part of a url after the "//", that is, the domain name.
URN - MDN Web Docs Glossary: Definitions of Web-related terms
this example comes from rfc3986: urn:oasis:names:specification:docbook:dtd:xml:4.1.2 learn more general knowledge urn on wikipedia ...
UX - MDN Web Docs Glossary: Definitions of Web-related terms
ux studies undertaken on a web page for example can demonstrate whether it is easy for users to understand the page, navigate to different areas, and complete common tasks, and where such processes could have less friction.
Unicode - MDN Web Docs Glossary: Definitions of Web-related terms
for example, one character set would store japanese characters, and another would store the arabic alphabet.
Wrapper - MDN Web Docs Glossary: Definitions of Web-related terms
for example, sdk libraries for aws are examples of wrappers.
XML - MDN Web Docs Glossary: Definitions of Web-related terms
for example, web services can use xml to exchange requests and responses.
Character encoding - MDN Web Docs Glossary: Definitions of Web-related terms
for example, in html we normally declare a character encoding of utf-8, using the following line: <meta charset="utf-8"> this ensures that you can use characters from just about any human language in your html document, and they will display reliably.
Character set - MDN Web Docs Glossary: Definitions of Web-related terms
if a character set is used incorrectly (for example, unicode for an acticle encoded in big5), you may see nothing but broken characters, which are called mojibake.
firewall - MDN Web Docs Glossary: Definitions of Web-related terms
for example, it can block incoming connections aimed at a certain port or outgoing connections to a certain ip address.
LTR (Left To Right) - MDN Web Docs Glossary: Definitions of Web-related terms
for example, the en-us locale (for us english) specifies left-to-right.
non-normative - MDN Web Docs Glossary: Definitions of Web-related terms
software specifications often contains information marked as non-normative or informative, which means that those are provided there for the purpose of helping the readers to understand the specification better or to show an example or a best practice, and not needed to be followed as a rule.
Prerender - MDN Web Docs Glossary: Definitions of Web-related terms
<link rel="prerender" href="https://example.com/content/to/prerender"> see also prefetch ...
privileged code - MDN Web Docs Glossary: Definitions of Web-related terms
for example, code in content scripts.
Property (CSS) - MDN Web Docs Glossary: Definitions of Web-related terms
here's an example of a css rule: /* "div" is a selector indicating that all the div elements */ /* in the document will be styled by that rule */ div { /* the property "color" with the value "black" indicates */ /* that the text will have the color black */ color: black; /* the property "background-color" with the value "white" indicates */ /* that the background color of the elements will be white */ background-color: white; } learn more general knowledge learn css technical reference the css reference on mdn the css working group current work ...
RTL (Right to Left) - MDN Web Docs Glossary: Definitions of Web-related terms
for example, the he locale (for hebrew) specifies right-to-left.
Safe - MDN Web Docs Glossary: Definitions of Web-related terms
for example, put and delete are both idempotent but unsafe.
undefined - MDN Web Docs Glossary: Definitions of Web-related terms
example var x; //create a variable but assign it no value console.log("x's value is", x) //logs "x's value is undefined" learn more general knowledge undefined value on wikipedia technical reference javascript data types and data structures ...
User agent - MDN Web Docs Glossary: Definitions of Web-related terms
a user agent is a computer program representing a person, for example, a browser in a web context.
Accessibility - 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 can try out most of the code examples in an online coding program such as jsbin or glitch.
CSS building blocks - Learn web development
note: if you are working on a computer/tablet/another 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.
Normal Flow - Learn web development
let's look at a simple example that explains all of this: <h1>basic document flow</h1> <p>i am a basic block level element.
Styling text - 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, codepen or glitch.
What text editors are available? - Learn web development
save you time by auto-completing recurring structures (for example, automatically close html tags, or suggesting valid values for a given css property).
How do you host your website on Google App Engine? - Learn web development
for example, for the project id gaesamplesite, go to gaesamplesite.appspot.com.
Web forms — Working with user data - 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.
Front-end web developer - Learn web development
for example, if you already know html, you can skip ahead to the css section.
Installing basic software - Learn web development
installing a local web server some examples will need to be run by a web server to work successfully.
What will your website look like? - Learn web development
this is sometimes called a design guide, design system, or brand book, and you can see an example at the firefox photon design system.
Define terms with HTML - Learn web development
a simple example here's a simple example describing kinds of food and drink: <dl> <dt>jambalaya</dt> <dd> rice-based entree typically containing chicken, sausage, seafood, and spices </dd> <dt>sukiyaki</dt> <dd> japanese specialty consisting of thinly sliced meat, vegetables, and noodles, cooked in sake and soy sauce </dd> <dt>chianti</dt> <dd> dry itali...
Use JavaScript within a webpage - Learn web development
for example, if you've implemented a nice javascript progress bar, make sure to supplement it with matching text percentages inside the html.
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
LearnHTMLTables
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.
Structuring the web with HTML - Learn web development
after learning html, you can then move on to learning about more advanced topics such as: css, and how to use it to style html (for example alter your text size and fonts used, add borders and drop shadows, layout your page with multiple columns, add animations and other visual effects.) javascript, and how to use it to add dynamic functionality to web pages (for example find your location and plot it on a map, make ui elements appear/disappear when you toggle a button, save users' data locally on their computers, and much much more...
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.
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.
JavaScript — Dynamic client-side scripting - Learn web development
after getting familiar with the basics of javascript, you should be in a position to learn about more advanced topics, for example: javascript in depth, as taught in our javascript guide web apis modules this topic contains the following modules, in a suggested order for working through them.
HTML performance features - Learn web development
complications can occur when, for example, the file size of a <video> embed is too large, or when a webpage is not optimized for mobile devices.
Perceived performance - Learn web development
for example, because page render is blocked by loading and parsing css and javascript, minimizing the amount of css and js that needs to be loaded on initially will have a major impact on improving perceived performance.
Web performance resources - Learn web development
if you do, have a backup plan for seo (e.g render full page for bot traffic); for example, by using the loading attribute on the <img> element it is also crucial to realize what is really important to your users.
What is web performance? - Learn web development
there are a lot of best practices to consider in making apps feel smooth, for example using css animations rather than javascript for animation, and minimizing the number of repaints the ui requires due to changes in the dom.
Multimedia: video - Learn web development
for example, given video compressions in three different formats at 10mb, 12mb, and 13mb, declare the smallest first and the largest last: <video width="400" height="300" controls="controls"> <!-- webm: 10 mb --> <source src="video.webm" type="video/webm" /> <!-- mpeg-4/h.264: 12 mb --> <source src="video.mp4" type="video/mp4" /> <!-- ogg/theora: 13 mb --> <source src="video.ogv" type="video/ogv...
Learning area release notes - Learn web development
it has new examples available and techniques covered.
Server-side website programming - Learn web development
for example, imagine how many products are available on amazon, and imagine how many posts have been written on facebook.
Ember Interactivity: Footer functionality, conditional rendering - Learn web development
in ember, you can conditionally render parts of the template using conditional content; a simple block example looks something like this: {{#if this.thingistrue}} content for the block form of "if" {{/if}} so let's try replacing this part of footer.hbs: <strong>{{this.todos.incomplete.length}}</strong> todos left with the following: <strong>{{this.todos.incomplete.length}}</strong> {{#if this.todos.incomplete.length === 1}} todo {{else}} todos {{/if}} left this will give us an er...
Ember interactivity: Events, classes and state - Learn web development
for example, the @tracked decorator (see slightly later on) runs code it is applied to, but additionally tracks it and automatically updates the app when values change.
Ember resources and troubleshooting - Learn web development
more concretely, using mut allows for template-only settings functions to be declared: <checkbox @value={{this.somedata}} @ontoggle={{fn (mut this.somedata) (not this.somedata)}} /> whereas, without mut, a component class would be needed: import component from '@glimmer/component'; import { tracked } from '@glimmer/tracking'; import { action } from '@ember/object'; export default class example extends component { @tracked somedata = false; @action setdata(newvalue) { this.somedata = newvalue; } } which would then be called in the template like so: <checkbox @data={{this.somedata}} @onchange={{this.setdata}} /> due to the conciseness of using mut, it may be desireable to reach for it.
Routing in Ember - Learn web development
in this file, change <todolist /> to <todolist @todos={{ @model.activetodos }}/> note that, in each of the route model hooks, we are returning an object with a getter instead of a static object, or more simply just the static list of todos (for example, this.todos.completed).
Ember app structure and componentization - Learn web development
to start with, delete the contents of application.hbs and replace them with the following: <section class="todoapp"> <h1>todos</h1> <input class="new-todo" aria-label="what needs to be done?" placeholder="what needs to be done?" autofocus > </section> note: aria-label provides a label for assistive technology to make use of — for example, for a screenreader to read out.
Accessibility in React - Learn web development
using pseudocode, our logic should be something like this: if (wasnoteditingbefore && iseditingnow) { focusoneditfield() } if (waseditingbefore && isnoteditingnow) { focusoneditbutton() } the react team had discussed ways to get a component’s previous state, and has provided an example custom hook we can use for the job.
React interactivity: Editing, filtering, conditional rendering - Learn web development
when filter is all, for example, filter_map[filter] will evaluate to () => true.
React resources - Learn web development
for this app, we could have for example written a dedicated form.css file to house the styles of those respective components, then imported the styles into their respective modules like this: import form from './form'; import './form.css' this approach makes it easy to identify and manage the css that belongs to a specific component.
Beginning our React todo list - Learn web development
for example: <button type="button" classname="btn toggle-btn" aria-pressed="true"> <span classname="visually-hidden">show </span> <span>all</span> <span classname="visually-hidden"> tasks</span> </button> here, aria-pressed tells assistive technology (like screen readers) that the button can be in one of two states: pressed or unpressed.
Vue conditional rendering: editing existing todos - Learn web development
for example: app.vue <to-do-form> listens for: todo-added event emitted by the onsubmit() method inside the todoform component when the form is submitted.
Creating our first Vue component - Learn web development
we'll see an example of this shortly.
Vue resources - Learn web development
contains comprehensive documentation, including examples, cookbooks, and reference material.
Deploying our app - Learn web development
previous overview: understanding client-side tools in the final article in our series, we take the example toolchain we built up in the previous article and add to it so that we can deploy our sample app.
Accessibility/LiveRegionDevGuide
please refer to the liveregions and gecko python modules in orca for a real world example.
Embedding API for Accessibility
for example, settings per url would allow a user to accept scripts from their known benign web pages, but not others.
Adding phishing protection data providers
you can find examples of how to read and write preferences in the article adding preferences to an extension.
Android-specific test suites
for example, to disable org.mozilla.gecko.permissions.testsuccessrunnableisexecutedifpermissionsaregranted, add @ignore as follows: ...
Testopia
if you are on windows or another case insensitive file system you should first rename the folder (testopia-old for example) and then unzip the tarball.
What to do and what not to do in Bugzilla
for example, don't move bugs into the js engine component unless you really know they are js engine bugs, and don't leave bugs in the js engine component if you know that the malfunction being described is a dom problem.
Capturing a minidump
for example, if the application is hanging (not responding to input, but hasn't crashed) then breakpad is not triggered, and it can be difficult to determine where the problem lies.
Debugging JavaScript
log.jsm (formerly log4moz) this is a partial implementation of the log4* interfaces (for example, see log4j or log4net).
Debugging OpenGL
you don't have to define more than one of these; for example, if you set moz_gl_debug_abort_on_error, the moz_gl_debug setting is assumed.
Debugging Table Reflow
debug_table_strategy editor's note: the following examples are not shown correctly due to the wiki's technical constraint.
Debugging
remote debugging core dumps and examples of remote debugging.
Adding APIs to the navigator object
real-world example you can see an example of how this is used in firefox by taking a look at how the mozapps api is implemented: dom/apps/webapps.manifest dom/apps/webapps.js ...
Gmake vs. Pymake
for example, if using the default objdir, you might type in the root of your source tree: mkdir obj-i686-pc-mingw32; cd obj-i686-pc-mingw32; python ../build/pymake/make.py -f ../client.mk.
Installing headers using EXPORTS
here is an example <tt>makefile.in</tt> which has both c++ and idl headers: module = content xpidl_module = content_base exports = \ nsicontent.h \ nsidocument.h \ nsistylesheet.h \ $(null) xpidlsrcs = \ nsicontentpolicy.idl \ nsiselectioncontroller.idl \ $(null) include $(topsrcdir)/config/rules.mk ...
Updating NSPR or NSS in mozilla-central
for example, in the following, "3.16.1" would be replaced with the new nss version.
pymake
for example: instead of make -f client.mk to start a build, you would type python build/pymake/make.py -f client.mk.
ESLint
for example: in windows 10, if you have installed node.js on "c:\nodejs", then the command should look like: export path=$path:/c/nodejs enabling eslint for a new directory remove the directory from .eslintignore (in the base directory of the repository) fix errors that occur when running ./mach eslint path/to/dir, see also the no-undef rules below.
Eclipse CDT Manual Setup
something like $home/eclipse-workspaces/mozilla-tree-1, for example.
Inner and outer windows
this happens, for example, when a document contains a <frame> or <iframe>.
Contributing to the Mozilla code base
when you commit your code, please use the following format for your commit message: `bug number - what your patch does; r?reviewer` for example, a commit message may look like `bug 1234567 - remove reflow by caching element size.
Listening to events on all tabs
onrefreshattempted notification that a refresh or redirect has been requested in awebprogress for example, via a <meta http-equiv="refresh"> or an http refresh: header.
Reviewer Checklist
which one you choose depends on how the feature is implemented: a pure java service can't easily check gecko prefs, for example.] strings there should be no string changes in patches that will be uplifted (including string removals).
Index
one example is the new tab page, which includes a "top sites" section showing sites you visit that firefox thinks you're likely to want to visit again, as well as potentially some sites that have been pinned to always appear in that space.
Security best practices for Firefox front-end engineers
developers are able to avoid tripping the rule by using escaping functions in combination with template strings, for example: bar.innerhtml = escapehtml`<a href='${url}'>about</a>`; in system-privileged chrome code, any kind of remaining scripts will still be removed by our sanitizer.
Site Identity Button
if the site identity button on your site shows something you do not expect (for example, an orange warning triangle when you expect a green padlock) you can find out the cause of the problem by looking in the web console in the firefox developer tools: ensure your web console is displaying messages in the 'security' category force-refresh the page on your site that is causing problems watch for any security messages that may appear a downgraded security ui will be due to one of these three problems: mixed content - while your page has been served over tls, but subres...
Firefox and the "about" protocol
(question mark) > troubleshooting information) about:sync-log displays a synchronization protocol related to the sync feature about:telemetry displays telemetry data collected and sent to mozilla while firefox is running (in case the user enabled telemetry) about:url-classifier displays the status of the url classifier services that firefox uses (for example for safe browsing) about:webrtc information about webrtc usage about:welcome page first displayed when firefox is installed about:welcomeback information page displayed after firefox is reset these urls are defined in docshell/base/nsaboutredirector.cpp within the kredirmap array.
Firefox
one example is the new tab page, which includes a "top sites" section showing sites you visit that firefox thinks you're likely to want to visit again, as well as potentially some sites that have been pinned to always appear in that space.
Firefox Operational Information Database: SQLite
in the manager, select the database you want to explore in the '(select profile database)' pulldown, click 'go', select one of the tables listed in the left column and see the current contents of the database in the 'browse & search' tab.) some databases are used by the browser itself, others are used by applications that you have installed or used; for example: content-prefs.sqlite cookies.sqlite download.sqlite formhistory.sqlite persmissions.sqlite places.sqlite search.sqlite signons.sqlite webappstore.sqlite ...
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.findAll()
casesensitivity a string to declare whether you want the search to be case sensitive (case-sensitive) or insensitive (case-insensitive.) example the following function is taken from our browser api demo, and executes a search when a search form is submitted.
HTMLIFrameElement.findNext()
examples the following functions are taken from our browser api demo, and cycle through the available search results.
HTMLIFrameElement.getActive()
example var browser = document.queryselector('iframe'); var amiactive = browser.getactive(); specification not part of any specification.
HTMLIFrameElement.getCanGoBack()
example function canmovebwd() { browser.getcangoback().then(function(result) { if (result) { back.disabled = false; console.log("it's possible to navigate the history backward."); } else { back.disabled = true; console.log("it's not possible to navigate the history backward."); } }); } specification not part of any specifica...
HTMLIFrameElement.getCanGoForward()
example function canmovefwd() { browser.getcangoforward().then(function(result) { if (result) { fwd.disabled = false; console.log("it's possible to navigate the history forward."); } else { fwd.disabled = true; console.log("it's not possible to navigate the history forward."); } }); } specification not part of any specificat...
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.getMuted()
example callback version: var browser = document.queryselector('iframe'); var request = browser.getmuted(); request.onsuccess = function() { if(request.result) { console.log('the browser is muted.'); } else { console.log('the browser is unmuted.'); } } promise version: var browser = document.queryselector('iframe'); browser.getmuted().then(function(muted) { if(muted) { console...
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 ...
HTMLIFrameElement.getVisible()
example var browser = document.queryselector('iframe'); var request = browser.getvisible(); request.onsuccess = function() { console.log('the visible state is: ' + this.result ?
HTMLIFrameElement.getVolume()
example callback version: var browser = document.queryselector('iframe'); var request = browser.getvolume(); request.onsuccess = function() { console.log('the current browser volume is ' + request.result); } promise version: var browser = document.queryselector('iframe'); browser.getvolume().then(function(volume) { console.log('the current browser volume is ' + volume); }); specification n...
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 mozbr...
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 moz...
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 ...
mozbrowserclose
example var browser = document.queryselector("iframe"); browser.addeventlistener("mozbrowserclose", function() { console.log("browser window has been closed; iframe will be destroyed."); }); related events mozbrowserasyncscroll mozbrowsercontextmenu mozbrowsererror mozbrowsericonchange mozbrowserloadend mozbrowserloadstart mozbrowserlocationchange mozbrowseropenwindow mozbrowsersecuritych...
mozbrowserdocumentfirstpaint
example var browser = document.queryselector("iframe"); browser.addeventlistener("mozbrowserdocumentfirstpaint", function() { console.log("first content painted."); }); related events mozbrowserasyncscroll mozbrowsercontextmenu mozbrowsererror mozbrowsericonchange mozbrowserloadend mozbrowserloadstart mozbrowserlocationchange mozbrowseropenwindow mozbrowsersecuritychange mozbrowsershowmo...
mozbrowsererror
found dnsnotfound connectionfailure netinterrupt nettimeout cspblocked phishingblocked malwareblocked unwantedblocked offline malformeduri redirectloop unknownsockettype netreset notcached isprinting deniedportaccess proxyresolvefailure proxyconnectfailure contentencodingfailure remotexul unsafecontenttype corruptedcontenterror certerror other example var browser = document.queryselector("iframe"); browser.addeventlistener("mozbrowsererror", function( event ) { console.log("an error occurred:" + event.detail); }); related events mozbrowserasyncscroll mozbrowserclose mozbrowsercontextmenu mozbrowsericonchange mozbrowserloadend mozbrowserloadstart mozbrowserlocationchange mozbrowseropenwindow mozbrowsersecuritychange mozbrowsers...
mozbrowserfindchange
example var browser = document.queryselector("iframe"); browser.addeventlistener("mozbrowserfindchange", function(event) { console.log("currently highlighted: " + event.details.activematchordinal + " out of " + event.details.numberofmatches); }); related events mozbrowserasyncscroll mozbrowsercontextmenu mozbrowsererror mozbrowsericonchange mozbrowserloadend mozbrowserloadstart...
mozbrowserfirstpaint
example var browser = document.queryselector("iframe"); browser.addeventlistener("mozbrowserfirstpaint", function(event) { console.log("first content painted."); }); related events mozbrowserasyncscroll mozbrowsercontextmenu mozbrowsererror mozbrowsericonchange mozbrowserloadend mozbrowserloadstart mozbrowserlocationchange mozbrowseropenwindow mozbrowsersecuritychange mozbrowsershowmodal...
mozbrowsericonchange
example var browser = document.queryselector("iframe"); browser.addeventlistener("mozbrowsericonchange", function( event ) { console.log("the url of the new favicon is:" + event.details.href); }); related events mozbrowserasyncscroll mozbrowserclose mozbrowsercontextmenu mozbrowsererror mozbrowserloadend mozbrowserloadstart mozbrowserlocationchange mozbrowseropenwindow mozbrowsersecurityc...
mozbrowserloadstart
example in this example the mozbrowserloadend and mozbrowserloadstart events are used to change the icon shown on the stop/reload button between stop (x) and reload (r), as appropriate.
mozbrowserlocationchange
example this example updates the url bar so that it will always display the correct url for the current location.
mozbrowsermanifestchange
example var browser = document.queryselector("iframe"); browser.addeventlistener("mozbrowsermanifestchange", function(event) { console.log("new manifest url: " + event.details.href); }); related events mozbrowserasyncscroll mozbrowsercontextmenu mozbrowsererror mozbrowsericonchange mozbrowserloadend mozbrowserloadstart mozbrowserlocationchange mozbrowseropenwindow mozbrowsersecuritychange...
mozbrowsermetachange
example var browser = document.queryselector("iframe"); browser.addeventlistener("mozbrowsermetachange", function(event) { console.log("a meta tag has been " + event.details.type + ".
mozbrowseropensearch
example var browser = document.queryselector("iframe"); browser.addeventlistener("mozbrowseropensearch", function( event ) { console.log("new search engine encountered: " + event.details.title); }); related events mozbrowserasyncscroll mozbrowserclose mozbrowsercontextmenu mozbrowsererror mozbrowsericonchange mozbrowserloadend mozbrowserloadstart mozbrowserlocationchange mozbrowseropenwin...
mozbrowseropenwindow
example var browser = document.queryselector("iframe"); browser.addeventlistener("mozbrowseropenwindow", function( event ) { console.log("a new window has opened containing the content at " + event.details.url + "."); }); related events mozbrowserasyncscroll mozbrowserclose mozbrowsercontextmenu mozbrowsererror mozbrowsericonchange mozbrowserloadend mozbrowserloadstart mozbrowserlocationch...
mozbrowserresize
example var browser = document.queryselector("iframe"); browser.addeventlistener("mozbrowserresize", function( event ) { console.log("the new window size is " + event.details.width + " x " + event.details.height + "."); }); related events mozbrowserasyncscroll mozbrowserclose mozbrowsercontextmenu mozbrowsererror mozbrowsericonchange mozbrowserloadend mozbrowserloadstart mozbrowserlocation...
mozbrowserscroll
example var browser = document.queryselector("iframe"); browser.addeventlistener("mozbrowserscroll", function( event ) { console.log("the new scroll position is " + event.details.left + " across and " + event.details.top + "down."); }); related events mozbrowserasyncscroll mozbrowserclose mozbrowsercontextmenu mozbrowsererror mozbrowsericonchange mozbrowserloadend mozbrowserlo...
mozbrowserscrollviewchange
example var browser = document.queryselector("iframe"); browser.addeventlistener("mozbrowserscrollviewchange", function( event ) { console.log("scrolling has " + event.details.state + "."); }); related events mozbrowserasyncscroll mozbrowserclose mozbrowsercontextmenu mozbrowsererror mozbrowsericonchange mozbrowserloadend mozbrowserloadstart mozbrowserlocationchange mozbrowsersecuritychan...
mozbrowsersecuritychange
example var browser = document.queryselector("iframe"); browser.addeventlistener("mozbrowsersecuritychange", function( event ) { console.log("the ssl state is:" + event.details.state); }); related events mozbrowserasyncscroll mozbrowserclose mozbrowsercontextmenu mozbrowsererror mozbrowsericonchange mozbrowserloadend mozbrowserloadstart mozbrowserlocationchange mozbrowseropenwindow mozbr...
mozbrowserselectionstatechanged
example var browser = document.queryselector("iframe"); browser.addeventlistener("mozbrowserselectionstatechanged", function( event ) { if(event.details.visible) { console.log("the current selection is visible."); } else { console.log("the current selection is not visible."); } }); related events mozbrowserasyncscroll mozbrowserclose mozbrowsercontextmenu mozbrowsererror mozbrowse...
mozbrowsershowmodalprompt
example var browser = document.queryselector("iframe"); browser.addeventlistener("mozbrowsershowmodalprompt", function( event ) { console.log("asking for prompt:" + json.stringify(event.detail)); }); related events mozbrowserasyncscroll mozbrowserclose mozbrowsercontextmenu mozbrowsererror mozbrowsericonchange mozbrowserloadend mozbrowserloadstart mozbrowserlocationchange mozbrowseropenwi...
mozbrowsertitlechange
example var browser = document.queryselector("iframe"); browser.addeventlistener("mozbrowsertitlechange", function( event ) { console.log("the title of the document is:" + event.detail); }); related events mozbrowserasyncscroll mozbrowserclose mozbrowsercontextmenu mozbrowsererror mozbrowsericonchange mozbrowserloadend mozbrowserloadstart mozbrowserlocationchange mozbrowseropenwindow moz...
mozbrowserusernameandpasswordrequired
example var browser = document.queryselector("iframe[mozbrowser]"); browser.addeventlistener("mozbrowserusernameandpasswordrequired", function( event ) { console.log("the auth realm is:" + event.detail.realm); }); related events mozbrowserasyncscroll mozbrowserclose mozbrowsercontextmenu mozbrowsererror mozbrowsericonchange mozbrowserloadend mozbrowserloadstart mozbrowserlocationchange mo...
HTMLIFrameElement.mute()
MozillaGeckoChromeAPIBrowser APImute
example var browser = document.queryselector('iframe'); browser.mute(); specification not in a specification.
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.setActive()
example var browser = document.queryselector('iframe'); browser.setactive(); specification not part of any specification.
HTMLIFrameElement.setVolume()
example var browser = document.queryselector('iframe'); browser.setvolume(0.5); specification not part of any specification.
HTMLIFrameElement.stop()
MozillaGeckoChromeAPIBrowser APIstop
examples stopreload.addeventlistener('touchend',function() { if(stopreload.textcontent === 'x') { browser.stop(); } else { browser.reload(); } }); specification not part of any specification.
HTMLIFrameElement.unmute()
example var browser = document.queryselector('iframe'); browser.unmute(); specification not part of any specification.
Chrome-only API reference
MozillaGeckoChromeAPI
examples of chromeworker's using js-ctypes are availabe on github and are linked to from the see also section below.
CSS -moz-bool-pref() @supports function
example warning: this will only work when loaded from a gecko chrome stylesheet.
-moz-window-dragging
no-drag the window is not draggable formal syntax drag | no-drag example toolbarpaletteitem { -moz-window-dragging: no-drag; } specifications this property is not part of any specification.
::-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 ...
MozScrolledAreaChanged
example document.addeventlistener("mozscrolledareachanged", event => { // find something useful to do with those values event.width; event.height; event.x; event.y; }, false); ...
smartcard-insert
example document.addeventlistener("smartcard-insert", smartcardchangehandler ); related events smartcard-remove ...
smartcard-remove
example document.addeventlistener("smartcard-remove", smartcardchangehandler ); related events smartcard-insert ...
Gecko's "Almost Standards" Mode
for example, consider the following doctype: <!doctype html public "-//w3c//dtd html 4.01 transitional//en" "http://www.w3.org/tr/html4/loose.dtd"> the parts are as follows: public identifier: "-//w3c//dtd html 4.01 transitional//en" system identifier: "http://www.w3.org/tr/html4/loose.dtd" thus any html 4.01 transitional or frameset doctype with a uri (system identifier) will trigger "almost stan...
How to investigate Disconnect failures
an example of such a failure disconnect failures happens when one side is closing the connection and mozmill is unable to send the information over the bridge or when firefox crashes.
How to Report a Hung Firefox
the crash report should look something like this report, which is an example of bug 1132241.
Creating a New Protocol
see dom/ipc/moz.build for an example.
Extending a Protocol
the tutorial is designed for browser engineers who are implementing dom/web apis that need to, for example, send a message to the os or spin up something off the main thread - so it's biased towards supporting w3c/whatwg dom apis.
Infallible memory allocation
choosing a memory allocator as you write new code that needs to allocate memory, there are some simple rules to follow to help you decide whether to use a fallible or an infallible memory allocator: if you're allocating what may be a large chunk of memory, you should allocate the memory fallibly (using malloc() for example), and check the result to be sure it's not null.
Addon
for xpi style add-ons, for example, it tests whether the named file was included in the package.
Code Samples
ource://gre/modules/addonmanager.jsm"); addonmanager.getaddonbyid("youraddon@youraddon.com", function(addon) { addon.uninstall(); }); disable an add-on components.utils.import("resource://gre/modules/addonmanager.jsm"); addonmanager.getaddonbyid("youraddon@youraddon.com", function(addon) { if (addon.isactive) addon.userdisabled = addon.isactive; }); listening for add-on uninstall this example sets a variable beinguninstalled that you can check when you get a profile-before-change message to do cleanup for your add-on on uninstall.
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); } }); ...
DownloadSource
a downloadsource object represents the source of a download, for example a document or an uri.
DownloadTarget
a downloadtarget object represents the target of a download, for example a file in the global downloads directory, or a file in the system temporary directory.
FileUtils.jsm
see also nsifileoutputstream code snippets and examples ...
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.
OS.File.Error
using os.file.error example: finding out whether the problem is due to a file that does not exist try { let file = os.file.open("myfile.txt"); // ...
Services.jsm
for example, to obtain a reference to the preferences service: var prefsservice = services.prefs; provided service getters service accessor service interface service name androidbridge nsiandroidbridge 1 appinfo nsixulappinfo nsixulruntime application information service appshell nsiappshellservice application shell service blockli...
Using workers in JavaScript code modules
for example, "script_url.js" can be "chrome://extension_name/content/script.js".
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 w...
source-editor.jsm
this may be, for example, "\n", "\r", or "\r\n".
L10n Checks
the file names will be shown in a hierarchical form, so in the example above, your files are browser.dtd in ab-cd/browser/chrome/browser and migration.dtd in another directory level deeper.
Localizing XLIFF files for iOS
here is an example of such a <trans-unit> <trans-unit id="add to bookmarks"> <source>add to bookmarks</source> </trans-unit> your translations must be contained inside <target> child tags.
Localizing extension descriptions
the following example demonstrates this (most normal manifest properties have been removed for brevity): <?xml version="1.0"?> <rdf xmlns="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:em="http://www.mozilla.org/2004/em-rdf#"> <description about="urn:mozilla:install-manifest"> <em:id>tabsidebar@blueprintit.co.uk</em:id> <em:localized> <description> <em:locale>de-de</em:locale> ...
Initial setup
here is an example bug that illustrates the process well.
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.
SVN for Localizers
installing svn client: linux users can download the svn client from http://subversion.apache.org/packages.html or install packages provided within their distribution (for example, in debian, sudo apt-get install subversion).
Creating localizable web content
happens for things like faq, or video pages for example.
What every Mozilla translator should know
for example: bug 12345, fix typos and resize prefwindow, a=l10n as soon as you have committed, put the bug in fixed state and write fixed1.8.xxx in the keyword field you have to verify in the next build that the changes have been successful.
Writing localizable code
an example of a well used composite string is firefox's setting for visited pages: the translator can (implicitly) position the text field as he sees fit.
Mozilla Framework Based on Templates (MFBT)
mfbt code goes to some length to document all its interfaces in comments, including examples when possible.
Extras
for example with the style rule: <code style="white-space: nowrap;">*[title] { color: blue; }</code> <math class="cue" display="block"> <mrow> <mrow> <msub title="base-a log"> <mi>log</mi> <mi>a</mi> </msub> <mo>&applyfunction;</mo> <mi>x</mi> </mrow> <mo>=</mo> <mfrac> <mrow> <mi title="natural log">ln</mi> <mo>&applyfunction;</mo> <mi>x</mi> </mrow> <mrow> <mi title="natural log">ln</mi> <mo>&applyfunctio...
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.
Mozilla Port Blocking
see the example below.
Mozilla Development Strategies
you'll need this one for regressions that require your immediate attention (a new crasher, a blocker, or problem in your area, for example).
Mozilla Quirks Mode Behavior
prior to gecko 6.0 (firefox 6.0 / thunderbird 6.0 / seamonkey 2.3), there was no class check, so the :hover pseudoclass was not applied to class selectors; for example, .someclass:hover did not work.
Mozilla Style System Documentation
for example, suppose we had the css stylesheet: /* rule 1 */ doc { display: block; text-indent: 1em; } /* rule 2 */ title { display: block; font-size: 3em; } /* rule 3 */ para { display: block; } /* rule 4 */ [class="emph"] { font-style: italic; } and the following document: <doc> <title>a few quotes</title> <para class="emph">benjamin franklin said that <quote>"a penny saved is a penny earn...
Investigating CSS Performance
for example, hasstatedependentstyle will compute a hint that determines how many elements we'll restyle.
Reporting a Performance Problem
for example you might have one addon that slows down page load and another one that slows down tab switch.
TraceMalloc
this example is for macos; small modifications are needed for other platforms.
perf
the following example shows how to invoke it for this purpose.
Phishing: a short definition
for example, a usb token, bluetooth device, mobile phone, or simply a key stored on a separate device.
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.
javascript.options.strict
example : <html> <head> <title>sample</title> </head> <body> <label id="name">enter you first name</label> <p id ="sample"></p> <script> "use strict" name1= "john" ; // this will cause and an error as variable not declared .
Preferences
examples code snippets preference-related code snippets.
Leak Monitor
it will pop-up an alert when a window is closed and javascript still links to that window (for example, an observer that is not cleared when the window closes).
MailNews automated testing
these tests can go beyond the limitations of xpcshell-tests (for example, access c++ code) and other testing options that don't test at the right level.
NSPR Poll Method
for example, consider an i/o layer that buffers input data.
NSPR's Position On Abrupt Thread Termination
the existence of exit() in the unix/c environment is a perfect example of how programmers will employ the most expediant solution available.
Nonblocking IO In NSPR
one can make the new socket nonblocking by using <tt>pr_setsockopt()</tt> as in the example below (error checking is omitted for clarity): <tt>prfiledesc *sock;</tt> <tt>printn optval = 1;</tt> <tt>sock = pr_newtcpsocket();</tt> /* * make the socket nonblocking */ pr_setsockopt(sock, pr_sockopt_nonblocking, &optval, sizeof(optval)); programming constraints there are some constraints due to the use of nt asynchronous i/o in the nspr.
Date and Time
for example, without specifying the time zone, the time 8:00am 1 may 1998 is ambiguous.
Dynamic Library Linking
for example, link your executable program a.out without the +s option, then execute the following: chatr +s enable a.out on rhapsody, the environment variable is dyld_library_path.
I/O Types
for example, the netscape implementation of the secure sockets layer (ssl) protocol is implemented as an i/o layer on top of nspr's socket layer.
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).
PRIntn
it is guaranteed to be at least 16 bits, though various architectures may define it to be wider (for example, 32 or even 64 bits).
PRUintn
it is guaranteed to be at least 16 bits, though various architectures may define it to be wider (for example, 32 or even 64 bits).
PR_AttachThread
if unsuccessful, for example if system resources are not available, null.
PR_ClearInterrupt
for example, the target thread may reach the agreed-on control point without providing an opportunity for the runtime to notify the thread of the interrupt request.
PR_CreateThread
if unsuccessful, (for example, if system resources are unavailable), null.
PR_INIT_STATIC_CLIST
for example, prclist free_object_list = pr_init_static_clist(&free_object_list); ...
PR ImportTCPSocket
for example, on posix systems, nspr will put the native file descriptor (an int) in non-blocking mode by calling fcntl to set the o_nonblock file status flag on the native file descriptor, and then nspr will call socket functions such as recv, send, and poll on the native file descriptor.
PR_InitializeNetAddr
this may occur, for example, if the value of val is not within the ranges defined by prnetaddrvalue.
PR_IntervalNow
pr_intervalnow() is both very efficient and nonblocking, so it is appropriate to use (for example) while holding a mutex.
PR_JoinThread
returns the function returns one of the following values: if successful, pr_success if unsuccessful--for example, if no joinable thread can be found that corresponds to the specified target thread, or if the target thread is unjoinable--pr_failure.
PR_LOG
for an example of using conditional logging, see use example.
PR_MkDir
for example, if the pathname of the directory to be created is a/b/c/d, the directory a/b/c must already exist.
PR_NewCondVar
if unsuccessful (for example, if system resources are unavailable), null.
PR_NewLock
if unsuccessful (for example, the lock cannot be created because of resource constraints), null.
PR_NewMonitor
if unsuccessful (for example, if some operating system resource is unavailable), null.
PR_NotifyAllCondVar
if unsuccessful (for example, if the caller has not locked the lock associated with the condition variable), pr_failure.
PR_NotifyCondVar
if unsuccessful (for example, if the caller has not locked the lock associated with the condition variable), pr_failure.
PR_PopIOLayer
if the layer is not found in the stack or cannot be popped (for example, the bottommost layer), the function returns null with the error code pr_invalid_argument_error.
PR_SetLogBuffering
the application can use the model provided in use example to effect application logging.
PR_SetLogFile
the application can use the model provided in use example to effect application logging.
PR_Unlock
if unsuccessful (for example, if the caller does not own the lock), pr_failure.
PR_WaitCondVar
if unsuccessful (for example, if the caller has not locked the lock associated with the condition variable or the thread was interrupted with pr_interrupt), pr_failure.
PR_dtoa
for example, with ieee 754 arithmetic, mode 0 gives 1e23 whereas mode 1 gives 9.999999999999999e22.
NSPR API Reference
em information and environment variables logging conditional compilation and execution log types and variables prlogmoduleinfo prlogmodulelevel nspr_log_modules nspr_log_file logging functions and macros pr_newlogmodule pr_setlogfile pr_setlogbuffering pr_logprint pr_logflush pr_log_test pr_log pr_assert pr_assert pr_not_reached use example instrumentation counters named shared memory shared memory protocol named shared memory functions anonymous shared memory anonymous memory protocol anonymous shared memory functions ipc semaphores ipc semaphore functions thread pools thread pool types thread pool functions random number generator random number generator function hash tables hash tables and type c...
NSPR release process
look at their cvs histories for examples.
Running NSPR tests
to run the test suite, run the shell script mozilla/nsprpub/pr/tests/runtests.sh in the directory where the test program binaries reside, for example, cvs -q co -r nspr_4_6_6_rtm mozilla/nsprpub mkdir linux.debug cd linux.debug ../mozilla/nsprpub/configure gmake cd pr/tests gmake ../../../mozilla/nsprpub/pr/tests/runtests.sh the output of the test suite looks like this: nspr test results - tests begin mon mar 12 11:44:41 pdt 2007 nspr_test_logfile /dev/null test result accept ...
Encrypt Decrypt MAC Keys As Session Objects
goto cleanup; } } cleanup: if (infile) { pr_close(infile); } if (headerfile) { pr_close(headerfile); } if (encfile) { pr_close(encfile); } if (slot) { pk11_freeslot(slot); } if (enckey) { pk11_freesymkey(enckey); } if (mackey) { pk11_freesymkey(mackey); } return rv; } /* * this example illustrates basic encryption/decryption and macing * generates the encryption/mac keys and uses token for storing.
Encrypt and decrypt MAC using token
goto cleanup; } } cleanup: if (infile) { pr_close(infile); } if (headerfile) { pr_close(headerfile); } if (encfile) { pr_close(encfile); } if (slot) { pk11_freeslot(slot); } if (enckey) { pk11_freesymkey(enckey); } if (mackey) { pk11_freesymkey(mackey); } return rv; } /* * this example illustrates basic encryption/decryption and macing * generates the encryption/mac keys and uses token for storing.
NSS FAQ
MozillaProjectsNSSFAQ
it was built as an example of an ssl implementation, not for creating production applications.
JSS Provider Notes
the following example shows how you can specify which token is used for various jca operations: // lookup pkcs #11 tokens cryptomanager manager = cryptomanager.getinstance(); cryptotoken tokena = manager.gettokenbyname("tokena"); cryptotoken tokenb = manager.gettokenbyname("tokenb"); // create an rsa keypairgenerator using tokena manager.setthreadtoken(tokena); keypairgenerator rsakpg = keypairgenerator.getinstan...
Mozilla-JSS JCA Provider notes
the following example shows how you can specify which token is used for various jca operations: // lookup pkcs #11 tokens cryptomanager manager = cryptomanager.getinstance(); cryptotoken tokena = manager.gettokenbyname("tokena"); cryptotoken tokenb = manager.gettokenbyname("tokenb"); // create an rsa keypairgenerator using tokena manager.setthreadtoken(tokena); keypairgenerator rsakpg = keypairgenerator.getinstance("...
NSS 3.12.4 release notes
example: *~abc will match any string except abc unions: (foo|bar) will match either the expression foo, or the expression bar.
NSS_3.12_release_notes.html
in pkcs11n.h, all the _netscape_ macros are renamed with _nss_ for example, cko_netscape_crl becomes cko_nss_crl.
NSS 3.24 release notes
note: this approach is only useful when the arena use is tightly bounded, for example, if it is only used in a single function.
NSS 3.44 release notes
se __builtin_bswap64 in crypto_primitives.h 1533216 - cert_decodecertpackage() crash with netscape certificate sequences 1533616 - sdb_getattributevaluenolock should make at most one sql query, rather than one for each attribute 1531236 - provide accessor for certcertificate.dercert 1536734 - lib/freebl/crypto_primitives.c assumes a big endian machine 1532384 - in nss test certificates, use @example.com (not @bogus.com) 1538479 - post-handshake messages after async server authentication break when using record layer separation 1521578 - x25519 support in pk11pars.c 1540205 - freebl build fails with -dnss_disable_chachapoly 1532312 - post-handshake auth doesn't interoperate with openssl 1542741 - certutil -f crashes with segmentation fault 1546925 - allow preceding text in try comment ...
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.
Enc Dec MAC Output Public Key as CSR
key != null); rv = certreq(privkey, pubkey, keytype, hashalgtag, subject, ascii, certreqfilename); if (rv != secsuccess) { pr_fprintf(pr_stderr, "failed to create certificate request\n"); } cleanup: if (privkey) { seckey_destroyprivatekey(privkey); } if (pubkey) { seckey_destroypublickey(pubkey); } return rv; } /* * this example illustrates basic encryption/decryption and macing * generates the rsa key pair as token object and outputs public key as cert request.
Enc Dec MAC Using Key Wrap CertReq PKCS10 CSR
n rv; } /* map option letter to command */ static commandtype option2command(char c) { switch (c) { case 'g': return generate_csr; case 'a': return add_cert_to_db; case 'h': return save_cert_to_header; case 'e': return encrypt; case 'd': return decrypt; case 's': return sign; case 'v': return verify; default: return unknown; } } /* * this example illustrates basic encryption/decryption and macing * generates the rsa key pair as token object and outputs public key as cert request.
Encrypt Decrypt_MAC_Using Token
goto cleanup; } } cleanup: if (infile) { pr_close(infile); } if (headerfile) { pr_close(headerfile); } if (encfile) { pr_close(encfile); } if (slot) { pk11_freeslot(slot); } if (enckey) { pk11_freesymkey(enckey); } if (mackey) { pk11_freesymkey(mackey); } return rv; } /* * this example illustrates basic encryption/decryption and macing.
NSS Sample Code Sample_1_Hashing
this is an example program that demonstrates how to compute the hash of a file and save it to another file.
Initialize NSS database - sample 2
pw(slot, oldpw, newpw) != secsuccess) { pr_fprintf(pr_stderr, "failed to change password.\n"); return secfailure; } port_memset(oldpw, 0, pl_strlen(oldpw)); port_free(oldpw); pr_fprintf(pr_stdout, "password changed successfully.\n"); } port_memset(newpw, 0, pl_strlen(newpw)); port_free(newpw); return secsuccess; } /* * this example illustrates initialization of the nss database.
sample2
tkey); } if (cert) { cert_destroycertificate(cert); } return rv; } /* map option letter to command */ static commandtype option2command(char c) { switch (c) { case 'g': return generate_csr; case 'a': return add_cert_to_db; case 'h': return save_cert_to_header; case 'e': return encrypt; case 'd': return decrypt; case 's': return sign; case 'v': return verify; default: return unknown; } } /* * this example illustrates basic encryption/decryption and macing * generates the rsa key pair as token object and outputs public key as cert request.
NSS Sample Code
sample code 1: key generation and transport between servers sample code 2: symmetric encryption sample code 3: hashing, mac sample code 4: pki encryption sample code 5: pki encryption with a raw public & private key in der format sample code 6: persistent symmetric keys in nss database these are very old examples in need of replacement.
NSS Tools sslstrength
for example, ciphers=bfi will turn on these cipher preferences and turn off all others.
New NSS Samples
these new examples are a work in progress.
PKCS #11 Module Specs
examples: ...
PKCS11 Implement
for example, if a particular token can't do des encryption, nss decrypts the key, then copies it over to the token that can do des encryption.
Installation guide
this is done here: http://lxr.mozilla.org/security/sour...platlibs.mk#53 53 ifeq ($(os_arch), linux) 54 ifeq ($(use_64), 1) 55 extra_shared_libs += -wl,-rpath,'$$origin/../lib64:$$origin/../lib' 56 else 57 extra_shared_libs += -wl,-rpath,'$$origin/../lib' 58 endif 59 endif for example, if you install certutil in /foo/bar/nss/bin and the .so's in /foo/bar/nss/lib, then you only need to add /foo/bar/nss/bin to your path; you don't need to set ld_library_path.
Sample manual installation
for example, <obj-dir> for a debug build of nss on the x86 platform with a linux kernel version 2.6 with glibc would be: linux2.6_x86_glibc_pth_dbg.obj from these directories, you can copy the files to any system (or other) directory.
FC_CancelFunction
examples see also nsc_cancelfunction ...
FC_CloseAllSessions
return value examples see also fc_closesession, nsc_closeallsessions ...
FC_CloseSession
return value examples see also fc_opensession ...
FC_CopyObject
return value examples see also fc_destroyobject, nsc_copyobject ...
FC_CreateObject
return value examples see also fc_destroyobject, nsc_createobject ...
FC_Decrypt
return value examples see also fc_decryptinit, nsc_decrypt ...
FC_DecryptDigestUpdate
return value examples see also nsc_decryptdigestupdate ...
FC_DecryptFinal
return value examples see also fc_decryptinit, nsc_decryptfinal ...
FC_DecryptInit
return value examples see also nsc_decryptinit ...
FC_DecryptUpdate
return value examples see also fc_decryptinit, nsc_decryptupdate ...
FC_DecryptVerifyUpdate
return value examples see also nsc_decryptverifyupdate ...
FC_DeriveKey
return value examples see also nsc_derivekey ...
FC_DestroyObject
return value examples see also nsc_destroyobject ...
FC_Digest
return value examples see also fc_digestinit, nsc_digest ...
FC_DigestEncryptUpdate
return value examples see also nsc_digestencryptupdate ...
FC_DigestFinal
return value examples see also fc_digestinit, nsc_digestfinal ...
FC_DigestInit
return value examples see also nsc_digestinit ...
FC_DigestKey
return value examples see also fc_digestinit, fc_digestfinal, nsc_digestkey ...
FC_DigestUpdate
return value examples see also fc_digestinit, fc_digestfinal, nsc_digestupdate ...
FC_Encrypt
return value examples see also fc_encryptinit, nsc_encrypt ...
FC_EncryptFinal
return value examples see also fc_encryptinit, nsc_encryptfinal ...
FC_EncryptInit
examples see also nsc_encryptinit ...
FC_EncryptUpdate
return value examples see also fc_encryptinit, nsc_encryptupdate ...
FC_Finalize
examples #include <assert.h> ck_function_list_ptr pfunctionlist; ck_rv crv; crv = fc_getfunctionlist(&pfunctionlist); assert(crv == ckr_ok); ...
FC_FindObjects
return value examples see also fc_findobjectsinit, nsc_findobjects ...
FC_FindObjectsFinal
return value examples see also fc_findobjects, nsc_findobjectsfinal ...
FC_FindObjectsInit
return value examples see also fc_findobjects, nsc_findobjectsinit ...
FC_GenerateKey
return value examples see also nsc_generatekey ...
FC_GenerateKeyPair
return value examples see also nsc_generatekeypair ...
FC_GenerateRandom
return value examples see also nsc_generaterandom ...
FC_GetAttributeValue
return value examples see also nsc_getattributevalue ...
FC_GetFunctionList
examples #include <assert.h> ck_function_list_ptr pfunctionlist; ck_rv crv; crv = fc_getfunctionlist(&pfunctionlist); assert(crv == ckr_ok); /* invoke the fc_xxx function as pfunctionlist->c_xxx */ see also nsc_getfunctionlist ...
FC_GetFunctionStatus
examples see also nsc_getfunctionstatus ...
FC_GetMechanismInfo
return value ckr_ok examples see also nsc_getmechanisminfo ...
FC_GetMechanismList
return value ckr_ok examples see also nsc_getmechanismlist ...
FC_GetObjectSize
return value examples see also nsc_getobjectsize ...
FC_GetOperationState
return value examples see also fc_setoperationstate, nsc_getoperationstate ...
FC_GetSessionInfo
return value examples see also fc_closesession, nsc_opensession ...
FC_GetSlotInfo
examples see also nsc_getslotinfo ...
FC_GetSlotList
return value ckr_ok examples see also nsc_getslotlist ...
FC_Logout
return value examples see also fc_closesession, nsc_logout ...
FC_OpenSession
return value examples see also fc_closesession, nsc_opensession ...
FC_SeedRandom
return value examples see also nsc_seedrandom ...
FC_SetAttributeValue
return value examples see also nsc_setattributevalue ...
FC_SetOperationState
return value examples see also fc_getoperationstate, nsc_setoperationstate ...
FC_SetPIN
return value ckr_ok examples see also nsc_setpin ...
FC_Sign
return value examples see also fc_signinit, nsc_sign ...
FC_SignEncryptUpdate
return value examples see also nsc_signencryptupdate ...
FC_SignFinal
return value examples see also fc_signupdate, nsc_signfinal ...
FC_SignInit
return value examples see also nsc_signinit fc_sign fc_signupdate fc_signfinal ...
FC_SignRecover
return value examples see also nsc_signrecover ...
FC_SignRecoverInit
return value examples see also nsc_signrecoverinit ...
FC_SignUpdate
return value examples see also fc_signinit, fc_signfinal, nsc_signupdate ...
FC_UnwrapKey
return value examples see also nsc_unwrapkey ...
FC_Verify
examples see also fc_verifyinit, nsc_verify ...
FC_VerifyFinal
return value examples see also fc_verifyupdate, nsc_verifyfinal ...
FC_VerifyInit
return value examples see also nsc_verifyinit ...
FC_VerifyRecover
return value examples see also nsc_verifyrecover ...
FC_VerifyRecoverInit
return value examples see also nsc_verifyrecoverinit ...
FC_VerifyUpdate
return value examples see also fc_verifyfinal, nsc_verifyupdate ...
FC_WaitForSlotEvent
examples see also fc_waitforslotevent ...
FC_WrapKey
return value examples see also nsc_wrapkey ...
NSC_InitToken
examples application usage nsc_inittoken() is used to reset the password for the key database when the user forgets the password.
ssltyp.html
<a name="> many of the structures presented here (certcertdbhandle, certcertificate, pk11slotinfo, and seckeyprivatekey) are opaque--that is, they are types defined as structures (for example, certcertdbhandlestr) that may change in future releases of network security services.
NSS Tools pk12util
-p prefix specify the prefix used on the cert8.db and key3.db files (for example, my_cert8.db and my_key3.db).
NSS Tools sslstrength
for example, ciphers=bfi will turn on these cipher preferences and turn off all others.
Necko walkthrough
nsdocshell as an example client of the nsihttpchannel api nsdocshell::loaduri(string) create nsiuri from string nsdocshell::loaduri(nsiuri) creates 2 nsiinputstream for read response from; passes them with uri to ...
Pork Tool Development
the "renamer" tool is used as an example; tests are in the "oink/renamer_tests" subdirectory.
Rhino documentation
examples a set of examples showing how to control the javascript engine and build javascript host objects.
Rhino FAQ
for example, creating an array of seven ints can be done with the code var intarray = java.lang.reflect.array.newinstance(java.lang.integer.type, 7); when i try to execute a script i get the exception required security context missing.
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!
Shumway
the next step is to use the inspector included as one of shumway's examples.
SpiderMonkey compartments
compartment example the firefox browser embeds spidermonkey.
Getting SpiderMonkey source code
downloading gzipped spidermonkey source code you can download gzipped spidermonkey source code from the following urls: http://ftp.mozilla.org/pub/spidermonkey/releases/ http://ftp.mozilla.org/pub/spidermonkey/prereleases/ here is a command-line example of downloading and unzipping spidermonkey source code version 59.0: mkdir mozilla cd mozilla wget http://ftp.mozilla.org/pub/spidermonkey/prereleases/59/pre1/mozjs-59.0a1.0.tar.bz2 tar xvf mozjs-59.0a1.0.tar.bz2 these commands should work on most platforms including windows, as long as on windows you are using the mozillabuild bash shell.
Bytecodes
for example, in (a + b) + c you would push a, then push b, then add, then push c, then add, which requires a maximum depth of two expression slots.
Statistics API
for example, the sweep phase includes the time for the sweep_atoms, sweep_tables, sweep_compartments phases and so on.
SpiderMonkey Internals: Thread Safety
exception handling, for example, is per-jscontext.
Tracing JIT
for example, when recording any conditional branch in the spidermonkey bytecode, a guard will be incorported into the trace that checks the branch is taken the same way during execution as it was during recording.
SpiderMonkey Internals
an example, from perfect.js: function perfect(n) { print("the perfect numbers up to " + n + " are:"); // we build sumofdivisors[i] to hold a string expression for // the sum of the divisors of i, excluding i itself.
INT_FITS_IN_JSVAL
example the following code snippet illustrates how a c variable, item, is conditionally tested in an if statement to see if it is a legal jsval integer value.
JS::AutoIdArray
examples { js::autoidarray ids(cx, js_enumerate(cx, obj)); if (!ids) // check the returned value from js_enumerate return false; for (int32_t i = 0, len = ids.length(); i < len; i++) { somefunc(cx, ids[i]); } /* when leaving this scope, the jsidarray returned by js_enumerate is freed.
JS::AutoSaveExceptionState
example // typical usage: bool ok = js::evaluate(cx, ...); autosaveexceptionstate savedexc(cx); ...
JS::AutoValueArray
examples pass to function as a pointer to js::value.
JS::Compile
see also the jsapi user guide contains example code using compiled scripts.
JS::CompileFunction
see also the jsapi user guide contains example code using compiled scripts.
JS::CompileOffThread
see also the jsapi user guide contains example code using compiled scripts.
JS::CompileOptions
for example, js::compileoffthread needs to save compilation options where a worker thread can find them, and then return immediately.
JS::DeflateStringToUTF8Buffer
examples char16_t uchars[] = { 0xd83e, 0xdd8a, 0 }; js::rootedstring str(cx, js_newucstringcopyn(cx, uchars, 2)); if (!str) return false; js::rooted<jsflatstring*> flatstr(cx, js_flattenstring(cx, str)); if (!flatstr) return false; size_t length = js::getdeflatedutf8stringlength(flatstr); char* buffer = static_cast<char*>(js_malloc(cx, length + 1)); if (!buffer) return false; js::deflatestringtoutf...
JS::PersistentRooted
typedef persistentrooted<jsid> persistentrootedid; typedef persistentrooted<jsobject*> persistentrootedobject; typedef persistentrooted<jsscript*> persistentrootedscript; typedef persistentrooted<jsstring*> persistentrootedstring; typedef persistentrooted<js::symbol*> persistentrootedsymbol; // added in spidermonkey 38 typedef persistentrooted<value> persistentrootedvalue; } example following example allocates persistentrootedvalue, and provides two functions for setting and getting it from javascript.
JS::SourceBufferHolder
example size_t length = 512; char16_t* chars = static_cast<char16_t*>(js_malloc(sizeof(char16_t) * length)); js::sourcebufferholder srcbuf(chars, length, js::sourcebufferholder::giveownership); js::compile(cx, obj, options, srcbuf); see also mxr id search for js::sourcebufferholder js::compile js::compilefunction js::evaluate bug 987556 ...
JSAutoByteString
examples use constructor arguments { jsstring *str = js::tostring(cx, strval); if (!str) return false; jsautobytestring bytes(cx, str); /* calls js_encodestring internally */ if (!bytes) return false; /* ...do something with bytes...
JSClass
(this example uses the c++ new and delete keywords, but the application can allocate the memory for private data however it likes.
JSExtendedClass
for example, an object and its wrappers are all equal under ===.
JSFunction
instead of using js_callfunction, for example, it must call js_callfunctionvalue.
JSNative
this has limited use cases; it's used to implement firefox's "slow script" dialog, for example.) when a jsnative is called, no jsstackframe is generated.
JSObjectOps.dropProperty
(that is, for each object, all property accesses happened in some order, and what each thread observed was consistent with that order: no stale reads, for example.) however, spidermonkey does not guarantee this high degree of serialization.
JSObjectOps.setProto
see js_setprototype or js_setparent in js/src/jsobj.cpp for an example.
JSPrincipals
some examples of security-enhanced api call are js_compilescriptforprincipals, js_compilefunctionforprincipals, and js_evaluatescriptforprincipals.
JSRuntime
for example, a browser might create a separate context for each html page; every script in the page could use the same context.
JSVAL_IS_DOUBLE
example the following code snippet illustrates how a javascript variable, myitem, is conditionally tested in an if statement to see if it is a js double data type.
JSVAL_IS_INT
example the following code snippet illustrates how a javascript variable, myitem, is conditionally tested in an if statement to see if it is a js integer data type.
JSVAL_IS_NULL
(note: jsval_is_object(jsval_null) is also true.) example the following code snippet illustrates how a javascript variable, myitem, is conditionally tested in an if statement to see if it contains a null value.
JSVAL_IS_NUMBER
example the following code snippet illustrates how a javascript variable, myitem, is conditionally tested in an if statement to see if it is a js integer or double value.
JSVAL_IS_STRING
example the following code snippet illustrates how a javascript variable, myitem, is conditionally tested in an if statement to see if it is a string.
JSVAL_IS_VOID
example the following code snippet illustrates how a javascript variable, myitem, is conditionally tested in an if statement to see if it is void.
JSVAL_TO_GCTHING
another possible alternative is to avoid casting altogether by using an api that operates on jsvals rather than raw pointers (for example, js_call_value_tracer rather than js_call_tracer).
JS_AddArgumentFormatter
for a given format string, for example "aa", the formatter is called from js_convertargumentsva like so: formatter(cx, "aa...", js_true, &sp, &ap); sp points into the arguments array on the js stack, while ap points into the stdarg.h va_list on the c stack.
JS_Add*Root
(for example, it must not be an uninitialized local variable.
JS_ClearPendingException
see examples in the jsapi phrasebook.
JS_CompileScript
see also the jsapi user guide contains example code using compiled scripts.
JS_CompileUTF8File
see also the jsapi user guide contains example code using compiled scripts.
JS_CompileUTF8FileHandle
see also the jsapi user guide contains example code using compiled scripts.
JS_ContextIterator
example the following code snippet illustrates how to cycle through the contexts for a given runtime: jscontext *acx; jscontext *iterp = null; int i = 0; while ((acx = js_contextiterator(rt, &iterp)) != null) { printf("%d ", ++i); } see also mxr id search for js_contextiterator ...
JS_ConvertArguments
for example, if format is "biob", then js_convertarguments converts the first js value in argv into a bool, the second value into a double, the third value into a jsobject *, and the last value into a bool.
JS_EnterLocalRootScope
for example: jsbool my_getproperty(jscontext *cx, jsobject *obj, jsval id, jsval *vp) { jsbool ok; if (!js_enterlocalrootscope(cx)) return js_false; // this function doesn't need to bother rooting any new objects, // strings, or doubles it creates using cx.
JS_Enumerate
but, for example, if an application calls back into javascript while it is looping over the property ids in the jsidarray, the script could delete properties from obj.
JS_ExecuteScript
the jsapi user guide contains example code using compiled scripts.
JS_FlattenString
example: // in a fallible situation jsflatstring *fstr = js_flattenstring(cx, str); if (!fstr) return false; js_assert(fstr == js_assert_string_is_flat(str)); // in an infallible situation, for the same 'str' const jschar *chars = js_getflatstringchars(fstr) js_assert(chars); see also mxr id search for js_flattenstring js_assert_string_is_flat js_forget_string_flatness bug 609440 ...
JS_GetFunctionId
examples the name returned by js_getfunctiondisplayid is the same as returned by js_getfunctionid if the function explicitly has a name listed in the source, or if not it is an intelligently guessed name for the function based on its context in the source.
JS_GetGlobalForObject
for example, if the function refers to a global variable foo, then foo is a property of the object returned by js_getglobalforobject.
JS_GetNaNValue
for example, 0/0 and math.sqrt(-1) both return nan.
JS_GetParent
for example, after d = new date, d has the same parent as date, ordinarily the global object.
JS_GetPendingException
see examples in the jsapi phrasebook.
JS_GetPositiveInfinityValue
for example, any nonzero value multiplied by infinity is infinity with the expected sign, and any finite value divided by infinity is zero (again with the expected sign).
JS_GetProperty
see also mxr id search for js_getproperty mxr id search for js_getucproperty mxr id search for js_getpropertybyid example in the jsapi phrasebook js_defineproperty js_definepropertywithtinyid js_deleteproperty js_deleteproperty2 js_lookupproperty js_propertystub js_setproperty bug 461163 ...
JS_GetPropertyAttributes
if obj does not have the specified property, or if it inherits it from some other object (on its prototype chain, for example), then *foundp is set to js_false.
JS_IsConstructing_PossiblyWithGivenThisObject
in such cases, the following example would provide the additional information of whether a special this was supplied.
JS_IsExceptionPending
example /* jsapi */ bool pending; js::rootedvalue exception(cx); /* if an exception is pending, save and clear it.
JS_LookupElement
for example, obj[6] is always exactly the same as obj["6"].
JS_LookupProperty
for example, mozilla's document.all property is hidden in this way.
JS_NewScriptObject
(the name "js_newscriptobject" suggests that the script object is freshly allocated; this was the case in older versions of the api, but now the script object is allocated along with the jsscript itself.) (some temporary scripts used internally by spidermonkey do not have script objects allocated for them; such scripts are not accessible via jsapi.) see also the jsapi user guide contains example code using compiled scripts.
JS_PropertyStub
examples at jsclass illustrate how stub functions can be used.
JS_PushArguments
for example, if format is "biob", then there must be four arguments after format.
JS_ReportError
an example is shown in the jsapi phrasebook.
JS_ReportErrorNumber
the source code seems to say we ignore the .exntype, actually, but surely i'm just missing something.) otherwise, if any javascript code is running in cx (for example, if the caller is a jsnative that was called from a script), then an error object is created and becomes the pending exception.
JS_ReportOutOfMemory
when a script tries to grow an array beyond 230-1 elements, for example, or concatenate strings such that the result is more than 229-1 characters long, the javascript engine reports an error as though by calling this function.
JS_SetBranchCallback
for example, the callback my call js_maybegc(cx).
JS_SetCallReturnValue2
an example is in js/src/js.c; searching for js_setcallreturnvalue2 should find it.
JS_SetCheckObjectAccessCallback
this callback is also used to check access to the caller property of function objects (as, for example, when the javascript engine creates a stack trace) and to check access from scripts to properties with scripted getters or setters.
JS_SetContextCallback
for example, the callback my call js_getcontextprivate(cx) in order to free up resources previously allocated by js_setcontextprivate.
JS_SetErrorReporter
example code with error handling omitted: class myrequest { public: void execute() { auto rt = js_newruntime(memlimit); js_setruntimeprivate(rt, this); js_seterrorreporter(rt, &myrequest::dispatcherror); // execute js } void onerror(const std::string& error) { // handle error } static void dispatcherror( jscontext...
JS_SetFunctionCallback
see function tracing for an example.
JS_SetGCCallback
for example, if the jsgc_mark_end callback does something that triggers gc, a jsgc_begin callback might happen.
JS_SetPendingException
see examples in the jsapi phrasebook.
JS_SetPrivate
for example, a socket class might use the private data field to store the socket handle.
JS_ValueToSource
this happens, for example, if v is an object and v.tosource() throws an exception.
JS_ValueToString
this happens, for example, if v is an object and v.tostring() throws an exception.
JS_malloc
here is an example of proper code: /* * `p` points to the memory area to resize.
Parser API
example: > var expr = reflect.parse("obj.foo + 42").body[0].expression > expr.left.property ({loc:null, type:"identifier", name:"foo"}) > expr.right ({loc:{source:null, start:{line:1, column:10}, end:{line:1, column:12}}, type:"literal", value:42}) it is also available since firefox 7; it can be imported into the global object via: components.utils.import("resource://gre/modules/reflect.jsm") or in...
SpiderMonkey 1.8
functions that were js_threadsafe-only in spidermonkey 1.7 (js_beginrequest, for example) are now present, but do nothing, in non-js_threadsafe builds.
Shell global objects
throws in case of internal error, or if the operation doesn't even make sense (for example, because the object is a revoked proxy).
TPS Formdata Lists
for example: var formdata1 = [ { fieldname: "testing", value: "success", date: -1 }, { fieldname: "testing", value: "failure", date: -2 }, { fieldname: "username", value: "joe" } ]; formdata lists and phase actions you can use the following functions in phase actions for formdata lists: formdata.add formdata.delete formdata.verify formdata.verifynot for an example, see the tps formdata unittest: http://hg.mozilla.org/services/tps/f...st_formdata.js notes note 1, tps supports ...
TPS Password Lists
for example: var password_list = [ { hostname: "http://www.example.com", submiturl: "http://login.example.com", username: "joe", password: "secret123", usernamefield: "uname", passwordfield: "pword", changes: { password: "zippity-do-dah" } }, { hostname: "http://www.example.com", realm: "login", username: "joe", password: "secretlogin" } ]; each object has the following properties: hostname: the hostname for the password.
Zest usecase: Reporting Security Vulnerabilities to Developers
when security teams find vulnerabilities they typically describe them to developers using words, for example in a pdf or via a bug tracker.
compare-locales
the file names will be shown in a hierarchical form, so in the example above, your files are browser.dtd in ab-cd/browser/chrome/browser and migration.dtd in another directory level deeper.
Mozinfo
example output: os: linux version: ubuntu 10.10 bits: 32 processor: x86 three of these fields, os, bits, and processor, have a finite set of choices.
Mozilla Projects
it will pop-up an alert when a window is closed and javascript still links to that window (for example, an observer that is not cleared when the window closes).
Using RAII classes in Mozilla
for example, instead of writing: autolock lock(mmutex); which causes the lock to be held until the end of the block, one might write: autolock(mmutex); which erroneously causes the lock to be released at the end of the statement.
The Rust programming language
download the rust compiler, check out examples, and learn everything you could possibly wish to know at the rust official web site.
Handling Mozilla Security Bugs
thus, for example, if a particular security vulnerability is reported initially and then is independently reported again by someone else, each bug reporter retains control over whether to publicly disclose their own bug, but their decision will not affect disclosure for the bug reported by the other person.
Signing Mozilla apps for Mac OS X
however, to modify apple's automatic signing process (for example, to exclude a file or folder), you'll need to provide this file..
Animated PNG graphics
MozillaTechAPNG
for example, if the default image is included in the animation, and uses a blend_op of apng_blend_op_source, clearing is not necessary because the entire output buffer will be overwritten.
Gecko events
this includes for example most of the attributes available via the iaccessiblecomponent interface.
Gecko Roles
for example, a user clicks and drags a sizing grip in the lower-right corner of a window to resize it role_sound represents a system sound, which is associated with various system events.
AT APIs Support
examples of xul applications: firefox - web-browser thunderbird - email client seamonkey - web-browser, advanced e-mail and newsgroup client, irc chat client, and html editing made simple sunbird - cross-platform calendar application kompozer - a complete web authoring system for linux desktop, microsoft windows and macintosh users to rival programs like frontpage and dreamweaver.
Feed content access API
example: reading a feed from the web it's actually quite easy to read and parse a feed.
Mork
MozillaTechMork
for example, the message summary format files use a table for each thread, where the meta-rows represent information about the thread in general.
Using the Places annotation service
for example, "my_extension/page_state".
Places
manipulating bookmarks using places examples for how to work with bookmarks using the places api.
Preferences API
see also code snippets:preferences (more detailed discussion with multiple examples) ...
The Publicity Stream API
example use cases: 'adam got a high score in mafia wars', 'bethany bought a plane ticket to the caribbean', etc.
Toolkit API
mation about how to package extensions theme packaging: specific information about how to package themes multiple-item extension packaging: specific information about multiple-item extension xpis xul application packaging: specific information about how to package xulrunner applications chrome registration printing in xul apps see also the following developer pages contain examples and discussions of particular topics: xul xul overlays developing extensions xulrunner developing themes dom rdf storage ...
XPCOM glue
MozillaTechXPCOMGlue
for example: pkg-config --cflags --libs libxul.pc these instructions are for mozilla 1.8 and above.
Building the WebLock UI
for example, user interface packages often include an english dtd that defines labels and strings for button and menus and other elements in the interface.
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 str...
Detailed XPCOM hashtable guide
for examples of entry classes, see the declarations at xpcom/glue/nshashkeys.h.
mozilla::services namespace
for example, to obtain a reference to the ioservice: nscomptr<nsiioservice> ioservice = mozilla::services::getioservice(); provided service getters service accessor service interface service name getchromeregistryservice nsichromeregistryservice chrome registry service getioservice nsiioservice io service getobserverservice nsiobserverservice observer service getstringbundleservice nsistringbundl...
XPCOM guide
MozillaTechXPCOMGuide
efficient alternative for obtaining a service as compared to the indirect xpcom approach: getservice(), callgetservice(), etc methods are expensive and should be avoided when possible.receiving startup notificationssometimes it's necessary for xpcom components to receive notifications as to the progress of the application's startup process, so they can start new services at appropriate times, for example.xpcom array guidemozilla has many array classes because each array is optimized for a particular usage pattern.
Components.Constructor
for example: var binaryinputstream = components.constructor("@mozilla.org/binaryinputstream;1"); var bis = new binaryinputstream(); print(bis.tostring()); // "[xpconnect wrapped nsisupports]" try { // someinputstream is an existing nsiinputstream // throws because bis hasn't been qi'd to nsibinaryinputstream bis.setinputstream(someinputstream); } catch (e) { bis.queryinterface(components.interfaces...
Components.Exception
can be displayed in the error console when your exception is thrown or in other developer-facing locations, defaulting to 'exception' result the nsresult value of the exception, which defaults to components.results.ns_error_failure stack an xpcom stack to be set on the exception (defaulting to the current stack chain) data any additional data you might want to store, defaulting to null example throw components.exception("i am throwing an exception from a javascript xpcom component."); ...
Components.classes
if this is not the case, you might want to try and find example usages of that component within mxr.
Components.interfaces
for example, assume we have the following interface declaration: interface nsifoo : nsisupports { const pruint32 myflag = 5; }; the constant myflag can then be accessed using var myflag = components.interfaces.nsifoo.myflag; ...
Components.lastResult
example in the following example, the local variable i contains the actual result returned by bar() (assuming that bar() is called via xpconnect), and components.lastresult contains the success code returned by bar().
Components.returnCode
example var foo = { bar: function(i) { if (yada_yada) components.returncode = 5; return i * 2; } }; ...
Components.stack
see usage examples in the mozilla source tree.
Components.utils.cloneInto
example this add-on script creates an object, clones it into the content window and makes it a property of the content window global: // add-on script var addonscriptobject = {"greeting" : "hello from add-on"}; contentwindow.addonscriptobject = cloneinto(addonscriptobject, contentwindow); scripts running in the page can now access the object: // page script button.addeventlistener("click", function() {...
Components.utils.evalInSandbox
for example: function double(n) { return n * 2; } // create new sandbox instance var mysandbox = new components.utils.sandbox("http://www.example.com/"); mysandbox.y = 5; // insert property 'y' with value 5 into global scope.
Components.utils.forceGC
this will make sure that xpcom components that build cycles with javascript objects also get collected which might be important, for example for testcases that depend on the garbage collector.
Components.utils.getGlobalForObject
syntax var global = components.utils.getglobalforobject(obj); parameters obj an object whose corresponding global object is to be retrieved; non-optional, must be object-valued example var obj = {}; function foo() { } var global = this; var g1 = components.utils.getglobalforobject(foo); var g2 = components.utils.getglobalforobject(obj); // g1 === global, g2 === global, g1 === g2 // in a script in another window var global2 = this; function bar() { } var obj2 = {}; // then, assuming bar refers to the function defined in that other window: var o1 = components.utils.getglobalfo...
Components.utils.getWeakReference
example in this example here, a weak reference to a window is held.
Components.utils.makeObjectPropsNormal
example for an example, see components.utils.createobjectin().
Components.utils
getglobalforobject() returns the global object with which a given object is associated (through its prototype chain at birth, for example).
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"); ...
Components.utils.schedulePreciseGC
using scheduleprecisegc() when you call components.utils.scheduleprecisegc(), you specify a callback that is executed in once the scheduled garbage collection has been completed: components.utils.scheduleprecisegc( function() { // this code is executed when the garbage collection has completed } ); since the garbage collection doesn't occur until some time in the future (unlike, for example, components.utils.forcegc(), which causes garbage collection immediately but isn't able to collect all javascript-related memory), the callback lets you know when that's been finished.
Components.utils.unload
example you can unload a module called mymodule.jsm using the following line of code: components.utils.unload("resource://myaddon/modules/mymodule.jsm"); note: currently components.utils.unload clears the global object of an unloaded module.
Components object
utils.getglobalforobject returns the global object with which a given object is associated (through its prototype chain at birth, for example).
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.
Profiling XPCShell
for example, on linux or macosx you do: export mozilla_js_profiler_output=/tmp/profile.txt now, run the script using xpcshell.
xpcshell
example you can input javascript, straight to mozilla.
nsDirectoryService
example code #include "nsxpcom.h" #include "nscomptr.h" #include "nsdirectoryservicedefs.h" #include "nsiservicemanager.h" #include "nsiproperties.h" /** * get the location of the system's "temp" directory.
nsLocalFile
example code function getfilesize(path) { var file = components.classes["@mozilla.org/file/local;1"].
nsScriptableInputStream
example code const nsiscriptableinputstream = components.interfaces.nsiscriptableinputstream; function consumestream(inputstream) { var factory = components.classes["@mozilla.org/scriptableinputstream;1"]; var sis = factory.createinstance(nsiscriptableinputstream); sis.init(inputstream); try { while (true) { var chunk = sis.read(512); if (chunk.length == 0) break; // ok, chunk now contains a portion of the stream's data...
NS_InitXPCOM2
many of the xpcom glue functions and classes are also available prior to xpcom initialization, including for example nsembedcstring and nscomptr.
NS_InitXPCOM3
many of the xpcom glue functions and classes are also available prior to xpcom initialization, including for example nsembedcstring and nscomptr.
NS_NewNativeLocalFile
example code // create a local file that references c:\foo.txt nsresult rv; nscomptr<nsilocalfile> file; rv = ns_newnativelocalfile(nsembedcstring("c:\\foo.txt"), pr_false, getter_addrefs(file)); if (ns_failed(rv)) return rv; here, nsembedcstring is used to convert the ascii string literal to an object that can be passed as a const nsacstring& parameter.
NS_OVERRIDE
example class a has a method getfoo() which is overridden by class b: class a { virtual nsresult getfoo(nsifoo** aresult); }; class b : public a { ns_override virtual nsresult getfoo(nsifoo** aresult); }; later, the signature of a::getfoo() is changed to remove the output parameter: class a { - virtual nsresult getfoo(nsifoo** aresult); + virtual already_addrefed<nsifoo> getfoo(); }; b::getfoo() no longer overrides a::getfoo() as was originally int...
BeginReading
example code // count the number of times a particular character appears in the string pruint32 countchar(const nsacstring& str, char c) { const char* start = str.beginreading(); const char* end = str.endreading(); pruint32 count = 0; while (start != end) { if (*start++ == c) ++count; } return count; } see also length, endreading ...
EndReading
example code see beginreading for an example.
nsACString
see, for example, ns_cstringgetdata.
nsACString_internal
for example, see nststring.
BeginReading
example code // count the number of times a particular character appears in the string pruint32 countchar(const nsastring& str, prunichar c) { const prunichar* start = str.beginreading(); const prunichar* end = str.endreading(); pruint32 count = 0; while (start != end) { if (*start++ == c) ++count; } return count; } see also length ...
EndReading
example code see beginreading for an example.
nsAString
see, for example, ns_stringgetdata.
nsAString_internal
for example, see nststring.
nsAutoRefTraits
for example: ns_specialize_template class nsautoreftraits<prfiledesc> : public nspointerreftraits<prfiledesc> { public: static void release(prfiledesc *ptr) { pr_close(ptr); } }; or ns_specialize_template class nsautoreftraits<fcpattern> : public nspointerreftraits<fcpattern> { public: static void release(fcpattern *ptr) { fcpatterndestroy(ptr); } static void addref(fcpatt...
get
const char_type* get() const; example code nsembedcstring str("hello world"); printf("%s\n", str.get()); ...
nsEmbedCString
see, for example, ns_cstringcontainerinit.
get
const char_type* get() const; example code void getbar(nsastring &result); void func() { nsembedstring str; getbar(str); const prunichar *data = str.get(); ...
nsEmbedString
see, for example, ns_stringcontainerinit.
nsSupportsWeakReference
example code // supporting weak references to a hypothetical implementation // of the nsifoo interface...
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.
amIWebInstallInfo
for example, the referring page for a link to an xpi download.
imgIContainer
auserspacetoimagespace the transformation from user space (for example, appunits) to image space.
imgIDecoderObserver
unfortunately, this is currently the only way to signal decoding errors to consumers, and the only decoding errors that consumers care about (indeed, the only ones that they're prepared to hear about) are failures to instantiate the decoder (<img src="foo.html"> for example).
imgIEncoder
post-multiplied alpha us used (for example 50% transparent red is 0xff000080) input_format_hostargb 2 input is host-endian argb: on big-endian machines each pixel is therefore argb, and for little-endian machiens (intel) each pixel is bgra (this is used by canvas to match it's internal representation) pre-multiplied alpha is used (that is, 50% transparent red is 0x80800000, not 0x80ff0000) possible values for outputoptions.
imgIRequest
note that this might not be the actual uri for the image (for example if http redirects happened during the load).
mozIJSSubScriptLoader
jsval loadsubscript( in string url, in object targetobj optional, in string charset optional, ); example let context = {}; services.scriptloader.loadsubscript("chrome://my-package/content/foo-script.js", context, "utf-8" /* the script's encoding */); parameters url the url pointing to the script to load.
mozIRegistry
i'll talk about them to provide examples of how you should use the other boxes.
mozIStorageConnection
for example: "foo integer, bar string".
mozIStorageService
if your database contains virtual tables (for example, for full-text indexes), you must use mozistorageservice.openunshareddatabase() to open it, since those tables are not compatible with a shared cache.
mozIStorageStatementParams
for example, say you create a statement like so: var statement = dbconn.createstatement("select * from table_name where id = :item_id"); this object would have one property, item_id, that you can use to bind a value to that named parameter like so: statement.params.item_id = 2; for more details on why you should bind parameters as opposed to hard-coding them into your statement, please see the overview document about binding parameters.
mozIStorageStatementRow
for example, say you create a statement like so: var statement = dbconn.createstatement("select id, name from table_name"); the object would have two properties, id and name, that can be used to get the value of the column after you have called mozistoragestatement.executestep() like so: while (statement.executestep()) { let id = statement.row.id; let name = statement.row.name; } see also storage mozistoragestatement ...
mozIStorageVacuumParticipant
you may wish to return false, for example, if you're in the middle of an operation that you don't want to (or can't) interrupt.
nsIAboutModule
the section "firefox 4 (second approach)" provides copy paste code for working example.
nsIAccessibleDocument
for example, in windows you can static cast it to an hwnd.
nsIAccessibleEditableText
for example, sets font styles, such as italic, bold, and so on.
nsIAnnotationService
expire_with_history 5 for annotations that only live as long as the uri is in history (for example, has > 0 visits).
nsIApplicationCacheChannel
this value may be false even if the resource is assigned to an application cache if, for example, it was loaded as a fallback.
nsIAuthInformation
for example, a paragraph in the dialog might say "please enter your password for user jsmith at server intranet".
nsIAuthPrompt2
note: this method may throw any exception when the prompt fails to queue, for example because of out-of-memory error.
nsIAuthPromptProvider
iid the desired interface, for example, ns_get_iid(nsiauthprompt2).
nsIBinaryInputStream
this might be used, for example, to implement network protocols or to read from architecture-neutral disk files, that is ones that can be read and written by both big-endian and little-endian platforms.
nsIBinaryOutputStream
this might be used, for example, to implement network protocols or to produce architecture-neutral binary disk files, that is ones that can be read and written by both big-endian and little-endian platforms.
nsIBrowserHistory
designates the specified url as coming from a link explicitly followed by the user (for example by clicking on it).
nsICacheService
for example, a non-stream-based cache entry can only have a storage policy of store_in_memory.
nsIChannelPolicy
loadtype unsigned long indicates what type of content is being loaded, for example nsicontentpolicy::type_image.
nsIClassInfo
for example, if asked for the helper for nsiprogramminglanguage::javascript this might return an object that can be nsisupports.queryinterface()'d into the nsixpcscriptable interface to assist xpconnect in supplying javascript specific behavior to callers of the instance object.
nsIClipboardCommands
copylinklocation() copy the link location of the current selection (for example the |href| attribute of a selected |a| tag).
nsIClipboardHelper
aclipboardid the id of the clipboard to copy to (for example kselectionclipboard).
nsICommandLineHandler
example: category entry value command-line-handler b-jsdebug @mozilla.org/venkman/clh;1 command-line-handler c-extensions @mozilla.org/extension-manager/clh;1 command-line-handler m-edit @mozilla.org/composer/clh;1 command-line-handler m-irc @mozilla.org/chatzilla/clh...
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.
nsIComponentRegistrar
for example, if the given file is a native library, it must export the symbol nsgetmodule.
nsIConsoleMessage
see nsiscripterror for an example.
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.
nsIContentSniffer
example how to read content from adata.
nsIContentViewManager
this lets you, for example, take the coordinates at which the user clicked (or touched) the screen, and expand outward to create a rectangle from that point.
nsIConverterInputStream
see also nsiconverteroutputstream see reading textual data for an example.
nsIConverterOutputStream
see also nsiconverterinputstream see writing textual data for an example.
nsIDBChangeListener
example here is an example implementation of the listener (that does nothing): var mylistener = { onhdrflagschanged: function(ahdrchanged, aoldflags, anewflags, ainstigator) {}, onhdrdeleted: function(ahdrchanged, aparentkey, aflags, ainstigator) {}, onhdradded: function(ahdrchanged, aparentkey, aflags, ainstigator) {}, onparentchanged: function(akeychanged, oldparent, newparent, ainstigator) {}, onannouncergoingaway: function(ainstigator) {}, onreadchanged: function(ainstigator) {}, onjunkscorechanged: function(ainstigator) {}, onhdrpropertychanged: function(ahdrtochange, aprechange, astatus, ainstigator) {}, onevent: function(adb, aevent...
nsIDNSRecord
acstring getnextaddrasstring(); boolean hasmore(); void rewind(); attributes attribute type description canonicalname acstring for example, www.mozilla.org --> rheet.mozilla.org.
nsIDNSService
example let dnsservice = components.classes["@mozilla.org/network/dns-service;1"] .createinstance(components.interfaces.nsidnsservice); let thread = components.classes["@mozilla.org/thread-manager;1"] .getservice(components.interfaces.nsithreadmanager).currentthread; let host = "www.mozilla.org"; let listener = { onlookupcomplete: function(request, record, status) { ...
nsIDOMFileReader
examples os.file for the main thread - example - save canvas to disk see also file api specification working draft nsidomfile nsidomfilelist nsidomfileexception ...
nsIDOMGeoPositionAddress
dom/interfaces/geolocation/nsidomgeopositionaddress.idlscriptable this interface describes the geographical address of a location, including street, city, and country information, for example.
nsIDOMHTMLAudioElement
for example, specify 44100 for 44.1khz.
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"...
nsIDOMXPathResult
for example, modifying a node invalidates the iterator.
nsIDOMXULElement
focus() attempts to set focus to the element; will not work for example for disabled elements.
nsIDebug2
this often correlates to whether other code (for example, firefox, xulrunner) was compiled with debug defined.
nsIDirectoryServiceProvider
example this code creates a global, read-only string called currdir with the value of the current working directory.
nsIDownload
for example, a private download and a public one might have identical ids.
nsIDroppedLinkHandler
this prevents a source document from tricking the user into a dragging a chrome url for example.
nsIDynamicContainer
containers should follow these when possible, for example, whether to expand queries, etc.
nsIEditor
nsidomnode newleftnode); void joinnodes(in nsidomnode leftnode, in nsidomnode rightnode, in nsidomnode parent); void deletenode(in nsidomnode child); void marknodedirty(in nsidomnode node); direction controller void switchtextdirection(); output methods astring outputtostring(in astring formattype, in unsigned long flags); example: // flags are declared in base/public/nsidocumentencoder.idl // outputselectiononly = 1, outputformatted = 2, // outputraw = 4, outputbodyonly = 8, // outputpreformatted = 16, outputwrap = 32, // outputformatflowed = 64, outputabsolutelinks = 258, // outputencodew3centities = 256, outputcrlinebreak = 512, // outputlflinebreak = 1024, outputnoscri...
nsIEditorSpellCheck
setfilter() used to filter the content (for example, to skip blockquotes in email from spell checking).
nsIEffectiveTLDService
for example, the public suffix for www.bbc.co.uk is co.uk.
nsIEnvironment
examples windows this example gets the path to the porgram files directory on windows.
nsIEventListenerInfo
return value returns a string describing the event listener, or null if serialization isn't possible (for example, if the listener was written in c++).
nsIException
for example, standard language errors would generally have the same location as their top stack entry.
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); }); ...
nsIFaviconService
example var ioservice = components.classes["@mozilla.org/network/io-service;1"] .getservice(components.interfaces.nsiioservice); var pageuri = ioservice.newuri("http://www.mozilla.org/", null, null); var faviconuri = ioservice.newuri("http://www.mozilla.org/favicon.ico", null, null); faviconservice.setandloadfaviconforpage(pageuri, faviconuri, false); setfavicondata()...
nsIFeed
for example, to skip fetching on mondays, a feed that does not want to be fetched on mondays would specify "monday" in this array.
nsIFileProtocolHandler
readurlfile() takes a local file and tries to interpret it as an internet shortcut (for example .url files on windows).
nsIGeolocationProvider
see dom/src/geolocation/networkgeolocationprovider.js for an example of how to write a geolocation provider.
nsIGlobalHistory2
embedders should consider filtering out these schemes and others, for example mailbox:, for the main nsiuri and the referrer.
nsIHttpHeaderVisitor
example this example shows how to detect flash content.
nsIHttpServer
an example : https://github.com/laurentj/slimerjs/blob/master/src/modules/webserver.jsm var exported_symbols = ["create"]; components.utils.import("resource://gre/modules/services.jsm"); function create() { var server = components.classes["@mozilla.org/server/jshttp;1"] .createinstance(components.interfaces.nsihttpserver); return { get objectname () { return "webserver"; }, /** * @param integer|string port port or "host:port" * @param object opt optional options.
nsIHttpUpgradeListener
1.0 66 introduced gecko 6.0 inherits from: nsisupports last changed in gecko 6.0 (firefox 6.0 / thunderbird 6.0 / seamonkey 2.3) this is used, for example, by websockets in order to upgrade an http channel to use the websocket protocol.
nsIInputStream
example consume all data from an input stream using read().
nsILoginManagerCrypto
can throw if the user cancels entry of their master password, or if the ciphertext value can not be successfully decrypted (for example, if it was encrypted with some other key).
nsILoginMetaInfo
for example, "{d4e1a1f6-5ea0-40ee-bff5-da57982f21cf}" timecreated unsigned long long the time, in unix epoch milliseconds, when the login was first created.
nsIMIMEInputStream
example var postdata = components.classes["@mozilla.org/network/mime-input-stream;1"] .createinstance(components.interfaces.nsimimeinputstream); postdata.addheader("content-type", "application/x-www-form-urlencoded"); postdata.addcontentlength = true; postdata.setdata(stringstream); ...
nsIMemory
a client that wishes to be notified of low memory situations (for example, because the client maintains a large memory cache that could be released when memory is tight) should register with the observer service (see nsiobserverservice) using the topic "memory-pressure".
nsIMemoryReporterManager
emoryreporter reporter); void unregistermultireporter(in nsimemorymultireporter reporter); void unregisterreporter(in nsimemoryreporter reporter); attributes attribute type description explicit print64 gets the total size of explicit memory allocations, both at the operating system level (for example, via mmap, virtualalloc) and at the heap level (for example, via malloc(), calloc(), operator new).
nsIMessenger
for example, back-forward history needs a list of visited messages, and where it is in the list.
nsIMicrosummaryGenerator
for generators installed via some other mechanism (for example an extension that dynamically creates generators), this uri is a urn in a form of the extension's own choosing, with the only restriction being that the uri be globally unique.
nsIMsgAccountManagerExtension
an account manager extension with a "name" attribute of "devmo" and the "chromepackagename" attribute set to "extension@example.org" means, that the account manager expects to find a xul file in "chrome://extension@example.org/content/am-devmo.xul" and a property file in "chrome://extension@example.org/locale/am-devmo.properties" containing a property named "prefpanel-devmo".
nsIMsgCustomColumnHandler
example implementation an example javascript implementation that does nothing: var columnhandler = { iseditable: function(arow, acol) {return false;}, cyclecell: function(arow, acol) { }, getcelltext: function(arow, acol) { }, getsortstringforrow: function(ahdr) { return ""; }, isstring: function() {return true;}, getcellproperties: function(arow, acol, aprops) { }, getr...
nsIMsgDBView
typical examples are move or copy commands.
nsIMsgFilterCustomAction
* recommended form: extensionname@example.com#actionname */ readonly attribute acstring id; /* action name to display in action list.
nsIMsgMessageService
e.g., header=filter return the nsiuri that gets run example for example, the next piece of code shows the selected message code on a dialog: (taken from mozillazine) var content = ""; var messageuri = getfirstselectedmessage(); var msgservice = messenger.messageservicefromuri(messageuri); var msgstream = components.classes["@mozilla.org/network/sync-stream-listener;1"].createinstance(); var consumer = msgstream.queryinterface(components.inter...
nsIMsgSearchCustomTerm
* recommended form: extensionname@example.com#termname * commas and quotes are not allowed, the id must not * parse to an integer, and names of standard search * attributes in searchattribentrytable in nsmsgsearchterm.cpp * are not allowed.
nsINavHistoryQueryOptions
an example is to exclude livemark items (parent folders have the "livemark/feeduri" annotation).
nsINavHistoryResultNode
view-implementations may use this value to track the node index in the view, for example the tree view uses this value to indicate the row in the tree that this node is at.
nsINavHistoryService
markpageasfollowedlink() designates the specified url as coming from a link explicitly followed by the user (for example by clicking on it).
nsINavHistoryVisitResultNode
it describes a visit to an entry; you can use it to determine the date and time of the last time the user visited a particular page, for example.
nsIOutputStream
example writesegments() example // copy data from a string to a stream static ns_method copysegment(nsiinputstream* astream, void* aclosure, char* atosegment, pruint32 afromoffset, pruint32 acount, pruint32* areadcount) { // afromsegment now contai...
nsIParserUtils
that is, by default, for example <img> with a source pointing to an http server potentially controlled by a third party is not removed.
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.
nsIPermission
the nsipermission interface defines a "permission" object, which is used to allow or block objects (for example cookies, images) from certain sites based on user preferences.
nsIPrincipal
on the web, for example, a typical principal is comprised of an url scheme, host, and port.
nsIProcess
example // create an nsifile for the executable var file = components.classes["@mozilla.org/file/local;1"] .createinstance(components.interfaces.nsifile); file.initwithpath("c:\\myapp.exe"); // create an nsiprocess var process = components.classes["@mozilla.org/process/util;1"] .createinstance(components.interfaces.nsiprocess); process.init(file); // run th...
nsIProfileLock
(for example, this directory may not be included as part of a backup scheme.) in some cases, this directory may just be the main profile directory.
nsIPrompt
example usage is also documented: using the button flags see also nsipromptservice ...
nsIPropertyBag
examples get user agent information (operating system specifics.
nsISHEntry
example see nssessionstore.js for a real example.
nsISHistory
for example to control memory usage of the browser, to prevent users from loading documents from history, to erase evidence of prior page loads and so on.
nsIScriptError
examples logging a message with additional information in this example nsiscripterror, which implements nsiconsolemessage, is used to log information to the console including information about the source file and line number of the error.
nsIScriptableUnicodeConverter
examples see reading textual data and writing textual data for examples.
nsIScrollable
example var nsiscr = gbrowser.selectedbrowser.docshell.queryinterface(components.interfaces.nsiscrollable); var v={}; var h={}; nsiscr.getscrollbarvisibility(v,h); v.value //returns true if the vertical scrollbar is displayed h.value //returns true if the horizontal scrollbar is displayed ...
nsISimpleEnumerator
see also code example of nsisimpleenumerator ...
nsISocketTransportService
example // at first, we need a nsisockettransportservice ....
nsISound
void playsystemsound( in astring soundalias ); parameters soundalias two different types of names are supported: you can specify the name of a system sound provided by the host operating system; for example, if you specify "systemexclamation", you can play the windows alert sound, but it's played only on windows.
nsIStandardURL
this corresponds to the charset that should be used when communicating this uri to an origin server, for example.
nsIStyleSheetService
see also see using the stylesheet service for examples.
nsISupportsPriority
see also changing the priority of http requests for an example of using this interface to adjust the priority of an http request.
nsITaskbarWindowPreview
for example, the title and icon for each preview always match the title and icon of the corresponding window.
nsITelemetry
example you can find detailed information on adding a new telemetry probe and recording telemetry data at adding a new telemetry probe [en-us].
nsITextInputProcessorCallback
example of simple js-ime: var simpleime = { _hasfocus: false, _hasrightstocompose: false, _tip: null, _callback: function simpleime_callback(atip, anotification) { try { switch (anotification.type) { case "request-to-commit": atip.commitcomposition(); break; case "request-to-cancel": atip.cancelcomposition(); break; case...
nsIThreadObserver
example it is possible to overlay processing events for a gui toolkit on top of the events for a thread: var nativequeue; observer = { ondispatchedevent(thread) { nativequeue.signal(); } onprocessnextevent(thread, maywait, recursiondepth) { if (nativequeue.hasnextevent()) { nativequeue.processnextevent(); } while (maywait && !thread.haspendingevent()) { nativequeue.wai...
nsITimer
remarks type_repeating_slack timer is the preferable repeating timer type for most situations example using initwithcallback: // we need an nsitimercallback compatible...
nsIToolkitProfile
example: var profile = profilelist.getnext().queryinterface(ci.nsitoolkitprofile); var locker = profile.lock({}); remove() removes the profile from the registry of profiles.
nsITransferable
for example, we try to delete data that you copy to the clipboard when you close a private browsing window.
nsITransport
nsitransport implementations may override these status codes with their own more specific status codes (for example, see nsisockettransport).
nsITreeBoxObject
example you deleted the row with index rowindex.
nsITreeSelection
a view can use this to temporarily suppress the selection while manipulating all of the indices, for example, on a sort.
nsIUpdatePrompt
if background is true (for example the download was not user initiated) and the app.update.silent preference is true the call will be a no-op.
nsIUpdateTimerManager
these timers are used to schedule update checks in the future, for example.
nsIUploadChannel
history here is that we need to support both streams that already have headers (for example, content-type and content-length) information prepended to the stream (by plugins) as well as clients (composer, uploading application) that want to upload data streams without any knowledge of protocol specifications.
nsIWebNavigation
there may be cases where the user will be asked to confirm the reload (for example, when it is determined that the request is non-idempotent).
nsIWebNavigationInfo
example let webnavigationinfo_service = components.classes["@mozilla.org/webnavigation-info;1"] .getservice(components.interfaces.nsiwebnavigationinfo); let support_code = webnavigationinfo_service.istypesupported(contenttype, null); if (support_code == webnavigationinfo_service.unsupported) { dump("unsupported content-type: not displaying in the browser\n"); } see als...
nsIWebProgressListener2
for example, via a <meta http-equiv="refresh"> or an http refresh: header.
nsIWifiMonitor
1.0 66 introduced gecko 1.9.1 inherits from: nsisupports last changed in gecko 1.9.1 (firefox 3.5 / thunderbird 3.0 / seamonkey 2.0) this is used, for example, by geolocation to use wifi access points for location detection.
nsIXFormsNSInstanceElement
related interfaces nsixformsmodelelement example code none.
nsIXFormsNSModelElement
related interfaces nsixformsmodelelement example code none.
nsIXPCScriptable
for example, callers must guarantee that they set the *_retval of the various methods that return a boolean to pr_true before making the call.
nsIXULBrowserWindow
this may be used, for example, to redirect links into new tabs or windows when it's not desirable to replace the content in the current tab (such as when the link is clicked in an app tab).
nsIXULBuilderListener
example create an object which implements nsixulbuilderlistener: var mylistener = { queryinterface: function(aiid) { if (aiid.equals(components.interfaces.nsixulbuilderlistener) || aiid.equals(components.interfaces.nsisupports)) return this; throw components.results.ns_nointerface; }, willrebuild : function(builder) {}, didrebuild : function(builder) { } } attach the list...
nsIZipEntry
for example, the entry for the directory foo/ in a zip containing exactly one entry for foo/bar.txt is synthetic.
NS_CStringAppendData
example nscstringcontainer str; ns_cstringcontainerinit(str); ns_cstringsetdata(str, "hello"); ns_cstringappenddata(str, " world"); const char* data; ns_cstringgetdata(str, &data); printf("%s\n", data); // prints out "hello world" ns_cstringcontainerfinish(str); history this function was frozen for mozilla 1.7.
NS_CStringContainerInit
example nscstringcontainer str; if (ns_succeeded(ns_cstringcontainerinit(str))) { // now, |str| can be used with any function taking a nsacstring parameter.
NS_CStringCopy
example /* attribute acstring value; */ ns_imethodimp mycomponent::getvalue(nsacstring& avalue) { return ns_cstringcopy(avalue, mvalue); } ns_imethodimp mycomponent::setvalue(const nsacstring& avalue) { return ns_cstringcopy(mvalue, avalue); } history this function was frozen in mozilla 1.7.
NS_CStringCutData
example code nscstringcontainer str; ns_cstringcontainerinit(str); ns_cstringsetdata(str, "hello world"); // remove " world" portion of string ns_cstringcutdata(str, 5, pr_uint32_max); const char* data; ns_cstringgetdata(str, &data); printf("%s\n", data); // prints out "hello" ns_cstringcontainerfinish(str); history this function was frozen for mozilla 1.7.
NS_CStringGetData
example code // count the number of times a particular character appears in a string.
NS_CStringGetMutableData
example // convert any uppercase ascii letters to lowercase void tolowercase(nscstring &str) { char *iter; pruint32 len = ns_cstringgetmutabledata(str, pr_uint32_max, &iter); char *end = iter + len; while (iter != end) { char c = *iter; if (c >= 'a' && c <= 'z') *iter = c + ('a' - 'a'); ++iter; } } history this function was finalized for mozilla 1.8.
NS_CStringInsertData
example code nscstringcontainer str; ns_cstringcontainerinit(str); ns_cstringsetdata(str, "hello"); ns_cstringinsertdata(str, 5, " world"); const char* data; ns_cstringgetdata(str, &data); printf("%s\n", data); // prints out "hello world" ns_cstringcontainerfinish(str); history this function was frozen for mozilla 1.7.
NS_CStringSetData
example nscstringcontainer str; rv = ns_cstringcontainerinit(str); if (ns_succeeded(rv)) { rv = ns_cstringsetdata(str, "hello world"); if (ns_succeeded(rv)) { // now, pass |str| to some function expecting a |const nsacstring&| parameter.
NS_CStringSetDataRange
example // replace all occurances of |matchval| with |newval| void replacesubstring(nsacstring& str, const nsacstring& matchval, const nsacstring& newval) { const char* sp, *mp, *np; pruint32 sl, ml, nl; sl = ns_cstringgetdata(str, &sp); ml = ns_cstringgetdata(matchval, &mp); nl = ns_cstringgetdata(newval, &np); for (const char* iter = sp; iter ...
NS_CStringToUTF16
example code nsembedcstring str("hello"); nsembedstring ustr; ns_cstringtoutf16(str, ns_cstring_encoding_ascii, ustr); const prunichar *unicharbuf = ustr.get(); history this function was frozen for mozilla 1.7.
NS_StringContainerFinish
example code see ns_stringcontainerinit for an example.
NS_StringContainerInit
example code nsstringcontainer str; if (ns_succeeded(ns_stringcontainerinit(str))) { // now, |str| can be used with any function taking a nsastring parameter.
NS_StringCopy
example code /* attribute acstring value; */ ns_imethodimp mycomponent::getvalue(nsastring& avalue) { return ns_stringcopy(avalue, mvalue); } ns_imethodimp mycomponent::setvalue(const nsastring& avalue) { return ns_stringcopy(mvalue, avalue); } history this function was frozen for mozilla 1.7.
NS_StringGetData
example code pruint32 countchar(const nsastring& str, prunichar c) { const prunichar* data; pruint32 len = ns_stringgetdata(str, &data); pruint32 count = 0; for (pruint32 i = 0; i < len; ++i) { if (data[i] == c) ++count; } return count; } history this function was frozen for mozilla 1.7.
NS_StringSetData
example code nsstringcontainer str; rv = ns_stringcontainerinit(str); if (ns_succeeded(rv)) { rv = ns_stringsetdata(str, "hello world"); if (ns_succeeded(rv)) { // now, pass |str| to some function expecting a |const nsastring&| parameter.
NS_StringSetDataRange
example code // replace all occurances of |matchval| with |newval| void replacesubstring(nsastring& str, const nsastring& matchval, const nsastring& newval) { const prunichar* sp, *mp, *np; pruint32 sl, ml, nl; sl = ns_stringgetdata(str, &sp); ml = ns_stringgetdata(matchval, &mp); nl = ns_stringgetdata(newval, &np); for (con...
NS_UTF16ToCString
example code // convert utf-16 (or ucs-2) string to utf-8 void copyutf16toutf8(const nsastring& in, nsacstring& out) { ns_utf16tocstring(in, ns_cstring_encoding_utf8, out); } history this function was frozen for mozilla 1.7.
nsMsgNavigationType
for example to move forward a message, you would call: // assuming gdbview is a global nsimsgdbview var resultid = new object(); var resultindex = new object(); var threadindex = new object(); gdbview.viewnavigate(components.interfaces.nsmsgnavigationtype.nextmessage, resultid, resultindex, threadindex, true); the nsmsgnavigationtype interface is defined as a global variable in thunderbird: var nsmsgviewcommandtype = components.interfaces.nsmsgviewcommandtype; mailnews/base/public/nsimsgdbview.idlscriptable please add a summary to this article.
nsMsgViewCommandType
for example to mark a message read, you would call: // assuming gdbview is a global nsimsgdbview gdbview.docommand(components.interfaces.nsmsgviewcommandtype.markmessagesread); mailnews/base/public/nsimsgdbview.idlscriptable please add a summary to this article.
nsMsgViewFlagsType
for example, the 'unread only' view would use the flag: components.interfaces.nsmsgviewflagstype.kunreadonly constants name value description knone 0x0 kthreadeddisplay 0x1 kshowignored 0x8 kunreadonly 0x10 kexpandall 0x20 kgroupbysort 0x40 ...
nsMsgViewSortOrder
for example to sort by date you would pass a function the value: components.interfaces.nsmsgviewsortorder.ascending mailnews/base/public/nsimsgdbview.idlscriptable please add a summary to this article.
nsMsgViewSortType
for example to sort by date you would pass a function the value: components.interfaces.nsmsgviewsorttype.bydate mailnews/base/public/nsimsgdbview.idlscriptable please add a summary to this article.
nsMsgViewType
for example, to request the 'show all threads' view use the constant: components.interfaces.nsmsgviewtype.eshowallthreads constants name value description eshowallthreads 0 eshowthreadswithunread 2 eshowwatchedthreadswithunread 3 eshowquicksearchresults 4 eshowvirtualfolderresults 5 eshowsearch 6 ...
Frequently Asked Questions
for example, the assertion occurs when you convert the pointer to the object to a raw pointer to that interface, then assign the raw pointer to another nscomptr for that interface.
Status, Recent Changes, and Plans
added an entire section to the getting started guide on nscomptrs in function signatures added references to recent bugs influencing the use of nscomptr machinery: bug 59212, and bug 59414 fixed comparisons 1 and 3, as per comments by morten welinder updated examples to prefer direct initialization over copy initialization.
Using nsIPasswordManager
the example below should serve as a starting point: // the host name of the password we are looking for var querystring = 'http://www.example.com'; // ask the password manager for an enumerator: var e = passwordmanager.enumerator; // step through each password in the password manager until we find the one we want: while (e.hasmoreelements()) { try { // get an nsipassword object out of the passwor...
Using nsISimpleEnumerator
using nsisimpleenumerator <stringbundle>.strings var enumerator = document.getelementbyid('astringbundleid').strings; var s = ""; while (enumerator.hasmoreelements()) { var property = enumerator.getnext().queryinterface(components.interfaces.nsipropertyelement); s += property.key + ' = ' + property.value + ';\n'; } alert(s); example using javascript 1.7 features // creates a generator iterating over enum's values function generatorfromsimpleenumerator(enum, interface) { while (enum.hasmoreelements()) { yield enum.getnext().queryinterface(interface); } } var b = document.getelementbyid("stringbundleset").firstchild var props = generatorfromenumerator(b.strings, components.interfaces.nsipropertyelement); var s = ""; for (let property in props) { s += property.key + ' =...
Using the Gecko SDK
for example, the nscomptr class is defined in the xpcom glue library.
XPCOM ABI
lpha series x86_64 - amd64/emt64 series in 64-bit mode (32-bit mode is still considered x86) sparc - sparc series ia64 - itanium series {target_compiler_abi}[platforms] represents the compiler abi and may be either: msvc - microsoft visual c++ n32 - irix 6 c++ compiler gcc2 - gnu c++ compiler 2.x gcc3 - gnu c++ compiler 3.x or 4.x sunc - sun c++ compiler ibmc - ibm c++ compiler for example: firefox built with the gnu c++ compiler 4.0.0 for the intel pentium processor would have xpcom abi of x86-gcc3 the xpcom abi string can be retrieved programmatically by using the nsixulruntime interface.
XPCOM ownership guidelines
such a function is the perfect example of something that creates an object with a longer lifespan that itself, and gives away ownership (by producing a pointer that is already addrefed) --- in this case, to the caller.
already_AddRefed
example ...
pyxpidl
/a (this is now the default and can't be turned off) -v verbose mode (nyi) n/a (feature removed) -t creates a typelib of a specific version number n/a (feature removed, and probably never actually worked) -i add an entry to start of include path for #include "nsifoo.idl" -i (unchanged) -o specify the base name for output (-o /tmp/nsifoo for example) -o outputfile (this isn't just the base name, but needs to include the extension; for example -o /tmp/nsifoo.idl) -e specify an explicit output file name (-e /tmp/nsifoo.idl for example) n/a (this is subsumed by -o now) -d write dependencies (requires -e) -d (unchanged) -m specify output mode n/a (feature removed; use header.py or typelib.py specif...
XTF
MozillaTechXTF
for example, the mozilla xforms project uses xtf to add support for the xforms namespace.
Mozilla technologies
for example, the mozilla xforms project uses xtf to add support for the xforms namespace.
The Valgrind Test Job
for example, we have a small number of deliberate but inconsequential memory leaks in the codebase that have corresponding suppressions.
Creating a gloda message query
see gloda examples for more code samples.
DB Views (message lists)
see the tutorial for information about styling trees using css, and the thunderbird source for some example css.
LDAP Support
in this example, we are setting the organization unit as the ldap attribute.
MailNews fakeserver
an example of such a manipulation is adding a folder or adding messages.
The libmime module
there is one header file and one source file for each class (for example, the mimeinlinetext class is defined in "mimetext.h" and "mimetext.c".) each header file follows the following boiler-plate form: typedefs these come first to avoid circular dependencies.
Thunderbird Configuration Files
the path examples above refers to the default profile that is automatically created when you start thunderbird for the first time.
Access Thunderbird Window Areas
an alternative to these methods is to directly access the element by it's id as in the detect when a folder opens example.
Access Window
check if the window is a tab or the root window window.addeventlistener("load", function(e) { alert("is root?: " + isroot()); }, false); function isroot() { if(window != window.top) return "false"; else return "true"; } the example above tells you if the window object is a reference of the application window or of one of it is a tabs.
Add Toolbar Button
example xul overlay file: <?xml version="1.0"?> <?xml-stylesheet href="chrome://demo/skin/overlay.css" type="text/css" ?> <overlay id="messengerwindow" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <script type="application/x-javascript" src="overlay.js" /> <toolbarpalette id="mailtoolbarpalette"> <toolbarbutton id="demo-button" class="demo-button toolbarbutton-1" label="demo" type="button" oncommand="demo.load();" /> </toolbarpalette> </overlay> add this to the css file you referenced in your xul file: #demo-button, [place="palette"] > #demo-button { list-style-image: url("chrome://demo/skin/icon.png") !important; } ...
Detect Opening Folder
some actions require execution every time you open a folder (for example, registering a custom column handler.
Modify Folder Pane Display
see https://addons.mozilla.org/thu...er-categories/ for an example.
Tips and Tricks from the newsgroups
extensions load an extension in its own tab run shell scripts from an extension (for example, to create a symlink) get extension metadata call java from thunderbird extensions (also an example here, written for firefox but compatible with thunderbird 3.x) define a custom protocol handler to call an external program save attachment and send it repeat image display using css sprites messages use reminderfox to open a message in the default thunderbi...
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.
libmime content type handlers
sample content type handler plugin to see an example of a content type handler plugin, the source for the handler of the content type "text/calendar" can be viewed at the following link: calendar plugin note: this plugin simply creates a blue table in the output stream to identify the fact that it is operational, but the basic constructs of what is needed to build a functional content type handler can be seen.
Using Mozilla code in other projects
there are also modules that aren't used in firefox but are available for use by other applications; an example of this is rhino, the javascript engine written in java.
Using popup notifications
for example, this popup notification is displayed when a web site requests geolocation information: this lets the user decide whether or not to share their location when it's convenient to do so, instead of being compelled to do it at once.
Virtualenv
unix example .
Memory Management
for example, a cdata object produced by accessing a field of a structure or the internals of an array will hold the referent objects alive.
CType
example ctypes.uint32_t.tosource() returns "ctypes.uint32_t".
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.
StructType
see opaque structures for further explanation and an example.
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.
Browser Side Plug-in API - Plugins
npn_getvalueforurl provides information to a plug-in which is associated with a given url, for example the cookies or preferred proxy.
DOM Inspector FAQ - Firefox Developer Tools
for example, if you search nodes' tags for "tab", you'll get matches for tabpanel and tabbox as well as tab.
Debugging service workers - Firefox Developer Tools
registration is done with a block of code along these lines, using the register() method: if('serviceworker' in navigator) { navigator.serviceworker .register('sw.js') .then(function() { console.log('service worker registered'); }); } if you get the path wrong, for example, you'll get an error in the web console giving you a hint as to what's wrong, which depends on what exactly is wrong with the code.
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 ...
Browser Toolbox - Firefox Developer Tools
for example, here's what the frame selection popup lists when there are two browser windows open, one with one content tab, and one with two: debugging popups it's hard to debug popups, because the browser hides them as soon as you click outside them.
Debug worker threads - Firefox Developer Tools
inspecting worker code for example, see the selected item worker.js below — it is listed in a separate thread in the sources list, but appears in the source pane in the same way as main thread code when selected.
Disable breakpoints - Firefox Developer Tools
for example: ...
Highlight and inspect DOM nodes - Firefox Developer Tools
a dom object in the watch expressions area, for example, includes a target.
Search - Firefox Developer Tools
for example, if i enter "load" when viewing the above list, i get the following: only the functions with load in their name are shown.
Set a conditional breakpoint - Firefox Developer Tools
this makes it possible to debug specific scenarios, such as bugs that only happen on odd entries in a list, or errors that occur the last time through a loop, for example.
Debugger keyboard shortcuts - Firefox Developer Tools
by default, on some macs, the function key is remapped to use a special feature: for example, to change the screen brightness or the volume.
Set event listener breakpoints - Firefox Developer Tools
so if we choose to log keyboard events, for example, the code no longer pauses as each event is fired: instead, we can then switch to the console, and whenever we press a key we are given a log of where related events were fired.
Debugger.Environment - Firefox Developer Tools
for example, functions whose locals are never aliased may present optimized-out environments.
Debugger.Frame - Firefox Developer Tools
for example, debugger.frame.prototype.eval pushes an "eval" frame for code it runs, whereas debugger.object.prototype.call pushes a "call" frame.
Debugger.Memory - Firefox Developer Tools
for example, it is typical for many objects to have identical sets of properties, with only the properties’ values varying from one object to the next.
Debugger.Source - Firefox Developer Tools
for example, an html document can contain javascript in multiple <script> elements and event handler content attributes.
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.
The Firefox JavaScript Debugger - Firefox Developer Tools
you can use it to debug code running locally in firefox or running remotely, for example on an android device running firefox for android.
All keyboard shortcuts - Firefox Developer Tools
by default, on some macs, the function key is remapped to use a special feature: for example, to change the screen brightness or the volume.
Dominators - Firefox Developer Tools
so when an object becomes unreachable (for example, because it is only referenced by a single local variable which goes out of scope) then any objects it references also become unreachable, as long as no other objects reference them: conversely, this means that objects are kept alive as long as some other reachable object is holding a reference to them.
Inspecting web sockets - Firefox Developer Tools
this filter can be combined with the others, to display, for example, only messages for control frames sent by the browser.
Network monitor recording - Firefox Developer Tools
this is useful in situations where, for example, you are trying to get a stable view of a page for debugging purposes, but under normal circumstances the view keeps evolving due to persistent network requests.
Network request details - Firefox Developer Tools
in the above screenshot for example, the highlighted request's server-timing header contains 4 items — data, markup, total, and miss.
Page inspector 3-pane mode - Firefox Developer Tools
for example, you could edit a css grid property and observe the change immediately in the grid inspector.
CSS Grid Inspector: Examine grid layouts - Firefox Developer Tools
note: the examples shown in the screenshots appearing in this article are jen simmons' futurismo and variations on a grid experiments, and a live named grid area example from rachel andrew.
Intensive JavaScript - Firefox Developer Tools
in this article we'll take an example site whose long-running javascript causes responsiveness problems, and apply two different approaches to fixing them.
UI Tour - Firefox Developer Tools
for example, in the screenshot below a long-running paint operation (shown as a green bar in the waterfall overview) corresponds to a drop in the frame rate: zooming in you can use the overview to select a slice of the recording to examine in more detail.
Rich output - Firefox Developer Tools
for example, by expanding the array in the above list, i get the following: console.log(todolist) (4) […] ​ 0: object { status: "done", description: "morning pages", datecreated: 1552404478137 } ​ 1: object { status: "in progress", description: "refactor styles", datecreated: 1552404493169 } ​ 2: object { status: "to do", description: "create feedback form", datecreated: 1552404512630 } ​ 3: objec...
about:debugging - Firefox Developer Tools
above the usual list of tools, you can see information about the device you are connected to, including the fact that you are connected (in this example) via usb, to firefox preview, on a pixel 2, as well as the title of the page that you are debugging, and the address of the page.
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.
ANGLE_instanced_arrays.vertexAttribDivisorANGLE() - Web APIs
examples var ext = gl.getextension('angle_instanced_arrays'); ext.vertexattribdivisorangle(0, 2); specifications specification status comment angle_instanced_arraysthe definition of 'angle_instanced_arrays' in that specification.
ANGLE_instanced_arrays - Web APIs
examples enabling the extension: var ext = gl.getextension('angle_instanced_arrays'); specifications specification status comment angle_instanced_arraysthe definition of 'angle_instanced_arrays' in that specification.
AbortSignal: abort event - Web APIs
bubbles no cancelable no interface event event handler onabort examples in the following snippets, we create a new abortcontroller object, and get its abortsignal (available in the signal property).
AbortSignal.aborted - Web APIs
syntax var isaborted = abortsignal.aborted; value a boolean examples in the following snippet, we create a new abortcontroller object, and get its abortsignal (available in the signal property).
AbortSignal.onabort - Web APIs
}; examples in the following snippet, we create a new abortcontroller object, and get its abortsignal (available in the signal property).
AbstractWorker.onerror - Web APIs
}; example the following code snippet shows creation of a worker object using the worker() constructor and setting up of an onerror handler on the resulting object: var myworker = new worker('worker.js'); myworker.onerror = function() { console.log('there is an error with your worker!'); } specifications specification status comment html living standardthe definition of 'abstractworker.onerror' in that specification.
AddressErrors.organization - Web APIs
for example, if validation simply ensures that only permitted characters are included in the organization's name, this might return a string such as "the organization name may only contain the letters a-z, digits, spaces, and commas." if the organization value was validated successfully, this property is not included in the addresserrors object.
AesKeyGenParams - Web APIs
examples see the examples for subtlecrypto.generatekey().
AmbientLightSensor.illuminance - Web APIs
example if ( 'ambientlightsensor' in window ) { const sensor = new ambientlightsensor(); sensor.onreading = () => { console.log('current light level:', sensor.illuminance); }; sensor.onerror = (event) => { console.log(event.error.name, event.error.message); }; sensor.start(); } specifications specification status comment generic sensor api candidate recom...
AmbientLightSensor - Web APIs
example if ( 'ambientlightsensor' in window ) { const sensor = new ambientlightsensor(); sensor.onreading = () => { console.log('current light level:', sensor.illuminance); }; sensor.onerror = (event) => { console.log(event.error.name, event.error.message); }; sensor.start(); } specifications specification status comment generic sensor api candidate recom...
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 th...
Animation.currentTime - Web APIs
examples in the drink me/eat me game, alice's height is animated so it can go from small to large or large to small.
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
WebAPIAnimationid
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.oncancel - Web APIs
examples if this animation is canceled, remove its element.
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 = functi...
Animation.persist() - Web APIs
WebAPIAnimationpersist
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.play() - Web APIs
WebAPIAnimationplay
return value undefined example in the growing/shrinking alice game example, clicking or tapping the cake causes alice's growing animation (alicechange) to play forward, causing her to get bigger, as well as triggering the cake's animation.
Animation.playState - Web APIs
example in the growing/shrinking alice game example, players can get an ending with alice crying into a pool of tears.
Animation.ready - Web APIs
WebAPIAnimationready
you'll typically use a construct similar to this when using the ready promise: animation.ready.then(function() { // do whatever needs to be done when // the animation is ready to run }); example in the following example, the state of the animation will be running when the current ready promise is resolved because the animation does not leave the pending play state in between the calls to pause and play and hence the current ready promise does not change.
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 = functi...
Animation.reverse() - Web APIs
WebAPIAnimationreverse
return value undefined example in the growing/shrinking alice game example, clicking or tapping the bottle causes alice's growing animation (alicechange) to play backwards, causing her to get smaller.
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 we...
Attr.namespaceURI - Web APIs
WebAPIAttrnamespaceURI
syntax namespace = attribute.namespaceuri example in this snippet, an attribute is being examined for its localname and its namespaceuri.
AudioBuffer.copyFromChannel() - Web APIs
example this example creates a new audio buffer, then copies the samples from another channel into it.
AudioBuffer.copyToChannel() - Web APIs
example var myarraybuffer = audioctx.createbuffer(2, framecount, audioctx.samplerate); var anotherarray = new float32array; // copy channel data from second channel of myarraybuffer.
AudioBuffer.duration - Web APIs
example // stereo var channels = 2; // create an empty two second stereo buffer at the // sample rate of the audiocontext var framecount = audioctx.samplerate * 2.0; var myarraybuffer = audioctx.createbuffer(2, framecount, audioctx.samplerate); button.onclick = function() { // fill the buffer with white noise; // just random values between -1.0 and 1.0 for (var channel = 0; channel < channels; channel++) { // this gives us the actual arraybuffer that contains the data var nowbuffering = myarraybuffer.getch...
AudioBuffer.getChannelData() - Web APIs
example in the following example we create a two second buffer, fill it with white noise, and then play it via an audiobuffersourcenode.
AudioBuffer.length - Web APIs
example // stereo var channels = 2; // create an empty two second stereo buffer at the // sample rate of the audiocontext var framecount = audioctx.samplerate * 2.0; var myarraybuffer = audioctx.createbuffer(2, framecount, audioctx.samplerate); button.onclick = function() { // fill the buffer with white noise; // just random values between -1.0 and 1.0 for (var channel = 0; channel < channels; channel++) { // this gives us the actual arraybuffer that contains the data var nowbuffering = myarraybuffer.get...
AudioBuffer.numberOfChannels - Web APIs
example // stereo var channels = 2; // create an empty two second stereo buffer at the // sample rate of the audiocontext var framecount = audioctx.samplerate * 2.0; var myarraybuffer = audioctx.createbuffer(2, framecount, audioctx.samplerate); button.onclick = function() { // fill the buffer with white noise; // just random values between -1.0 and 1.0 for (var channel = 0; channel < channels; channel++) { // this gives us the actual arraybuffer that contains the data ...
AudioBuffer.sampleRate - Web APIs
example // stereo var channels = 2; // create an empty two second stereo buffer at the // sample rate of the audiocontext var framecount = audioctx.samplerate * 2.0; var myarraybuffer = audioctx.createbuffer(2, framecount, audioctx.samplerate); button.onclick = function() { // fill the buffer with white noise; // just random values between -1.0 and 1.0 for (var channel = 0; channel < channels; channel++) { ...
AudioBufferSourceNode.buffer - Web APIs
example for a full working example, see this code running live, or view the source.
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 ...
AudioContext() - Web APIs
example this example creates a new audiocontext for interactive audio (optimizing for latency) and a sample rate of 44.1khz.
AudioContext.baseLatency - Web APIs
example // default latency ("interactive") const audioctx1 = new audiocontext(); console.log(audioctx1.baselatency); // 0.00 // higher latency ("playback") const audioctx2 = new audiocontext({ latencyhint: 'playback' }); console.log(audioctx2.baselatency); // 0.15 specifications specification status comment web audio apithe definition of 'baselatency' in that specification.
AudioContext.createJavaScriptNode() - Web APIs
example the following script illustrates the use of createjavascriptnode(): var sinewave = function(context) { var that = this; this.x = 0; // initial sample number this.context = context; this.node = context.createjavascriptnode(1024, 1, 1); this.node.onaudioprocess = function(e) { that.process(e) }; } sinewave.prototype.process = function(e) { var data = e.outputbuffer.getchanneldata(0);...
AudioContext.createMediaStreamTrackSource() - Web APIs
example in this example, getusermedia() is used to request access to the user's microphone.
AudioContext.outputLatency - Web APIs
example const audioctx = new audiocontext(); console.log(audioctx.outputlatency); specifications specification status comment web audio apithe definition of 'outputlatency' in that specification.
AudioContext.resume() - Web APIs
example the following snippet is taken from our audiocontext states demo (see it running live.) when the suspend/resume button is clicked, the audiocontext.state is queried — if it is running, suspend() is called; if it is suspended, resume() is called.
AudioContext.suspend() - Web APIs
example the following snippet is taken from our audiocontext states demo (see it running live.) when the suspend/resume button is clicked, the audiocontext.state is queried — if it is running, suspend() is called; if it is suspended, resume() is called.
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.
AudioContextOptions - Web APIs
example this example instantiates an audio context for music playback (optimized for power consumption over latency), with the sample rate 48,000 hz.
AudioDestinationNode.maxChannelCount - Web APIs
example 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 examp...
AudioNode.channelCount - Web APIs
example var audiocontext = window.audiocontext || window.webkitaudiocontext; var audioctx = new audiocontext(); var oscillator = audioctx.createoscillator(); var gainnode = audioctx.creategain(); oscillator.connect(gainnode); gainnode.connect(audioctx.destination); oscillator.channelcount; specifications specification status comment web audio apithe definition of 'channelc...
AudioNode.channelCountMode - Web APIs
example var audiocontext = window.audiocontext || window.webkitaudiocontext; var audioctx = new audiocontext(); var oscillator = audioctx.createoscillator(); var gainnode = audioctx.creategain(); oscillator.connect(gainnode); gainnode.connect(audioctx.destination); oscillator.channelcountmode = 'explicit'; specifications specification status comment web audio apithe defini...
AudioNode.channelInterpretation - Web APIs
example var audiocontext = window.audiocontext || window.webkitaudiocontext; var audioctx = new audiocontext(); var oscillator = audioctx.createoscillator(); var gainnode = audioctx.creategain(); oscillator.connect(gainnode); gainnode.connect(audioctx.destination); oscillator.channelinterpretation = 'discrete'; specifications specification status comment web audio apithe d...
AudioNode.context - Web APIs
WebAPIAudioNodecontext
example const audiocontext = window.audiocontext || window.webkitaudiocontext; const audioctx = new audiocontext(); const oscillator = audioctx.createoscillator(); const gainnode = audioctx.creategain(); oscillator.connect(gainnode).connect(audioctx.destination); console.log(oscillator.context); // audiocontext console.log(oscillator.context === audioctx); // true specifications specification status comment web audio apithe definition of 'context...
AudioNode.disconnect() - Web APIs
example var audiocontext = window.audiocontext || window.webkitaudiocontext; var audioctx = new audiocontext(); var oscillator = audioctx.createoscillator(); var gainnode = audioctx.creategain(); oscillator.connect(gainnode); gainnode.connect(audioctx.destination); gainnode.disconnect(); specifications specification status comment web audio apithe definition of 'disconnect...
AudioNode.numberOfInputs - Web APIs
example const audioctx = new audiocontext(); const oscillator = audioctx.createoscillator(); const gainnode = audioctx.creategain(); oscillator.connect(gainnode).connect(audioctx.destination); console.log(oscillator.numberofinputs); // 0 console.log(gainnode.numberofinputs); // 1 console.log(audioctx.destination.numberofinputs); // 1 specifications specification status comment web audio apithe definition of 'numberofinputs' in that specification.
AudioNode.numberOfOutputs - Web APIs
example const audioctx = new audiocontext(); const oscillator = audioctx.createoscillator(); const gainnode = audioctx.creategain(); oscillator.connect(gainnode).connect(audioctx.destination); console.log(oscillator.numberofoutputs); // 1 console.log(gainnode.numberofoutputs); // 1 console.log(audioctx.destination.numberofoutputs); // 0 specifications specification status comment web audio apithe definition of 'numberofoutputs' in that specification.
AudioNodeOptions - Web APIs
see for example analysernode.analysernode or gainnode.gainnode.
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.defaultValue - Web APIs
example const audioctx = new audiocontext(); const gainnode = audioctx.creategain(); const defaultval = gainnode.gain.defaultvalue; console.log(defaultval); // 1 console.log(defaultval === gainnode.gain.value); // true specifications specification status comment web audio apithe definition of 'defaultvalue' in that specification.
AudioParam.maxValue - Web APIs
example const audioctx = new audiocontext(); const gainnode = audioctx.creategain(); console.log(gainnode.gain.maxvalue); // 3.4028234663852886e38 specifications specification status comment web audio apithe definition of 'maxvalue' in that specification.
AudioParam.minValue - Web APIs
example const audioctx = new audiocontext(); const gainnode = audioctx.creategain(); console.log(gainnode.gain.minvalue); // -3.4028234663852886e38 specifications specification status comment web audio apithe definition of 'minvalue' in that specification.
AudioParamDescriptor - Web APIs
examples to demonstrate creation and usage of custom audioparams, we'll expand the example from audioworkletnode page.
AudioScheduledSourceNode.start() - Web APIs
example this example demonstrates how to create an oscillatornode which is scheduled to start playing in 2 seconds and stop playing 1 second after that.
AudioScheduledSourceNode.stop() - Web APIs
example this example demonstrates starting an oscillator node, scheduled to begin playing at once and to stop playing in one second.
AudioTrack.kind - Web APIs
WebAPIAudioTrackkind
this might be used to contain the director's commentary track on a movie, for example.
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.getTrackById() - Web APIs
example this example suggests a hypothetical game in which movies are used as cut-scenes or other key set pieces within the game.
AudioTrackList.length - Web APIs
example this snippet gets the number of audio tracks in the first <video> element found in the dom by queryselector().
AudioTrackList.onaddtrack - Web APIs
example this snippet establishes a handler for the addtrack event that calls a function, addtotracklist(), passing in the audiotrack object representing the newly-added track.
AudioTrackList.onremovetrack - Web APIs
example this simple example just fetches the current number of audio tracks in the media element whenever a track is removed from the media element.
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.
AudioWorklet - Web APIs
examples see audioworkletnode for complete examples of custom audio node creation.
AudioWorkletGlobalScope.registerProcessor - Web APIs
examples in this example we create a custom audioworkletnode that outputs silence.
AudioWorkletNode.onprocessorerror - Web APIs
}; examples // fill in example snippet specifications specification status comment web audio apithe definition of 'onprocessorerror' in that specification.
AudioWorkletNode.parameters - Web APIs
examples to demonstrate creation and usage of custom audioparams, we'll expand the example from audioworkletnode page.
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.
AudioWorkletNode - Web APIs
examples in this example we create a custom audioworkletnode that outputs white noise.
AudioWorkletProcessor.parameterDescriptors (static getter) - Web APIs
examples to demonstrate creation and usage of custom audioparams, we'll expand the example from audioworkletnode page.
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 ...
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 - 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 ...
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.challen...
BaseAudioContext.audioWorklet - Web APIs
examples for a complete example demonstrating user-defined audio processing, see the audioworkletnode page.
BaseAudioContext.createBufferSource() - Web APIs
example in this example, we create a two second buffer, fill it with white noise, and then play it via an audiobuffersourcenode.
BaseAudioContext.createChannelMerger() - Web APIs
example the following example shows how you could separate a stereo track (say, a piece of music), and process the left and right channel differently.
BaseAudioContext.createChannelSplitter() - Web APIs
example the following simple example shows how you could separate a stereo track (say, a piece of music), and process the left and right channel differently.
BaseAudioContext.createDelay() - Web APIs
example we have created a simple example that allows you to play three different samples on a constant loop — see create-delay (you can also view the source code).
BaseAudioContext.createPeriodicWave() - Web APIs
example the following example illustrates simple usage of createperiodicwave(), to create a periodicwave object containing a simple sine wave.
BaseAudioContext.createStereoPanner() - Web APIs
example in our stereopannernode example (see source code) html we have a simple <audio> element along with a slider <input> to increase and decrease pan value.
BaseAudioContext.currentTime - Web APIs
syntax var curtime = baseaudiocontext.currenttime; example var audiocontext = window.audiocontext || window.webkitaudiocontext; var audioctx = new audiocontext(); // older webkit/blink browsers require a prefix ...
BaseAudioContext.destination - Web APIs
example note: for a full example implementation, see one of our web audio demos on the mdn github repo, like voice-change-o-matic.
BaseAudioContext.listener - Web APIs
example note: for a full web audio spatialization example, see our panner-node demo.
BaseAudioContext.onstatechange - Web APIs
}; example the following snippet is taken from our audiocontext states demo (see it running live.) the onstatechange hander is used to log the current state to the console every time it changes.
BaseAudioContext.sampleRate - Web APIs
example note: for a full web audio example implementation, see one of our web audio demos on the mdn github repo, like panner-node.
BaseAudioContext.state - Web APIs
closed: the audio context has been closed (with the audiocontext.close() method.) example the following snippet is taken from our audiocontext states demo (see it running live.) the audiocontext.onstatechange hander is used to log the current state to the console every time it changes.
BasicCardRequest.supportedNetworks - Web APIs
legal values are defined in the w3c's document card network identifiers approved for use with payment request api, and are currently: amex cartebancaire diners discover jcb mastercard mir unionpay visa example the following example shows a sample definition of the first parameter of the paymentrequest() constructor, the data property of which contains supportednetworks and supportedtypes properties.
BasicCardRequest.supportedTypes - Web APIs
legal values are defined in basiccardtype enum, and are currently: credit debit prepaid example the following example shows a sample definition of the first parameter of the paymentrequest() constructor, the data property of which contains supportednetworks and supportedtypes properties.
BasicCardResponse.billingAddress - Web APIs
example let's look at a sample payment request: var request = new paymentrequest(supportedinstruments, details, options); // call show() to trigger the browser's payment flow.
BasicCardResponse.cardNumber - Web APIs
example let's look at a sample payment request: var request = new paymentrequest(supportedinstruments, details, options); // call show() to trigger the browser's payment flow.
BasicCardResponse.cardSecurityCode - Web APIs
example let's look at a sample payment request: var request = new paymentrequest(supportedinstruments, details, options); // call show() to trigger the browser's payment flow.
BasicCardResponse.cardholderName - Web APIs
example let's look at a sample payment request: var request = new paymentrequest(supportedinstruments, details, options); // call show() to trigger the browser's payment flow.
BasicCardResponse.expiryMonth - Web APIs
example let's look at a sample payment request: var request = new paymentrequest(supportedinstruments, details, options); // call show() to trigger the browser's payment flow.
BasicCardResponse.expiryYear - Web APIs
example let's look at a sample payment request: var request = new paymentrequest(supportedinstruments, details, options); // call show() to trigger the browser's payment flow.
BatteryManager.charging - Web APIs
example html content <div id="charging">(charging state unknown)</div> javascript content navigator.getbattery().then(function(battery) { var charging = battery.charging; document.queryselector('#charging').textcontent = charging ; }); specifications specification status comment battery status api candidate recommendation initial definition ...
BatteryManager.chargingTime - Web APIs
example html content <div id="chargingtime">(charging time unknown)</div> javascript content navigator.getbattery().then(function(battery) { var time = battery.chargingtime; document.queryselector('#chargingtime').textcontent = battery.chargingtime; }); specifications specification status comment battery status api candidate recommendation initial defin...
BatteryManager.dischargingTime - Web APIs
example html content <div id="dischargingtime">(discharging time unknown)</div> javascript content navigator.getbattery().then(function(battery) { var time = battery.dischargingtime; document.queryselector('#dischargingtime').textcontent = battery.dischargingtime; }); specifications specification status comment battery status api candidate recommendation...
BatteryManager.level - Web APIs
example html content <div id="level">(battery level unknown)</div> javascript content navigator.getbattery().then(function(battery) { var level = battery.level; document.queryselector('#level').textcontent = level; }); specifications specification status comment battery status api candidate recommendation initial definition ...
BatteryManager.onchargingchange - Web APIs
example html content <div id="level">(battery level unknown)</div> <div id="chargingtime">(charging time unknown)</div> javascript content navigator.getbattery().then(function(battery) { battery.onchargingchange = chargingchange(); function chargingchange() { document.queryselector('#level').textcontent = battery.level; document.queryselector('#chargingtime').textcontent = battery.chargingtime; } }); specifications specification status comment bat...
BatteryManager.onchargingtimechange - Web APIs
example html content <div id="level">(battery level unknown)</div> <div id="chargingtime">(charging time unknown)</div> javascript content navigator.getbattery().then(function(battery) { battery.onchargingtimechange = chargingtimechange(); function chargingtimechange(){ document.queryselector('#level').textcontent = battery.level; document.queryselector('#chargingtime').textcontent = battery.chargingtime; } }); specifications specification statu...
BatteryManager.ondischargingtimechange - Web APIs
example html content <div id="level">(battery level unknown)</div> <div id="chargingtime">(charging time unknown)</div> javascript content navigator.getbattery().then(function(battery) { battery.ondischargingtimechange = dischargingtimechange; function dischargingtimechange(){ document.queryselector('#level').textcontent = battery.level; document.queryselector('#chargingtime').textcontent = battery.chargingtime; } }); specifications spe...
BatteryManager.onlevelchange - Web APIs
example html <div id="level">(battery level unknown)</div> <div id="statebaterry">(charging state unknown)</div> javascript navigator.getbattery().then(function(battery) { battery.onlevelchange = function(){ document.queryselector('#level').textcontent = battery.level; if(battery.charging) { document.queryselector('#statebaterry').textcontent = "charging time: " + (battery.chargingtime / 60); } else { document.queryselect...
BeforeInstallPromptEvent.prompt() - Web APIs
example var istoosoon = true; window.addeventlistener("beforeinstallprompt", function(e) { if (istoosoon) { e.preventdefault(); // prevents prompt display // prompt later instead: settimeout(function() { istoosoon = false; e.prompt(); // throws if called more than once or default not prevented }, 10000); } // the event was re-dispatched in response to our request // ...
BiquadFilterNode.getFrequencyResponse() - Web APIs
example in the following example we are using a biquad filter on a media stream (for the full demo, see our stream-source-buffer demo live, or read the source.) as part of this demo, we get the frequency responses for this biquad filter, for five sample frequencies.
Blob() - Web APIs
WebAPIBlobBlob
example var afileparts = ['<a id="a"><b id="b">hey!</b></a>']; // an array consisting of a single domstring var omyblob = new blob(afileparts, {type : 'text/html'}); // the blob specification specification status comment file apithe definition of 'blob()' in that specification.
Blob.arrayBuffer() - Web APIs
WebAPIBlobarrayBuffer
this can happen, for example, if the reader used to fetch the blob's data throws an exception.
Blob.size - Web APIs
WebAPIBlobsize
example this example uses an <input> element of type file to ask the user for a group of files, then iterates over those files outputting their names and lengths in bytes.
Blob.type - Web APIs
WebAPIBlobtype
example this example asks the user to select a number of files, then checks each file to make sure it's one of a given set of image file types.
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!
Bluetooth - Web APIs
WebAPIBluetooth
for example, an eddystone beacon might advertise a url, which the user agent allows the user to open.
BluetoothCharacteristicProperties - Web APIs
examples the following example shows how tell if a gatt characteristic supports value change notifications.
BluetoothRemoteGATTCharacteristic.uuid - Web APIs
the bluetoothremotegattcharacteristic.uuid read-only property returns domstring containing the uuid of the characteristic, for example '00002a37-0000-1000-8000-00805f9b34fb' for the heart rate measurement characteristic.
BluetoothRemoteGATTCharacteristic - Web APIs
bluetoothremotegattcharacteristic.uuidread only returns a domstring containing the uuid of the characteristic, for example '00002a37-0000-1000-8000-00805f9b34fb' for the heart rate measurement characteristic.
uuid - Web APIs
the bluetoothremotegattdescriptor.uuid read-only property returns the uuid of the characteristic descriptor, for example '00002902-0000-1000-8000-00805f9b34fb' for theclient characteristic configuration descriptor.
BluetoothRemoteGATTDescriptor - Web APIs
bluetoothremotegattdescriptor.uuidread only returns the uuid of the characteristic descriptor, for example '00002902-0000-1000-8000-00805f9b34fb' for theclient characteristic configuration descriptor.
getCharacteristic() - Web APIs
} ) returns a promise to an instance of bluetoothgattcharacteristic parameters characteristic the uuid of a characteristic, for example '00002a37-0000-1000-8000-00805f9b34fb' for the heart rate measurement characteristic.
getCharacteristics() - Web APIs
parameters characteristic the uuid of a characteristic, for example '00002a37-0000-1000-8000-00805f9b34fb' for the heart rate measurement characteristic.
Body.arrayBuffer() - Web APIs
WebAPIBodyarrayBuffer
examples playing music in our fetch array buffer live, we have a play button.
Body.blob() - Web APIs
WebAPIBodyblob
example in our fetch request example (run fetch request live), we create a new request using the request() constructor, then use it to fetch a jpg.
Body.body - Web APIs
WebAPIBodybody
example in our simple stream pump example we fetch an image, expose the response's stream using response.body, create a reader using readablestream.getreader(), then enqueue that stream's chunks into a second, custom readable stream — effectively creating an identical copy of the image.
Body.bodyUsed - Web APIs
WebAPIBodybodyUsed
example in our fetch request example (run fetch request live), we create a new request using the request() constructor, then use it to fetch a jpg.
Body.json() - Web APIs
WebAPIBodyjson
example in our fetch json example (run fetch json live), we create a new request using the request() constructor, then use it to fetch a .json file.
Body.text() - Web APIs
WebAPIBodytext
example in our fetch text example (run fetch text live), we have an <article> element and three links (stored in the mylinks array.) first, we loop through all of these and give each one an onclick event handler so that the getdata() function is run — with the link's data-page identifier passed to it as an argument — when one of the links is clicked.
Body - Web APIs
WebAPIBody
examples the example below uses a simple fetch call to grab an image and display it in an <img> tag.
BroadcastChannel() - Web APIs
example // create a new channel listening to the "internal_notification" channel.
BroadcastChannel.close() - Web APIs
syntax var str = channel.close(); example // connect to a channel var bc = new broadcastchannel('test_channel'); // more operations (like postmessage, …) // when done, disconnect from the channel bc.close(); specifications specification status comment html living standardthe definition of 'broadcastchannel.close()' in that specification.
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.onmessa...
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.
BroadcastChannel.onmessage - Web APIs
example bc.onmessage = function(ev) { console.log(`message event received!
Broadcast Channel API - Web APIs
an example string message: // example of sending of a very simple message bc.postmessage('this is a test message.'); any kind of object can be sent, not just a domstring.
ByteLengthQueuingStrategy.ByteLengthQueuingStrategy() - Web APIs
examples const queuingstrategy = new bytelengthqueuingstrategy({ highwatermark: 1 }); const readablestream = new readablestream({ start(controller) { ...
ByteLengthQueuingStrategy.size() - Web APIs
examples const queuingstrategy = new bytelengthqueuingstrategy({ highwatermark: 1 }); const readablestream = new readablestream({ start(controller) { ...
ByteLengthQueuingStrategy - Web APIs
examples const queueingstrategy = new bytelengthqueuingstrategy({ highwatermark: 1 }); const readablestream = new readablestream({ start(controller) { ...
CDATASection - Web APIs
]]> for example: <foo>here is a cdata section: <![cdata[ < > & ]]> with all kinds of unescaped text.</foo> the only sequence which is not allowed within a cdata section is the closing sequence of a cdata section itself, ]]>: <![cdata[ ]]> will cause an error ]]> note that cdata sections should not be used within html; they only work in xml.
CSS.escape() - Web APIs
WebAPICSSescape
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 ...
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 curr...
CSS.paintWorklet (Static property) - Web APIs
WebAPICSSpaintWorklet
examples the following example demonstrates loading a paintworklet from its js file and does so by feature detection.
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
WebAPICSSsupports
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 stat...
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.value - Web APIs
examples the following example resets the css display property to its defaults.
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 - 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.x - Web APIs
example the following example positions a container <div> 5 pixels from the top and 10 pixels from the left of the page.
CSSPositionValue.y - Web APIs
example the following example positions a container <div> 5 pixels from the top and 10 pixels from the left of the page.
CSSPrimitiveValue.getFloatValue() - Web APIs
example var cs = window.getcomputedstyle(document.body); var cssvalue = cs.getpropertycssvalue("margin-top"); console.log(cssvalue.getfloatvalue(cssprimitivevalue.css_cm)); specifications specification status comment document object model (dom) level 2 style specificationthe definition of 'cssprimitivevalue.getfloatvalue' in that specification.
CSSPrimitiveValue.getRGBColorValue() - Web APIs
example var cs = window.getcomputedstyle(document.body); var cssvalue = cs.getpropertycssvalue("color"); console.log(cssvalue.getrgbcolorvalue()); specifications specification status comment document object model (dom) level 2 style specificationthe definition of 'cssprimitivevalue.getrgbcolorvalue' in that specification.
CSSPrimitiveValue.getRectValue() - Web APIs
example var cs = window.getcomputedstyle(document.getelementbyid("clippeddiv")); var cssvalue = cs.getpropertycssvalue("clip"); console.log(cssvalue.getrectvalue()); specifications specification status comment document object model (dom) level 2 style specificationthe definition of 'cssprimitivevalue.getrectvalue' in that specification.
CSSPrimitiveValue.getStringValue() - Web APIs
example var cs = window.getcomputedstyle(document.body); var cssvalue = cs.getpropertycssvalue("display"); console.log(cssvalue.getstringvalue()); specifications specification status comment document object model (dom) level 2 style specificationthe definition of 'cssprimitivevalue.getstringvalue' in that specification.
CSSPrimitiveValue.primitiveType - Web APIs
example var cs = window.getcomputedstyle(document.body); var cssvalue = cs.getpropertycssvalue("color"); console.log(cssvalue.primitivetype); specifications specification status comment document object model (dom) level 2 style specificationthe definition of 'cssprimitivevalue.primitivetype' in that specification.
CSSPrimitiveValue - Web APIs
(for example, a pixel value cannot be converted to a centimeter value.) percentage values can't be converted since they are relative to the parent value (or another property value).
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); // o...
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 t...
CSSRule.cssText - Web APIs
WebAPICSSRulecssText
syntax string = cssrule.csstext example <style> body { background-color: darkblue; } </style> <script> var stylesheet = document.stylesheets[0]; alert(stylesheet.cssrules[0].csstext); // body { background-color: darkblue; } </script> specifications specification status comment css object model (cssom)the definition of 'cssrule: csstext' in that specification.
CSSRule.parentStyleSheet - Web APIs
example if (bgrule.parentstylesheet != mysheet) { // alien style rule!
CSSRuleList - Web APIs
example // get the first style sheet’s first rule var first_rule = document.stylesheets[0].cssrules[0]; see also cssrule cssrulelist implementations there are multiple properties in the cssom that will return a cssrulelist.
CSSStyleDeclaration.cssText - Web APIs
example <span id="s1" style="color: red;"> some text </span> <script> var elem = document.getelementbyid("s1"); alert(elem.style.csstext); // "color: red;" </script> specifications specification status comment css object model (cssom)the definition of 'cssstyledeclaration: csstext' in that specification.
CSSStyleDeclaration.getPropertyCSSValue() - Web APIs
example the following javascript code gets an object containing the computed rgb values of the color css property: var style = window.getcomputedstyle(elem, null); var rgbobj = style.getpropertycssvalue('color').getrgbcolorvalue(); specifications specification status comment document object model (dom) level 2 style specificationthe definition of 'cssstyledeclaration' in ...
CSSStyleDeclaration.getPropertyPriority() - Web APIs
example the following javascript code checks whether margin is marked as important in a css selector rule: var declaration = document.stylesheets[0].cssrules[0].style; var isimportant = declaration.getpropertypriority('margin') === 'important'; specifications specification status comment css object model (cssom)the definition of 'cssstyledeclaration.getpropertypriority()'...
CSSStyleDeclaration.getPropertyValue() - Web APIs
example the following javascript code queries the value of the margin property in a css selector rule: var declaration = document.stylesheets[0].cssrules[0].style; var value = declaration.getpropertyvalue('margin'); // "1px 2px" specifications specification status comment css object model (cssom)the definition of 'cssstyledeclaration.getpropertyvalue()' in that specification.
CSSStyleDeclaration.item() - Web APIs
javascript has a special simpler syntax for obtaining an item from a nodelist by index: var propertyname = style[index]; example var style = document.getelementbyid('div1').style; var propertyname = style.item(1); // or simply style[1] - returns the second style listed specifications specification status comment css object model (cssom)the definition of 'cssstyledeclaration.item()' in that specification.
CSSStyleDeclaration.length - Web APIs
example the following gets the number of explicitly set styles on the following html element: <div id="div1" style="margin: 0 10px; background-color: #ca1; font-family: monospace"></div> javascript code: var mydiv = document.getelementbyid('div1'); var divstyle = mydiv.style; var len = divstyle.length; // 6 specifications specification status comment css object model (cssom)the definition of 'cssstyledeclaration.length' in that specification.
CSSStyleDeclaration.parentRule - Web APIs
example the following javascript code gets the parent css style rule from a cssstyledeclaration: var declaration = document.stylesheets[0].rules[0].style; var rule = declaration.parentrule; specifications specification status comment css object model (cssom)the definition of 'cssstyledeclaration.parentrule' in that specification.
CSSStyleDeclaration.removeProperty() - Web APIs
example the following javascript code removes the background-color css property from a selector rule: var declaration = document.stylesheets[0].rules[0].style; var oldvalue = declaration.removeproperty('background-color'); specifications specification status comment css object model (cssom)the definition of 'cssstyledeclaration.removeproperty()' in that specification.
CSSStyleRule.selectorText - Web APIs
syntax string = cssrule.selectortext example // for cssrule: body { background-color: darkblue; } var stylesheet = document.stylesheets[0]; alert(stylesheet.cssrules[0].selectortext); // body notes the implementation may have stripped out insignificant whitespace while parsing the selector.
CSSStyleRule.style - Web APIs
syntax styleobj = cssrule.style example function stilo() { alert(document.stylesheets[0].cssrules[0].style.csstext); } // displays "background-color: gray;" notes the declaration block is that part of the style rule that appears within the braces and that actually provides the style definitions (for the selector, the part that comes before the braces).
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 ca...
CSSStyleSheet.deleteRule() - Web APIs
return value undefined example this example removes the first rule from the stylesheet mystyles.
CSSStyleSheet.ownerRule - Web APIs
examples this snippet of code looks for rules which were not imported into the document using an @import at-rule.
CSSStyleSheet.removeRule() - Web APIs
return value undefined example this example removes the first rule from the stylesheet mystyles.
CSSStyleSheet - Web APIs
for example, one rule might be a cssstylerule object containing a style such as: h1, h2 { font-size: 16pt; } another rule might be an at-rule such as @import or @media, and so forth.
CSSStyleValue.parse() - Web APIs
example the code below parses a set of declarations for the transform property.
CSSUnitValue.unit - Web APIs
WebAPICSSUnitValueunit
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.
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.
CSSValue.cssText - Web APIs
WebAPICSSValuecssText
example var styledeclaration = document.stylesheets[0].cssrules[0].style; var cssvalue = styledeclaration.getpropertycssvalue("color"); console.log(cssvalue.csstext); specifications specification status comment document object model (dom) level 2 style specificationthe definition of 'cssvalue.csstext' in that specification.
CSSValue.cssValueType - Web APIs
example var styledeclaration = document.stylesheets[0].cssrules[0].style; var cssvalue = styledeclaration.getpropertycssvalue("color"); console.log(cssvalue.cssvaluetype); specifications specification status comment document object model (dom) level 2 style specificationthe definition of 'cssvalue.cssvaluetype' 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-colo...
Cache.add() - Web APIs
WebAPICacheadd
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
WebAPICacheaddAll
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
WebAPICachedelete
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.
Cache.keys() - Web APIs
WebAPICachekeys
examples caches.open('v1').then(function(cache) { cache.keys().then(function(keys) { keys.foreach(function(request, index, array) { cache.delete(request); }); }); }) specifications specification status comment service workersthe definition of 'cache: keys' in that specification.
Cache.matchAll() - Web APIs
WebAPICachematchAll
examples caches.open('v1').then(function(cache) { cache.matchall('/images/').then(function(response) { response.foreach(function(element, index, array) { cache.delete(element); }); }); }) specifications specification status comment service workersthe definition of 'cache: matchall' in that specification.
Cache.put() - Web APIs
WebAPICacheput
examples this example is from the mdn sw-test example (see sw-test running live).
CacheStorage.delete() - Web APIs
examples in this code snippet we wait for an activate event, and then run a waituntil() block that clears up any old, unused caches before a new service worker is activated.
CacheStorage.has() - Web APIs
WebAPICacheStoragehas
examples the following example first checks whether a cache called 'v1' exists.
CacheStorage.keys() - Web APIs
WebAPICacheStoragekeys
examples in this code snippet we wait for an activate event, and then run a waituntil() block that clears up any old, unused caches before a new service worker is activated.
CacheStorage.open() - Web APIs
WebAPICacheStorageopen
examples this example is from the mdn sw-test example (see sw-test running live).
CacheStorage - Web APIs
examples this code snippet is from the mdn sw-test example (see sw-test running live.) this service worker script waits for an installevent to fire, then runs waituntil to handle the install process for the app.
CanvasCaptureMediaStreamTrack.canvas - Web APIs
example // find the canvas element to capture var canvaselt = document.getelementsbytagname("canvas")[0]; // get the stream var stream = canvaselt.capturestream(25); // 25 fps // do things to the stream ...
CanvasCaptureMediaStreamTrack.requestFrame() - Web APIs
example // find the canvas element to capture var canvaselt = document.getelementsbytagname("canvas")[0]; // get the stream var stream = canvaselt.capturestream(25); // 25 fps // send the current state of the canvas as a frame to the stream stream.getvideotracks()[0].requestframe(); specifications specification status comment media capture from dom elementsthe definition...
CanvasGradient.addColorStop() - Web APIs
examples adding stops to a gradient this example uses the addcolorstop method to add stops to a linear canvasgradient object.
CanvasRenderingContext2D.beginPath() - Web APIs
syntax void ctx.beginpath(); examples creating distinct paths this example creates two paths, each of which contains a single line.
CanvasRenderingContext2D.canvas - Web APIs
syntax ctx.canvas; examples given this <canvas> element: <canvas id="canvas"></canvas> ...
CanvasRenderingContext2D.clearHitRegions() - Web APIs
syntax void ctx.clearhitregions(); examples using the clearhitregions method this example demonstrates the clearhitregions() method.
CanvasRenderingContext2D.createLinearGradient() - Web APIs
examples filling a rectangle with a linear gradient this example initializes a linear gradient using the createlineargradient() method.
CanvasRenderingContext2D.createRadialGradient() - Web APIs
examples filling a rectangle with a radial gradient this example initializes a radial gradient using the createradialgradient() method.
CanvasRenderingContext2D.currentTransform - Web APIs
examples manually changing the matrix this example uses the currenttransform property to set a transformation matrix.
CanvasRenderingContext2D.direction - Web APIs
examples changing text direction this example draws two pieces of text.
CanvasRenderingContext2D.drawFocusIfNeeded() - Web APIs
examples managing button focus this example draws two buttons on a canvas.
CanvasRenderingContext2D.fillRect() - Web APIs
examples a simple filled rectangle this example draws a filled green rectangle using the fillrect() method.
CanvasRenderingContext2D.font - Web APIs
examples using a custom font in this example we use the font property to specify a custom font weight, size, and family.
CanvasRenderingContext2D.getImageData() - Web APIs
example getting image data from a canvas this example draws a rectangle, and then uses getimagedata() to grab a portion of the canvas.
CanvasRenderingContext2D.getTransform() - Web APIs
examples in the following example, we have two <canvas> elements.
CanvasRenderingContext2D.globalCompositeOperation - Web APIs
types examples changing the composite operation this example uses the globalcompositeoperation property to draw two rectangles that exclude themselves where they overlap.
CanvasRenderingContext2D.imageSmoothingQuality - Web APIs
example setting image smoothing quality this example uses the imagesmoothingquality property with a scaled image.
CanvasRenderingContext2D.lineDashOffset - Web APIs
examples offsetting a line dash this example draws two dashed lines.
CanvasRenderingContext2D.miterLimit - Web APIs
examples using the miterlimit property see the chapter applying styles and color in the canvas tutorial for more information.
CanvasRenderingContext2D.moveTo() - Web APIs
examples creating multiple sub-paths this example uses moveto() to create two sub-paths within a single path.
CanvasRenderingContext2D.putImageData() - Web APIs
examples understanding putimagedata to understand what this algorithm does under the hood, here is an implementation on top of canvasrenderingcontext2d.fillrect().
CanvasRenderingContext2D.rect() - Web APIs
examples drawing a rectangle this example creates a rectangular path using the rect() method.
CanvasRenderingContext2D.removeHitRegion() - Web APIs
examples using the removehitregion method this example demonstrates the removehitregion() method.
CanvasRenderingContext2D.restore() - Web APIs
syntax void ctx.restore(); examples restoring a saved state this example uses the save() method to save the default state and restore() to restore it later, so that you are able to draw a rect with the default state later.
CanvasRenderingContext2D.save() - Web APIs
syntax void ctx.save(); examples saving the drawing state this example uses the save() method to save the default state and restore() to restore it later, so that you are able to draw a rect with the default state later.
CanvasRenderingContext2D.scrollPathIntoView() - Web APIs
examples using the scrollpathintoview method this example demonstrates the scrollpathintoview() method.
CanvasRenderingContext2D.shadowBlur - Web APIs
examples adding a shadow to a shape this example adds a blurred shadow to a rectangle.
CanvasRenderingContext2D.shadowOffsetX - Web APIs
examples moving a shadow horizontally this example adds a blurred shadow to a rectangle.
CanvasRenderingContext2D.shadowOffsetY - Web APIs
examples moving a shadow vertically this example adds a blurred shadow to a rectangle.
CanvasRenderingContext2D.textBaseline - Web APIs
examples comparison of property values this example demonstrates the various textbaseline property values.
CanvasRenderingContext2D.transform() - Web APIs
examples skewing a shape this example skews a rectangle both vertically (.2) and horizontally (.8).
CanvasRenderingContext2D.translate() - Web APIs
examples moving a shape this example draws a square that is moved from its default position by the translate() method.
Manipulating video using canvas - Web APIs
view the full source for this example.
Canvas API - Web APIs
basic example this simple example draws a green rectangle onto a canvas.
ChannelMergerNode() - Web APIs
example var ac = new audiocontext(); var options = { numberofinputs : 2 } var mymerger = new channelmergernode(ac, options); specifications specification status comment web audio apithe definition of 'channelmergernode' in that specification.
ChannelMergerNode - Web APIs
example the following example shows how you could separate a stereo track (say, a piece of music), and process the left and right channel differently.
ChannelSplitterNode.ChannelSplitterNode() - Web APIs
example var ac = new audiocontext(); var options = { numberofoutputs : 2 } var mysplitter = new channelsplitternode(ac, options); specifications specification status comment web audio apithe definition of 'channelsplitternode' in that specification.
ChannelSplitterNode - Web APIs
example the following simple example shows how you could separate a stereo track (say, a piece of music), and process the left and right channel differently.
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
WebAPIChildNodeafter
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); ...
ChildNode.before() - Web APIs
WebAPIChildNodebefore
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.remove() - Web APIs
WebAPIChildNoderemove
syntax node.remove(); example using remove() <div id="div-01">here is div-01</div> <div id="div-02">here is div-02</div> <div id="div-03">here is div-03</div> var el = document.getelementbyid('div-02'); el.remove(); // removes the div with the 'div-02' id childnode.remove() is unscopable the remove() method is not scoped into the with statement.
ChildNode.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.frameType - Web APIs
WebAPIClientframeType
syntax var myframetype = client.frametype; example tbd specifications specification status comment service workersthe definition of 'frametype' in that specification.
Client.id - Web APIs
WebAPIClientid
syntax var clientid = client.id; example tbd specifications specification status comment service workersthe definition of 'id' in that specification.
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.
Client.type - Web APIs
WebAPIClienttype
the value can be one of "window" "worker" "sharedworker" example // service worker client (e.g.
Client.url - Web APIs
WebAPIClienturl
example 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 == '/' && 'focus' in client) return client.focus(); } if (clients.openwindow) return clients.openwindow('/'); })); }); specifications specification status comme...
Clients.claim() - Web APIs
WebAPIClientsclaim
example the following example uses claim() inside service worker's "activate" event listener so that clients loaded in the same scope do not need to be reloaded before their fetches will go through this service worker.
Clients.get() - Web APIs
WebAPIClientsget
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
WebAPIClientsmatchAll
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 s...
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 ...
Clients - Web APIs
WebAPIClients
examples the following example shows an existing chat window or creates a new one when the user clicks a notification.
Clipboard.read() - Web APIs
WebAPIClipboardread
example after using navigator.permissions.query() to find out if we have (or if the user will be prompted to allow) "clipboard-read" access, this example fetches the data currently on the clipboard.
Clipboard.readText() - Web APIs
example this example retrieves the textual contents of the clipboard and inserts the returned text into an element's contents.
Clipboard.writeText() - Web APIs
example this example sets the clipboard's contents to the string "<empty clipboard>".
Clipboard - Web APIs
WebAPIClipboard
for example, firefox does not yet support the "clipboard-read" and "clipboard-write" permissions, so access to the methods that access and change the contents of the clipboard are restricted in other ways.
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.getType() - Web APIs
examples in the following example, we're returning all items on the clipboard via the clipboard.read() method.
ClipboardItem.types - Web APIs
examples in the below example, we're returning all items on the clipboard via the clipboard.read() method.
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.
CloseEvent - Web APIs
1003 unsupported data the connection is being terminated because the endpoint received data of a type it cannot accept (for example, a text-only endpoint received binary data).
Comment() - Web APIs
WebAPICommentComment
syntax comment1 = new comment(); // create an empty comment comment2 = new comment("this is a comment"); example var comment = new comment("test"); specifications specification status comment domthe definition of 'comment: comment' in that specification.
CompositionEvent.locale - Web APIs
the locale read-only property of the compositionevent interface returns the locale of current input method (for example, the keyboard layout locale if the composition is associated with ime).
CompositionEvent - Web APIs
compositionevent.locale read only returns the locale of current input method (for example, the keyboard layout locale if the composition is associated with ime).
console.assert() - Web APIs
WebAPIConsoleassert
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
WebAPIConsolecount
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.
Console.countReset() - 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.countreset(); console output will look something like this: "default: 1" "default: 2" "default: 3" "default: 4" "default: 0" note that the call to console.counterreset() resets the value of the default counter to zero.
Console.group() - Web APIs
WebAPIConsolegroup
for example, given this code: console.log("this is the outer level"); console.group(); console.log("level 2"); console.group(); console.log("level 3"); console.warn("more of level 3"); console.groupend(); console.log("back to level 2"); console.groupend(); console.log("back to the outer level"); the output looks like this: see using groups in the console in the documentation of console for more details...
Console.groupCollapsed() - Web APIs
see using groups in the console in the console documentation for details and examples.
Console.groupEnd() - Web APIs
WebAPIConsolegroupEnd
see using groups in the console in the console documentation for details and examples.
Console.profile() - Web APIs
WebAPIConsoleprofile
starts recording a performance profile (for example, the firefox performance tool).
Console.time() - Web APIs
WebAPIConsoletime
see timers in the console documentation for details and examples.
Console API - Web APIs
examples let mystring = 'hello world'; // output "hello world" to the console console.log(mystring) see the console reference page for more examples.
ConstantSourceNode() - Web APIs
example in this example, an audio context is created, then a constantsourcenode is established with its offset initialized to 0.5.
ConstantSourceNode.offset - Web APIs
example this example shows how to set up a constantsourcenode so its offset is used as the input to a pair of gainnodes; this snippet is derived from the complete example you can find in controlling multiple parameters with constantsourcenode.
ContentIndex.add() - Web APIs
WebAPIContentIndexadd
examples here we're declaring an item in the correct format and creating an asynchronous function which uses the add method to register it with the content index.
ContentIndex.delete() - Web APIs
examples below is an asynchronous function, that removes an item from the content index.
ContentIndex.getAll() - Web APIs
examples the below example shows an asynchronous function that retrieves items within the content index and iterates over each entry, building a list for the interface.
ContentIndexEvent() - Web APIs
examples this examples constructs a new contentindexevent with the relevant id.
ContentIndexEvent.id - Web APIs
examples this example listens for the contentdelete event and logs the removed content index id.
ContentIndexEvent - Web APIs
examples this example shows the sevice worker script listening for the contentdelete event and logs the removed content index id.
ConvolverNode.normalize - Web APIs
example var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); var convolver = audioctx.createconvolver(); ...
CountQueuingStrategy.CountQueuingStrategy() - Web APIs
examples const queuingstrategy = new countqueuingstrategy({ highwatermark: 1 }); const writablestream = new writablestream({ // implement the sink write(chunk) { ...
CountQueuingStrategy.size() - Web APIs
examples const queuingstrategy = new countqueuingstrategy({ highwatermark: 1 }); const writablestream = new writablestream({ // implement the sink write(chunk) { ...
CountQueuingStrategy - Web APIs
examples const queueingstrategy = new countqueuingstrategy({ highwatermark: 1 }); const writablestream = new writablestream({ // implement the sink write(chunk) { ...
Credential.name - Web APIs
WebAPICredentialname
example // tbd specifications specification status comment credential management level 1 working draft initial definition.
Credential.type - Web APIs
WebAPICredentialtype
example // tbd specifications specification status comment credential management level 1 working draft initial definition.
Credential - Web APIs
examples // tbd specifications specification status comment credential management level 1 working draft initial definition.
CredentialsContainer.get() - Web APIs
for example: if options.password exists, then the passwordcredential.[[collectfromcredentialstore]] is called.
CredentialsContainer.preventSilentAccess() - Web APIs
for example, you might call this, after a user signs out of a website to ensure that he/she isn't automatically signed in on the next site visit.
CredentialsContainer.store() - Web APIs
example // tbd specifications specification status comment credential management level 1 working draft initial definition.
CustomElementRegistry.get() - Web APIs
examples customelements.define('my-paragraph', class extends htmlelement { constructor() { super(); let template = document.getelementbyid('my-paragraph'); let templatecontent = template.content; const shadowroot = this.attachshadow({mode: 'open'}) .appendchild(templatecontent.clonenode(true)); } }) // return a reference to the my-paragraph constructor let ctor ...
CustomElementRegistry.upgrade() - Web APIs
examples taken from the html spec: const el = document.createelement("spider-man"); class spiderman extends htmlelement {} customelements.define("spider-man", spiderman); console.assert(!(el instanceof spiderman)); // not yet upgraded customelements.upgrade(el); console.assert(el instanceof spiderman); // upgraded!
CustomElementRegistry.whenDefined() - Web APIs
examples this example uses whendefined() to detect when the custom elements that make up a menu are defined.
CustomElementRegistry - Web APIs
examples the following code is taken from our word-count-web-component example (see it live also).
CustomEvent() - Web APIs
example // add an appropriate event listener obj.addeventlistener("cat", function(e) { process(e.detail) }); // create and dispatch the event var event = new customevent("cat", { detail: { hazcheeseburger: true } }); obj.dispatchevent(event); additional examples can be found at creating and triggering events.
CustomEvent.detail - Web APIs
example // add an appropriate event listener obj.addeventlistener("cat", function(e) { process(e.detail) }); // create and dispatch the event let event = new customevent("cat", { detail: { hazcheeseburger: true } }); obj.dispatchevent(event); // will return an object contaning the hazcheeseburger property let mydetail = event.detail; specifications specification status comment domthe definition of 'detail' in that specification.
DOMException() - Web APIs
example tbd specifications specification status comment web idlthe definition of 'domexception()' in that specification.
DOMException - Web APIs
for example, this can be thrown by the range object.
DOMImplementation.createDocument() - Web APIs
example var doc = document.implementation.createdocument ('http://www.w3.org/1999/xhtml', 'html', null); var body = document.createelementns('http://www.w3.org/1999/xhtml', 'body'); body.setattribute('id', 'abc'); doc.documentelement.appendchild(body); alert(doc.getelementbyid('abc')); // [object htmlbodyelement] specifications specification status comment domthe definition of...
DOMImplementation.createDocumentType() - Web APIs
example var dt = document.implementation.createdocumenttype('svg:svg', '-//w3c//dtd svg 1.1//en', 'http://www.w3.org/graphics/svg/1.1/dtd/svg11.dtd'); var d = document.implementation.createdocument('http://www.w3.org/2000/svg', 'svg:svg', dt); alert(d.doctype.publicid); // -//w3c//dtd svg 1.1//en specifications specification status comment domthe definition of 'domimplementati...
DOMMatrix() - Web APIs
example this example creates a dommatrix to use as an argument for calling point.matrixtransform().
DOMMatrixReadOnly.flipX() - Web APIs
examples this svg contains two paths in the shape of a triangle, both drawn to the same position.
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
WebAPIDOMParser
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://...
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
WebAPIDOMPointDOMPoint
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
WebAPIDOMPoint
examples in the webxr device api, dompointreadonly values are used to represent positions and orientations.
DOMPointInit - Web APIs
example this example creates a new dompoint representing the top-left corner of the current window, with a z component added to move the point closer to the user.
DOMPointReadOnly() - Web APIs
examples the following code demonstrates creating both 2d and 3d points.
DOMPointReadOnly.toJSON() - Web APIs
example this example creates a dompoint object representing the top-left corner of the current window, in screen coordinates, then converts that to json.
DOMRect.DOMRect() - Web APIs
WebAPIDOMRectDOMRect
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.
DOMRect - Web APIs
WebAPIDOMRect
for example, vreyeparameters.renderrect from the defunct webvr api specified the viewport of a canvas into which visuals for one eye of a head mounted display should be rendered.
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...
Binary strings - Web APIs
WebAPIDOMStringBinary
however, this is slow and error-prone, due to the need for multiple conversions (especially if the binary data is not actually byte-format data, but, for example, 32-bit integers or floats).
DOMTokenList.add() - Web APIs
WebAPIDOMTokenListadd
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.contains() - 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.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.forEach() - Web APIs
example 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
WebAPIDOMTokenListitem
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
WebAPIDOMTokenListkeys
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.supports() - Web APIs
example let iframe = document.getelementbyid('display'); if (iframe.sandbox.supports('an-upcoming-feature')) { // support code for mystery future feature } else { // fallback code } if (iframe.sandbox.supports('allow-scripts')) { // instruct frame to run javascript // // (note: this feature is well-supported; this is just an example!) // } specifications specification status comment cred...
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.
DataTransfer.addElement() - Web APIs
return value void example this example shows the use of the addelement() method function change_drag_node(event, node) { var dt = event.datatransfer; dt.addelement(node); } specifications this method is not defined in any web standard.
DataTransfer.clearData() - Web APIs
example this example shows the use of the datatransfer object's getdata(), setdata() and cleardata() methods.
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.mozClearDataAt() - Web APIs
return value void example this example shows the use of the mozcleardataat() method in a dragend event handler.
DataTransfer.mozCursor - Web APIs
example this example shows the use of the mozcursor property.
DataTransfer.mozGetDataAt() - Web APIs
example this example shows the use of the mozgetdataat() method in a drop event handler.
DataTransfer.mozTypesAt() - Web APIs
example this example shows the use of the moztypesat() method in a drop event handler.
DataTransfer.mozUserCancelled - Web APIs
example this example shows the use of the mozusercancelled property in the dragend event handler.
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.
DataTransferItem.getAsFile() - Web APIs
example this example shows the use of the getasfile() method in a drop event handler.
DataTransferItem.getAsString() - Web APIs
example this example shows the use of the getasstring() method as an inline function in a drop event handler.
DataTransferItem.kind - Web APIs
example this example shows the use of the kind property.
DataTransferItem - Web APIs
example all of this interface's methods and properties have their own reference page, and each reference page has an example of its usage.
DataTransferItemList - Web APIs
example each of this interface's methods and properties has a reference page, and each reference page has an example of its usage.
DedicatedWorkerGlobalScope.close() - Web APIs
syntax self.close(); example if you want to close your worker instance from inside the worker itself, you can call the following: close(); close() and self.close() are effectively equivalent — both represent close() being called from inside the worker's inner scope.
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}`); }); a...
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 ...
DedicatedWorkerGlobalScope.name - Web APIs
example if a worker is created using a constructor with a name option: var myworker = new worker("worker.js", { name : "myworker" }); the dedicatedworkerglobalscope will now have a name of "myworker", returnable by running self.name from inside the worker.
DedicatedWorkerGlobalScope - Web APIs
for example: importscripts('foo.js', 'bar.js'); implemented from other places windowbase64.atob() decodes a string of data which has been encoded using base-64 encoding.
DelayNode() - Web APIs
example const audioctx = new audiocontext(); const delaynode = new delaynode(audioctx, { delaytime: 0.5, maxdelaytime: 2, }); specifications specification status comment web audio apithe definition of 'delaynode()' in that specification.
DelayNode.delayTime - Web APIs
example we have created a simple example that allows you to play three different samples on a constant loop — see create-delay (you can also view the source code).
DelayNode - Web APIs
WebAPIDelayNode
example we have created a simple example that allows you to play three different samples on a constant loop — see create-delay (you can also view the source code).
DeviceMotionEvent - Web APIs
example window.addeventlistener('devicemotion', function(event) { console.log(event.acceleration.x + ' m/s2'); }); specifications specification status comment deviceorientation event specificationthe definition of 'devicemotionevent' in that specification.
DeviceOrientationEvent - Web APIs
example window.addeventlistener('deviceorientation', function(event) { console.log(event.alpha + ' : ' + event.beta + ' : ' + event.gamma); }); specifications specification status comment deviceorientation event specification editor's draft initial specification.
DeviceProximityEvent - Web APIs
examples window.addeventlistener('deviceproximity', function(event) { console.log("value: " + event.value, "max: " + event.max, "min: " + event.min); }); ...
DirectoryEntrySync - Web APIs
example the getfile() method returns a fileentrysync, which represents a file in the file system.
DirectoryReaderSync - Web APIs
example in the following code snippet from html5rocks, we create web workers and pass data from it to the main app.
DisplayMediaStreamConstraints.audio - Web APIs
example specifications specification status comment unknownthe definition of 'displaymediastreamconstraints.audio' in that specification.
DisplayMediaStreamConstraints.video - Web APIs
example specifications specification status comment unknownthe definition of 'displaymediastreamconstraints.video' in that specification.
Document.URL - Web APIs
WebAPIDocumentURL
syntax const url = document.url example javascript document.getelementbyid("url").textcontent = document.url; html <p id="urltext"> url:<br/> <span id="url">url goes here</span> </p> result specifications specification status comment domthe definition of 'document.url' in that specification.
Document.adoptNode() - Web APIs
example const iframe = document.queryselector('iframe'); const iframeimages = iframe.contentdocument.queryselectorall('img'); const newparent = document.getelementbyid('images'); iframeimages.foreach(function(imgel) { newparent.appendchild(document.adoptnode(imgel)); }); notes before they can be inserted into the current document, nodes from external documents should either be: cloned using doc...
Document.anchors - Web APIs
WebAPIDocumentanchors
example if (document.anchors.length >= 5) { dump("found too many anchors"); } the following is an example that auto populates a table of contents with every anchor on the page: <!doctype html> <html lang="en"> <head> <meta charset="utf-8" /> <title>test</title> <script> function init() { var toc = document.getelementbyid("toc"); var i, li, newanchor; for (i = 0; i < document.anchors.length; i++) { li = document.createelement("li"); newanchor = document.createelement('a'); newanchor.href = "#" + document.anchors[i].name; newanchor.innerhtml = document.anchors[i].text; li.appendchild(newan...
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: 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.applets - Web APIs
WebAPIDocumentapplets
example // when you know the second applet is the one you want my_java_app = document.applets[1]; specifications specification status comment html living standardthe definition of 'document.applets' in that specification.
Document.bgColor - Web APIs
WebAPIDocumentbgColor
example document.bgcolor = "darkblue"; notes the default value for this property in firefox is white (#ffffff in hexadecimal).
Document.body - Web APIs
WebAPIDocumentbody
syntax const objref = document.body document.body = objref example // given this html: <body id="oldbodyelement"></body> alert(document.body.id); // "oldbodyelement" const anewbodyelement = document.createelement("body"); anewbodyelement.id = "newbodyelement"; document.body = anewbodyelement; alert(document.body.id); // "newbodyelement" notes document.body is the element that contains the content for the document.
Document.caretRangeFromPoint() - Web APIs
example basic demo: when clicking in a paragraph insert a line break at the caret position: html <p>lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua.
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.close() - Web APIs
WebAPIDocumentclose
syntax document.close(); example // open a document to write to it document.open(); // write the content of the document document.write("<p>the one and only content.</p>"); // close the document document.close(); specifications specification status comment html living standardthe definition of 'document.close()' in that specification.
Document.compatMode - Web APIs
example if (document.compatmode == "backcompat") { // in quirks mode } specifications specification status comment domthe definition of 'compatmode' in that specification.
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.createAttribute() - Web APIs
example var node = document.getelementbyid("div1"); var a = document.createattribute("my_attrib"); a.value = "newval"; node.setattributenode(a); console.log(node.getattribute("my_attrib")); // "newval" specifications specification status comment domthe definition of 'document.createattribute()' in that specification.
Document.createCDATASection() - Web APIs
example var docu = new domparser().parsefromstring('<xml></xml>', 'application/xml') var cdata = docu.createcdatasection('some <cdata> data & then some'); docu.getelementsbytagname('xml')[0].appendchild(cdata); alert(new xmlserializer().serializetostring(docu)); // displays: <xml><![cdata[some <cdata> data & then some]]></xml> notes this will only work with xml, not html documents (as html documents do not support cdata sections); attempting it on an html document will throw not_supported_err.
Document.createComment() - Web APIs
example var docu = new domparser().parsefromstring('<xml></xml>', 'application/xml'); var comment = docu.createcomment('this is a not-so-secret comment in your document'); docu.getelementsbytagname('xml')[0].appendchild(comment); alert(new xmlserializer().serializetostring(docu)); // displays: <xml><!--this is a not-so-secret comment in your document--></xml> specifications specification status comment domthe definition of 'document.createcomment' in that specification.
Document.createDocumentFragment() - Web APIs
you can also use the documentfragment constructor to create a new fragment: let fragment = new documentfragment(); example this example creates a list of major web browsers in a documentfragment, then adds the new dom subtree to the document to be displayed.
Document.createEvent() - Web APIs
example // create the event.
Document.createProcessingInstruction() - Web APIs
example var doc = new domparser().parsefromstring('<foo />', 'application/xml'); var pi = doc.createprocessinginstruction('xml-stylesheet', 'href="mycss.css" type="text/css"'); doc.insertbefore(pi, doc.firstchild); console.log(new xmlserializer().serializetostring(doc)); // displays: <?xml-stylesheet href="mycss.css" type="text/css"?><foo/> specifications specification status comment...
Document.createRange() - Web APIs
example let range = document.createrange(); range.setstart(startnode, startoffset); range.setend(endnode, endoffset); notes once a range is created, you need to set its boundary points before you can make use of most of its methods.
Document.createTextNode() - Web APIs
example <!doctype html> <html lang="en"> <head> <title>createtextnode example</title> <script> function addtextnode(text) { var newtext = document.createtextnode(text), p1 = document.getelementbyid("p1"); p1.appendchild(newtext); } </script> </head> <body> <button onclick="addtextnode('yes!
Document.createTouch() - Web APIs
example this example illustrates using the document.createtouch() method to create touch objects.
Document.createTouchList() - Web APIs
example this example illustrates using the document.createtouchlist() method to create touchlist objects.
Document.createTreeWalker() - Web APIs
example the following example goes through all nodes in the body, reduces the set of nodes to elements, simply passes through as acceptable each node (it could reduce the set in the acceptnode() method instead), and then makes use of tree walker iterator that is created to advance through the nodes (now all elements) and push them into an array.
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.designMode - Web APIs
example make an <iframe>'s document editable: iframenode.contentdocument.designmode = "on"; specifications specification status comment html living standardthe definition of 'designmode' in that specification.
Document.doctype - Web APIs
WebAPIDocumentdoctype
example var doctypeobj = document.doctype; console.log( "doctypeobj.name: " + doctypeobj.name + "\n" + "doctypeobj.internalsubset: " + doctypeobj.internalsubset + "\n" + "doctypeobj.publicid: " + doctypeobj.publicid + "\n" + "doctypeobj.systemid: " + doctypeobj.systemid ); notes the property returns null if there is no dtd associated with the current document.
Document.documentURI - Web APIs
syntax const uri = document.documenturi example javascript document.getelementbyid("url").textcontent = document.documenturi; html <p id="urltext"> url:<br/> <span id="url">url goes here</span> </p> result specifications specification status comment domthe definition of 'documenturi' in that specification.
Document.documentURIObject - Web APIs
syntax var uri = document.documenturiobject; example // check that the uri scheme of the current tab in firefox is 'http', // assuming this code runs in context of browser.xul let uriobj = content.document.documenturiobject; let uriport = uriobj.port; if (uriobj.schemeis('http')) { ...
Document: drag event - Web APIs
interface dragevent event handler property ondrag examples see this code in a jsfiddle demo or interact with it below.
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: dragenter event - Web APIs
interface dragevent event handler property ondragenter examples see the drag event for example code or this jsfiddle demo.
Document: dragexit event - Web APIs
interface dragevent event handler property ondragexit examples see the drag event for example code or this jsfiddle demo.
Document: dragleave event - Web APIs
interface dragevent event handler property ondragleave examples see the drag event for example code or this jsfiddle demo.
Document: dragover event - Web APIs
interface dragevent event handler property ondragover examples see the drag event for example code or this jsfiddle demo.
Document: dragstart event - Web APIs
interface dragevent event handler property ondragstart 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.enableStyleSheetsForSet() - Web APIs
example document.enablestylesheetsforset("some style sheet set name"); ...
Document.fgColor - Web APIs
WebAPIDocumentfgColor
example document.fgcolor = "white"; document.bgcolor = "darkblue"; notes the default value for this property in mozilla firefox is black (#000000 in hexadecimal).
Document.fonts - Web APIs
WebAPIDocumentfonts
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.fullscreenEnabled - Web APIs
example in this example, before attempting to request full-screen mode for a <video> element, the value of fullscreenenabled is checked, in order to avoid making the attempt when not available.
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.getAnimations() - Web APIs
examples the following code snippet will slow down all animations on a page by halving their animation.playbackrate.
Document.getBoxObjectFor() - Web APIs
example var mydiv = document.getelementbyid("mydiv"), boxobj = document.getboxobjectfor (mydiv); alert ( "x:" + boxobj.x + ", y:" + boxobj.y + ", width:" + boxobj.width + ", height:" + boxobj.height ); notes specified in nsixuldocument.idl ...
Document.getElementsByName() - Web APIs
example <!doctype html> <html lang="en"> <title>example: using document.getelementsbyname</title> <input type="hidden" name="up"> <input type="hidden" name="down"> <script> var up_names = document.getelementsbyname("up"); console.log(up_names[0].tagname); // displays "input" </script> </html> notes the name attribute can only be applied in (x)html documents.
Document.hasStorageAccess() - Web APIs
examples document.hasstorageaccess().then(hasaccess => { if (hasaccess) { // storage access has been granted already.
Document.head - Web APIs
WebAPIDocumenthead
example <!doctype html> <head id="my-document-head"> <title>example: using document.head</title> </head> <script> var thehead = document.head; console.log(thehead.id); // "my-document-head"; console.log( thehead === document.queryselector("head") ); // true </script> notes document.head is read-only.
Document.height - Web APIs
WebAPIDocumentheight
syntax pixels = document.height example // alert document height alert(document.height); alternatives document.body.clientheight document.documentelement.clientheight document.documentelement.scrollheight specification html5 ...
Document.hidden - Web APIs
WebAPIDocumenthidden
syntax var boolean = document.hidden examples document.addeventlistener("visibilitychange", function() { console.log( document.hidden ); // modify behavior...
Document.images - Web APIs
WebAPIDocumentimages
the following are equivalent: firstimage = imagecollection.item(0); firstimage = imagecollection[0]; example this example looks through the list of images and finds one whose name is "banner.gif".
Document.importNode() - Web APIs
example const iframe = document.queryselector("iframe"); const oldnode = iframe.contentwindow.document.getelementbyid("mynode"); const newnode = document.importnode(oldnode, true); document.getelementbyid("container").appendchild(newnode); notes before they can be inserted into the current document, nodes from external documents should either be: cloned using document.importnode(); or adopted us...
Document.lastStyleSheetSet - Web APIs
example let lastsheetset = document.laststylesheetset; if (!lastsheetset) { lastsheetset = 'style sheet not yet changed'; } else { console.log('the last style sheet set is: ' + lastsheetset); } ...
Document.linkColor - Web APIs
example document.linkcolor = 'blue'; specification html5 document.linkcolor is deprecated in dom level 2 html.
Document.links - Web APIs
WebAPIDocumentlinks
example var links = document.links; for(var i = 0; i < links.length; i++) { var linkhref = document.createtextnode(links[i].href); var linebreak = document.createelement("br"); document.body.appendchild(linkhref); document.body.appendchild(linebreak); } specifications specification status comment html living standardthe definition of 'document.links' in that specification.
Document.mozSyntheticDocument - Web APIs
example this can be useful if you have a contextual menu item you only want to display for synthetic documents (or, conversely, for documents that aren't synthetic).
Document.onafterscriptexecute - Web APIs
example function finished(e) { logmessage(`finished script with id: ${e.target.id}`); } document.addeventlistener('afterscriptexecute', finished, true); view live example specification html5 ...
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.onfullscreenchange - Web APIs
example document.onfullscreenchange = function ( event ) { console.log("full screen change") }; document.documentelement.onclick = function () { // requestfullscreen() must be in an event handler or it will fail document.documentelement.requestfullscreen(); } specifications specification status comment fullscreen apithe definition of 'onfullscreenchange' in that spec...
Document.onfullscreenerror - Web APIs
example this example attempts to call requestfullscreen() outside of an event handler.
Document.ononline - Web APIs
WebAPIDocumentononline
example there's a simple test case that you can run to verify that the events are working.
Document.onvisibilitychange - Web APIs
example document.onvisibilitychange = function() { console.log("visibility of page has changed!"); }; specifications specification status comment page visibility (second edition)the definition of 'onvisibilitychange' in that specification.
Document.origin - Web APIs
WebAPIDocumentorigin
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.preferredStyleSheetSet - Web APIs
example if (document.preferredstylesheetset) { console.log("the preferred style sheet set is: " + document.preferredstylesheetset); } else { console.log("there is no preferred style sheet."); } ...
Document.queryCommandEnabled() - Web APIs
example var flg = document.querycommandenabled("selectall"); if(flg) { document.execcommand("selectall", false, null); // command is enabled, run it } specifications specification status comment execcommand ...
Document.queryCommandState() - Web APIs
example html <div contenteditable="true">select a part of this text!</div> <button onclick="makebold();">test the state of the 'bold' command</button> javascript function makebold() { var state = document.querycommandstate("bold"); switch (state) { case true: alert("the bold formatting will be removed from the selected text."); break; case false: alert("the selected text will be displayed in bold."); break; case null: alert...
Document.queryCommandSupported() - Web APIs
notes the 'paste' command return false not only if the feature is unavailable, but also if the script calling it has insufficient privileges to perform the action [1] example var flg = document.querycommandsupported("selectall"); if(flg) { // ...do something } specifications specification status comment execcommand ...
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.referrer - Web APIs
WebAPIDocumentreferrer
syntax var referrer = document.referrer; value the value is an empty string if the user navigated to the page directly (not through a link, but, for example, by using a bookmark).
Document.releaseCapture() - Web APIs
example see the example for element.setcapture().
Document.scripts - Web APIs
WebAPIDocumentscripts
example this example looks to see if the page has any <script> elements.
Document.scrollingElement - Web APIs
syntax var element = document.scrollingelement; example var scrollelm = document.scrollingelement; scrollelm.scrolltop = 0; specifications specification status comment css object model (cssom) view modulethe definition of 'scrollingelement' in that specification.
Document.selectedStyleSheetSet - Web APIs
example console.log('current style sheet set: ' + document.selectedstylesheetset); document.selectedstylesheetset = 'some other style sheet'; ...
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.styleSheetSets - Web APIs
example given an <ul> (list) element with the id "sheetlist", you can populate it with the names of all the available style sheet sets with code like this: let list = document.getelementbyid('sheetlist'); let sheets = document.stylesheetsets; list.innerhtml = ''; for (let i = 0; i < sheets.length; i++) { let item = document.createelement('li'); item.innerhtml = sheets[i]; list.appendchild(item); } notes the list of available style sheet sets is constructed by enumerating all the style sheets available for the document, in the order in which they're listed in th...
Document.title - Web APIs
WebAPIDocumenttitle
example <!doctype html> <html> <head> <title>hello world!</title> </head> <body> <script> alert(document.title); // displays "hello world!" document.title = "goodbye world!"; alert(document.title); // displays "goodbye world!" </script> </body> </html> notes this property applies to html, svg, xul, and other documents in gecko.
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: visibilitychange event - Web APIs
examples this example begins playing a music track when the document becomes visible, and pauses the music when the document is no longer visible.
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.
Document.width - Web APIs
WebAPIDocumentwidth
syntax pixels = document.width; example function init() { alert("the width of the document is " + document.width + " pixels."); } alternatives document.body.clientwidth /* width of <body> */ document.documentelement.clientwidth /* width of <html> */ window.innerwidth /* window's width */ specification html5 ...
Document.writeln() - Web APIs
WebAPIDocumentwriteln
example document.writeln("<p>enter password:</p>"); notes document.writeln is the same as document.write but adds a newline.
Document - Web APIs
WebAPIDocument
touch events touchcancel fired when one or more touch points have been disrupted in an implementation-specific manner (for example, too many touch points are created).
DocumentFragment() - Web APIs
syntax fragment = new documentfragment() example let fragment = new documentfragment(); specification specification status comment domthe definition of 'documentfragment()' in that specification.
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.
DocumentFragment - Web APIs
example html <ul id="list"></ul> javascript var list = document.queryselector('#list') var fruits = ['apple', 'orange', 'banana', 'melon'] var fragment = new documentfragment() fruits.foreach(function (fruit) { var li = document.createelement('li') li.innerhtml = fruit fragment.appendchild(li) }) list.appendchild(fragment) result specifications specification status comm...
DocumentOrShadowRoot.caretPositionFromPoint() - Web APIs
example this example inserts line breaks wherever you click.
DocumentOrShadowRoot.elementsFromPoint() - Web APIs
example html <div> <p>some text</p> </div> <p>elements at point 30, 20:</p> <div id="output"></div> javascript let output = document.getelementbyid("output"); if (document.elementsfrompoint) { let elements = document.elementsfrompoint(30, 20); for (var i = 0; i < elements.length; i++) { output.textcontent += elements[i].localname; if (i < elements.length - 1) { output.textcontent...
DocumentOrShadowRoot.fullscreenElement - Web APIs
example this example presents a function, isvideoinfullscreen(), which looks at the value returned by fullscreenelement; if the document is in full-screen mode (fullscreenelement isn't null) and the full-screen element's nodename is video, indicating a <video> element, the function returns true, indicating that the video is in full-screen mode.
DocumentOrShadowRoot.msElementsFromRect() - Web APIs
syntax object.mselementsfromrect(left, top, width, height, retval) parameters left [in] type: floating-point top[in] type: floating-point width[in] type: floating-point height [in] type: floating-point retval [out, reval] type: nodelist example to find all of the elements under a given point, use mselementsfrompoint(x, y).
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>documen...
DocumentOrShadowRoot.nodesFromPoint() - Web APIs
example html content <div> <p>some text</p> </div> <p>nodes at point 30, 20:</p> <div id="output"></div> javascript content var output = document.getelementbyid("output"); if (document.nodesfrompoint) { var nodes = document.nodesfrompoint(30, 20); for(var i = 0; i < nodes.length; i++) { output.textcontent += nodes[i].localname; if (i < nodes.length - 1) { output.textcontent += " ...
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.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.
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.
DragEvent.dataTransfer - Web APIs
example this example illustrates accessing the drag and drop data within the dragend event handler.
DragEvent - Web APIs
WebAPIDragEvent
example an example of each property, constructor, event type and global event handlers is included in their respective reference page.
DynamicsCompressorNode.reduction - Web APIs
example var audioctx = new audiocontext(); var compressor = audioctx.createdynamicscompressor(); var myreduction = compressor.reduction; specifications specification status comment web audio apithe definition of 'reduction' in that specification.
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_float - Web APIs
examples gl must be a webgl2renderingcontext.
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.beginQueryEXT() - Web APIs
examples var ext = gl.getextension('ext_disjoint_timer_query'); var query = ext.createqueryext(); ext.beginqueryext(ext.time_elapsed_ext, query); // ...
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.deleteQueryEXT() - Web APIs
examples var ext = gl.getextension('ext_disjoint_timer_query'); var query = ext.createqueryext(); // ...
EXT_disjoint_timer_query.endQueryEXT() - Web APIs
examples var ext = gl.getextension('ext_disjoint_timer_query'); var query = ext.createqueryext(); ext.beginqueryext(ext.time_elapsed_ext, query); // ...
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_quer...
EXT_disjoint_timer_query.getQueryObjectEXT() - Web APIs
examples var ext = gl.getextension('ext_disjoint_timer_query'); var query = ext.createqueryext(); ext.beginqueryext(ext.time_elapsed_ext, query); // ...
EXT_disjoint_timer_query.isQueryEXT() - Web APIs
examples var ext = gl.getextension('ext_disjoint_timer_query'); var query = ext.createqueryext(); // ...
EXT_disjoint_timer_query.queryCounterEXT() - Web APIs
examples var ext = gl.getextension('ext_disjoint_timer_query'); var startquery = ext.createqueryext(); var endquery = ext.createqueryext(); ext.querycounterext(startquery, ext.timestamp_ext); // ...
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.framebuffe...
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_depthth...
EXT_sRGB - Web APIs
WebAPIEXT sRGB
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, ...
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().
EcdhKeyDeriveParams - Web APIs
examples see the examples for subtlecrypto.derivekey().
EcdsaParams - Web APIs
examples see the examples for subtlecrypto.sign() or subtlecrypto.verify().
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 }); specifica...
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.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...
EffectTiming - Web APIs
0.5 would indicate starting halfway through the first iteration for example, and with this value set, an animation with 2 iterations would end halfway through a third iteration.
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: auxclick event - Web APIs
examples in this example we define functions for two event handlers — onclick and onauxclick.
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 d...
Element.classList - Web APIs
WebAPIElementclassList
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("vi...
Element.className - Web APIs
WebAPIElementclassName
example let el = document.getelementbyid('item'); if (el.classname === 'active'){ el.classname = 'inactive'; } else { el.classname = 'active'; } notes the name classname is used for this property instead of class because of conflicts with the "class" keyword in many languages which are used to manipulate the dom.
Element.clientHeight - Web APIs
example specification specification status comment css object model (cssom) view modulethe definition of 'clientheight' in that specification.
Element.clientLeft - Web APIs
syntax var left = element.clientleft; example padding-top lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
Element.clientWidth - Web APIs
example specification specification status comment css object model (cssom) view modulethe definition of 'clientwidth' in that specification.
Element.closest() - Web APIs
WebAPIElementclosest
example html <article> <div id="div-01">here is div-01 <div id="div-02">here is div-02 <div id="div-03">here is div-03</div> </div> </div> </article> javascript var el = document.getelementbyid('div-03'); var r1 = el.closest("#div-02"); // returns the element with the id=div-02 var r2 = el.closest("div div"); // returns the closest ancestor which is a div in div, here it is the di...
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'); so...
Element: cut event - Web APIs
WebAPIElementcut event
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'); so...
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: 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 ev...
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 specificati...
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 specification...
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.getAttributeNames() - Web APIs
syntax let attributenames = element.getattributenames(); example // iterate over element's attributes for (let name of element.getattributenames()) { let value = element.getattribute(name); console.log(name, value); } polyfill if (element.prototype.getattributenames == undefined) { element.prototype.getattributenames = function () { var attributes = this.attributes; var length = attributes.length; var result = new array(length); for (var i = 0; i < leng...
Element.getAttributeNode() - Web APIs
example // html: <div id="top" /> let t = document.getelementbyid("top"); let idattr = t.getattributenode("id"); alert(idattr.value == "top") notes when called on an html element in a dom flagged as an html document, getattributenode lower-cases its argument before proceeding.
Element.getAttributeNodeNS() - Web APIs
== example == tbd the example needs to be fixed pre> // html: <div id="top" /> t = document.getelementbyid("top"); specialnode = t.getattributenodens( "http://www.mozilla.org/ns/specialspace", "id"); // inode.value = "full-top" </pre notes getattributenodens is more specific than getattributenode in that it allows you to specify attributes that are part of a particular namespace.
Element.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').getelementsbyclassn...
Element.getElementsByTagName() - Web APIs
example // check the status of each data cell in a table const table = document.getelementbyid('forecast-table'); const cells = table.getelementsbytagname('td'); for (let cell of cells) { let status = cell.getattribute('data-status'); if (status === 'open') { // grab the data } } specifications specification status comment domthe definition of 'element.getelementsby...
Element.hasAttribute() - Web APIs
example var foo = document.getelementbyid("foo"); if (foo.hasattribute("bar")) { // do something } polyfill ;(function(prototype) { prototype.hasattribute = prototype.hasattribute || function(name) { return !!(this.attributes[name] && this.attributes[name].specified); } })(element.prototype); notes dom methods dealing with element's attributes: not namespace-aware, most commonly used methods namespace-aware variants (dom level 2) dom level 1 methods for deal...
Element.hasAttributeNS() - Web APIs
example // check that the attribute exists before you set a value var d = document.getelementbyid("div1"); if (d.hasattributens( "http://www.mozilla.org/ns/specialspace/", "special-align")) { d.setattribute("align", "center"); } notes dom methods dealing with element's attributes: not namespace-aware, most commonly used methods namespace-aware variants (dom level 2) dom level 1 methods for dealing with attr nodes directly (seldom used) dom level 2 namesp...
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.insertAdjacentElement() - Web APIs
example beforebtn.addeventlistener('click', function() { var tempdiv = document.createelement('div'); tempdiv.style.backgroundcolor = randomcolor(); if (activeelem) { activeelem.insertadjacentelement('beforebegin',tempdiv); } setlistener(tempdiv); }); afterbtn.addeventlistener('click', function() { var tempdiv = document.createelement('div'); tempdiv.style.backgroundcolor = randomcolo...
Element.insertAdjacentHTML() - Web APIs
example // <div id="one">one</div> var d1 = document.getelementbyid('one'); d1.insertadjacenthtml('afterend', '<div id="two">two</div>'); // at this point, the new structure is: // <div id="one">one</div><div id="two">two</div> notes security considerations when inserting html into a page by using insertadjacenthtml(), be careful not to use user input that hasn't been escaped.
Element.insertAdjacentText() - Web APIs
example beforebtn.addeventlistener('click', function() { para.insertadjacenttext('afterbegin',textinput.value); }); afterbtn.addeventlistener('click', function() { para.insertadjacenttext('beforeend',textinput.value); }); have a look at our insertadjacenttext.html demo on github (see the source code too.) here we have a simple paragraph.
Element.matches() - Web APIs
WebAPIElementmatches
example <ul id="birds"> <li>orange-winged parrot</li> <li class="endangered">philippine eagle</li> <li>great white pelican</li> </ul> <script type="text/javascript"> var birds = document.getelementsbytagname('li'); for (var i = 0; i < birds.length; i++) { if (birds[i].matches('.endangered')) { console.log('the ' + birds[i].textcontent + ' is endangered!'); } } </script> thi...
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: 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: msContentZoom event - Web APIs
bubbles unknown cancelable unknown interface unknown event handler property unknown example contentzoom.addeventlistener("mscontentzoom", function(e) { zoomfactor.value = contentzoom.mscontentzoomfactor.tofixed(2); }); specifications not part of any specification.
Element.msZoomTo() - Web APIs
WebAPIElementmsZoomTo
example /* zooming in on an element while still keeping it centered in the viewport */ var args = { contentx: target.offsetleft + target.offsetwidth/2; contenty: target.offsettop + target.offsetheight/2; scalefactor: 2.0; } zoomer.mszoomto(args); see also microsoft api extensions ...
Element.name - Web APIs
WebAPIElementname
syntax htmlelement.name = string let elname = htmlelement.name let fcontrol = htmlformelement.elementname let controlcollection = htmlformelement.elements.elementname example <form action="" name="forma"> <input type="text" value="foo"> </form> <script type="text/javascript"> // get a reference to the first element in the form let formelement = document.forms['forma'].elements[0] // give it a name formelement.name = 'inputa' // show the value of the input alert(document.forms['forma'].elements['inputa'].value) </script> notes in internet explore...
Element.namespaceURI - Web APIs
syntax namespace = element.namespaceuri example in this snippet, an element is being examined for its localname and its namespaceuri.
Element.onfullscreenchange - Web APIs
example this example establishes a fullscreenchange event handler, handlefullscreenchange().
Element.onfullscreenerror - Web APIs
example this example attempts to switch into full-screen mode from outside a handler for a user-initiated event (such as a click or keypress event).
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("wr...
Element.part - Web APIs
WebAPIElementpart
syntax let elementpartlist = element.part examples the following excerpt is from our shadow-part example.
Element.prefix - Web APIs
WebAPIElementprefix
syntax string = element.prefix examples the following logs "x" to the console.
Element.releasePointerCapture() - Web APIs
example this example sets pointer capture on a <div> when you press down on it.
Element.removeAttribute() - Web APIs
for dealing with attr nodes directly (seldom used) dom level 2 namespace-aware methods for dealing with attr nodes directly (seldom used) setattribute (dom 1) setattributens setattributenode setattributenodens getattribute (dom 1) getattributens getattributenode getattributenodens hasattribute (dom 2) hasattributens - - removeattribute (dom 1) removeattributens removeattributenode - example // given: <div id="div1" align="left" width="200px"> document.getelementbyid("div1").removeattribute("align"); // now: <div id="div1" width="200px"> specifications specification status comment domthe definition of 'element" removeattribute' in that specification.
Element.removeAttributeNS() - Web APIs
example // given: // <div id="div1" xmlns:special="http://www.mozilla.org/ns/specialspace" // special:specialalign="utterleft" width="200px" /> d = document.getelementbyid("div1"); d.removeattributens("http://www.mozilla.org/ns/specialspace", "specialalign"); // now: <div id="div1" width="200px" /> notes dom methods dealing with element's attributes: not namespace-aware, most commonly used methods namespace-aware variants (dom level 2) dom level 1 methods f...
Element.removeAttributeNode() - Web APIs
example // given: <div id="top" align="center" /> var d = document.getelementbyid("top"); var d_align = d.getattributenode("align"); d.removeattributenode(d_align); // align is now removed: <div id="top" /> notes if the removed attribute has a default value, it is immediately replaced.
Element.scroll() - Web APIs
WebAPIElementscroll
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
WebAPIElementscrollBy
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.scrollIntoView() - Web APIs
example var element = document.getelementbyid("box"); element.scrollintoview(); element.scrollintoview(false); element.scrollintoview({block: "end"}); element.scrollintoview({behavior: "smooth", block: "end", inline: "nearest"}); notes the element may not be scrolled completely to the top or bottom depending on the layout of other elements.
Element.scrollIntoViewIfNeeded() - Web APIs
example var element = document.getelementbyid("my-el"); element.scrollintoviewifneeded(); element.scrollintoviewifneeded(true); // centers the element in the visible area specifications not part of any specification.
Element.scrollLeft - Web APIs
example html <div id="container"> <div id="content">click the button to slide right!</div> </div> <button id="slide" type="button">slide right</button> css #container { width: 100px; height: 100px; border: 1px solid #ccc; overflow-x: scroll; } #content { width: 250px; background-color: #ccc; } javascript const button = document.getelementbyid('slide'); button.onclick = function () ...
Element.scrollTo() - Web APIs
WebAPIElementscrollTo
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.scrollTop - Web APIs
WebAPIElementscrollTop
example padding-top if you can see this, scrolltop = 0 lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
Element.scrollWidth - Web APIs
example <!doctype html> <html> <head> <title>example</title> <style> div { overflow: hidden; white-space: nowrap; text-overflow: ellipsis; } #adiv { width: 100px; } button { margin-bottom: 2em; } </style> </head> <body> <div id="adiv"> foobar-foobar-fooba...
Element.setAttributeNS() - Web APIs
example let d = document.getelementbyid('d1'); d.setattributens('http://www.mozilla.org/ns/specialspace', 'spec:align', 'center'); notes dom methods dealing with element's attributes: not namespace-aware, most commonly used methods namespace-aware variants (dom level 2) dom level 1 methods for dealing with attr nodes directly (seldom used) dom level 2 namespace-aware methods for dealing with attr ...
Element.setAttributeNode() - Web APIs
example this example copies the align attribute from one element to another.
Element.setAttributeNodeNS() - Web APIs
example // <div id="one" xmlns:myns="http://www.mozilla.org/ns/specialspace" // myns:special-align="utterleft">one</div> // <div id="two">two</div> var myns = "http://www.mozilla.org/ns/specialspace"; var d1 = document.getelementbyid("one"); var d2 = document.getelementbyid("two"); var a = d1.getattributenodens(myns, "special-align"); d2.setattributenodens(a.clonenode(true)); alert(d2.attributes[1].value) // returns: `utterleft' notes if the specified attribute already exists on the element, then that attribute is replaced with ...
Element.setPointerCapture() - Web APIs
example this example sets pointer capture on a <div> when you press down on it.
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.tabStop - Web APIs
WebAPIElementtabStop
syntax var istabstop = element.tabstop; element.tabstop = (true|false); example // tbd ...
Element.toggleAttribute() - Web APIs
example in the following example, toggleattribute() is used to toggle the readonly attribute of a <input>.
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.get...
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 elem...
Event() - Web APIs
WebAPIEventEvent
example // create a look event that bubbles up and cannot be canceled const evt = new event("look", {"bubbles":true, "cancelable":false}); document.dispatchevent(evt); // event can be dispatched from any element, not only the document mydiv.dispatchevent(evt); specifications specification status comment domthe definition of 'event()' in that specification.
Event.bubbles - Web APIs
WebAPIEventbubbles
example function handleinput(e) { // checks whether the event bubbles and ...
Event.cancelBubble - Web APIs
example elem.onclick = function(event) { // do cool things here event.cancelbubble = true; } specifications specification status comment domthe definition of 'cancelbubble' in that specification.
Event.cancelable - Web APIs
WebAPIEventcancelable
example for example, browser vendors are proposing that the wheel event can only be canceled the first time the listener is called — any following wheel events cannot be canceled.
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.defaultPrevented - Web APIs
example this example logs attempts to visit links from two <a> elements.
Event.eventPhase - Web APIs
WebAPIEventeventPhase
example html <h4>event propagation chain</h4> <ul> <li>click 'd1'</li> <li>analyse event propagation chain</li> <li>click next div and repeat the experience</li> <li>change capturing mode</li> <li>repeat the experience</li> </ul> <input type="checkbox" id="chcapture" /> <label for="chcapture">use capturing</label> <div id="d1">d1 <div id="d2">d2 <div id="d3">d3 <div id="d4...
Event.initEvent() - Web APIs
WebAPIEventinitEvent
example // create the event.
Event.isTrusted - Web APIs
WebAPIEventisTrusted
syntax var eventistrusted = event.istrusted; value boolean example if (e.istrusted) { /* the event is trusted */ } else { /* the event is not trusted */ } specification specification status comment domthe definition of 'event.istrusted' in that specification.
Event.msConvertURL() - Web APIs
example var bloblist = []; document.getelementbyid("pastezone").addeventlistener('paste', handlepaste, false); function handlepaste(evt) { var filelist = window.clipboarddata.files; // note that window.datatransfer.files is not applicable.
Event.originalTarget - Web APIs
see also comparison of event targets example need an example that makes sense here specification this is a mozilla-specific property.
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.
Event.target - Web APIs
WebAPIEventtarget
syntax const thetarget = someevent.target; value eventtarget example the event.target property can be used in order to implement event delegation.
Event.timeStamp - Web APIs
WebAPIEventtimeStamp
example html <p> focus this iframe and press any key to get the current timestamp for the keypress event.
Event.type - Web APIs
WebAPIEventtype
example this example logs the event type whenever you press a keyboard key or click a mouse button.
Event - Web APIs
WebAPIEvent
(for example, a webpage with an advertising-module and statistics-module both monitoring video-watching.) when there are many nested elements, each with its own handler(s), event processing can become very complicated—especially where a parent element receives the very same event as its child elements because "spatially" they overlap so the event technically occurs in both, and the processing order of suc...
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
WebAPIEventSourceclose
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
WebAPIEventSourceurl
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.
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.
EventTarget.dispatchEvent() - Web APIs
example see creating and triggering events.
ExtendableEvent() - Web APIs
syntax var extendableevent = new extendableevent(type, init); parameters type the type of the extendableevent, for example install, activate.
ExtendableEvent.waitUntil() - Web APIs
example using waituntil() within a service worker's install event: addeventlistener('install', event => { const precache = async () => { const cache = await caches.open('static-v1'); return cache.addall([ '/', '/about/', '/static/styles.css' ]); }; event.waituntil(precache()); }); specifications specification status comment service workersth...
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.
FeaturePolicy.allowedFeatures() - Web APIs
example the followin example logs all the allowed directives for the current document.
FeaturePolicy.allowsFeature() - Web APIs
example the following example queries whether or not the document is allowed to use camera api by the feature policy.
FeaturePolicy.features() - Web APIs
example the followin example logs all the supported directives in the console.
FeaturePolicy.getAllowlistForFeature() - Web APIs
example the followin example prints all the origins that are allowed to use camera api by the feature policy.
FederatedCredential.protocol - Web APIs
examples // tbd specifications specification status comments credential management level 1the definition of 'protocol' in that specification.
FederatedCredential.provider - Web APIs
example // tbd specifications specification status comments credential management level 1 working draft initial definition.
FetchEvent.preloadResponse - Web APIs
example this code snippet is from the navigation preload page.
FetchEvent.client - Web APIs
WebAPIFetchEventclient
example self.addeventlistener('fetch', function(event) { console.log(event.client); ​}); ...
FetchEvent.clientId - Web APIs
example self.addeventlistener('fetch', function(event) { console.log(event.clientid); ​}); specifications specification status comment service workersthe definition of 'clientid' in that specification.
FetchEvent.isReload - Web APIs
example self.addeventlistener('fetch', function(event) { event.respondwith( if (event.isreload) { //return something } else { //return something else }; ); ​}); ...
FetchEvent.navigationPreload - Web APIs
example the following example shows the implementation of a fetch event that uses a preloaded response.
FetchEvent.request - Web APIs
example this code snippet is from the service worker fetch sample (run the fetch sample live).
FetchEvent - Web APIs
examples this fetch event uses the browser default for non-get requests.
Fetch basic concepts - Web APIs
service workers is an example of an api that makes heavy use of fetch.
Cross-global fetch usage - Web APIs
frame.contentwindow.fetch() the url passed to fetch needs to be relative the problem in the past we would resolve the relative url against the current global, for example: let absolute = new url(relative, window.location.href) this is not a problem as such.
Fetch API - Web APIs
WebAPIFetch API
instead, these are more likely to be created as results of other api actions (for example, fetchevent.respondwith() from service workers).
File.File() - Web APIs
WebAPIFileFile
example var file = new file(["foo"], "foo.txt", { type: "text/plain", }); specifications specification status comment file api working draft initial definition ...
File.getAsBinary() - Web APIs
WebAPIFilegetAsBinary
example // fileinput is an htmlinputelement: <input type="file" id="myfileinput" multiple> var fileinput = document.getelementbyid("myfileinput"); // files is a filelist object (similar to nodelist) var files = fileinput.files; // object for allowed media types var accept = { binary : ["image/png", "image/jpeg"], text : ["text/plain", "text/css", "application/xml", "text/html"] }; var file; fo...
File.getAsDataURL() - Web APIs
WebAPIFilegetAsDataURL
syntax var url = instanceoffile.getasdataurl(); returns a string representing a data: url example // fileinput is a htmlinputelement: <input type="file" id="myfileinput" multiple> var fileinput = document.getelementbyid("myfileinput"); // files is a filelist object (similar to nodelist) var files = fileinput.files; // array with acceptable file types var accept = ["image/png"]; // img is a htmlimgelement: <img id="myimg"> var img = document.getelementbyid("myimg"); // if we accept the first selected file type if (accept.indexof(files[0].mediatype) > -1) { // display the image // sam...
File.getAsText() - Web APIs
WebAPIFilegetAsText
example // fileinput is a htmlinputelement: <input type="file" id="myfileinput" multiple> var fileinput = document.getelementbyid("myfileinput"); // files is a filelist object (similar to nodelist) var files = fileinput.files; // object for allowed media types var accept = { binary : ["image/png", "image/jpeg"], text : ["text/plain", "text/css", "application/xml", "text/html"] }; var file; for...
File.lastModified - Web APIs
WebAPIFilelastModified
example reading from file input <input type="file" multiple id="fileinput"> const fileinput = document.queryselector('#fileinput'); fileinput.addeventlistener('change', (event) => { // files is a filelist object (similar to nodelist) const files = event.target.files; for (let file of files) { const date = new date(file.lastmodified); console.log(`${file.name} has a last modified date of ${date}`); } }); try the ...
File.lastModifiedDate - Web APIs
example // fileinput is a htmlinputelement: <input type="file" multiple id="myfileinput"> var fileinput = document.getelementbyid("myfileinput"); // files is a filelist object (simliar to nodelist) var files = fileinput.files; for (var i = 0; i < files.length; i++) { alert(files[i].name + " has a last modified date of " + files[i].lastmodifieddate); } reduced time precision to offer protection against timing attacks and fingerprinting, the precision of somefile.lastmodifieddate.gettime() might ...
File.name - Web APIs
WebAPIFilename
example <input type="file" multiple onchange="processselectedfiles(this)"> function processselectedfiles(fileinput) { var files = fileinput.files; for (var i = 0; i < files.length; i++) { alert("filename " + files[i].name); } } try the results out below: specifications specification status comment file apithe definition of 'name' in that specification.
File.type - Web APIs
WebAPIFiletype
syntax var name = file.type; value a string, containing the media type(mime) indicating the type of the file, for example "image/png" for png images example <input type="file" multiple onchange="showtype(this)"> function showtype(fileinput) { var files = fileinput.files; for (var i = 0; i < files.length; i++) { var name = files[i].name; var type = files[i].type; alert("filename: " + name + " , type: " + type); } } note: based on the current implementation, browsers won't actually read the bytestream of a file to determine its media type.
File.webkitRelativePath - Web APIs
example in this example, a directory picker is presented which lets the user choose one or more directories.
File - Web APIs
WebAPIFile
see using files from web applications for more information and examples.
FileReader() - Web APIs
example the following code snippet shows creation of a filereader object using the filereader() constructor and subsequent usage of the object: function printfile(file) { var reader = new filereader(); reader.onload = function(evt) { console.log(evt.target.result); }; reader.readastext(file); } specifications specification status comment file api working draft initial definition ...
FileReader.onload - Web APIs
WebAPIFileReaderonload
example // callback from a <input type="file" onchange="onchange(event)"> function onchange(event) { var file = event.target.files[0]; var reader = new filereader(); reader.onload = function(e) { // the file's text will be printed here console.log(e.target.result) }; reader.readastext(file); } ...
FileReader.readAsBinaryString() - Web APIs
example var canvas = document.createelement('canvas'); var height = 200; var width = 200; canvas.width = width; canvas.height = height; var ctx = canvas.getcontext('2d'); ctx.strokestyle = '#090'; ctx.beginpath(); ctx.arc(width/2, height/2, width/2 - width/10, 0, math.pi*2); ctx.stroke(); canvas.toblob(function (blob) { var reader = new filereader(); reader.onload = function () { console.
FileReader.readyState - Web APIs
example var reader = new filereader(); console.log('empty', reader.readystate); // readystate will be 0 reader.readastext(blob); console.log('loading', reader.readystate); // readystate will be 1 reader.onloadend = function () { console.log('done', reader.readystate); // readystate will be 2 }; value a number which is one of the three possible state constants define for the filereader api.
FileReader.result - Web APIs
WebAPIFileReaderresult
example this example presents a function, read(), which reads a file from a file input.
FileRequest.onprogress - Web APIs
example // assuming 'request' which is a filerequest object request.onprogress = function (status) { var progress = document.queryselector('progress'); progress.value = status.loaded; progress.max = status.total; } specification not part of any current specification.
FileSystem.name - Web APIs
WebAPIFileSystemname
example // tbd specifications specification status comment file and directory entries apithe definition of 'name' in that specification.
FileSystem.root - Web APIs
WebAPIFileSystemroot
example // tbd specifications specification status comment file and directory entries apithe definition of 'root' in that specification.
FileSystemDirectoryEntry.createReader() - Web APIs
example this example creates a method called readdirectory(), which fetches all of the entries in the specified filesystemdirectoryentry and returns them in an array.
FileSystemDirectoryEntry.getDirectory() - Web APIs
example in this example, a function is presented whose job it is to locate within a user's app data directory a json file containing a user dictionary for a specified language, then load that dictionary.
FileSystemDirectoryEntry.getFile() - Web APIs
example in this example, a function is presented whose job it is to locate within a user's app data directory a json file containing a user dictionary for a specified language, then load that dictionary.
FileSystemDirectoryEntry.removeRecursively() - Web APIs
example directory.removerecursively(function() { /* the directory was removed successfully */ }, function() { /* an error occurred while removing the directory */ }); browser compatibility the compatibility table on this page is generated from structured data.
FileSystemDirectoryEntry - Web APIs
example in the following code snippet, we create a directory called "documents." // taking care of the browser-specific prefixes.
FileSystemEntry.copyTo() - Web APIs
example this example shows how a temporary log file might be moved into a more permanent "log" directory.
FileSystemEntry.filesystem - Web APIs
example this example obtains a filesystemdirectoryentry for the root directory of the file system containing a file.
FileSystemEntry.fullPath - Web APIs
example this example shows a function which is called with a file system; it then gets a filesystemfileentry for a file named data.json and returns its full path.
FileSystemEntry.getMetadata() - Web APIs
example this example checks the size of a log file in a temporary folder and, if it exceeds a megabyte, moves it into a different directory.
FileSystemEntry.isDirectory - Web APIs
example this example shows how this property might be used to determine whether to process the entry as a directory or file.
FileSystemEntry.isFile - Web APIs
example this example shows how this property might be used to determine whether to process the entry as a directory or file.
FileSystemEntry.moveTo() - Web APIs
example this example shows how a temporary log file might be moved into a more permanent "log" directory when it exceeds a megabyte in size.
FileSystemEntry.name - Web APIs
example this example shows a function called isfilewithextension() which returns true if the specified filesystementry is both a file and the file's name ends with a given extension.
FileSystemEntry.remove() - Web APIs
example this example deletes a temporary work file.
FileSystemEntry.toURL() - Web APIs
example if you have a filesystemfileentry corresponding to an image file in a file system available to your web site or app, you can call tourl() to get its url for use in html.
FileSystemFileEntry.createWriter() - Web APIs
example this example establishes a method, writetofileentry(), which outputs a text string to the file corresponding to the passed-in directory entry.
FileSystemFileEntry.file() - Web APIs
example this example establishes a method, readfile(), reads a text file and calls a specified callback function with the received text (in a string object) once the read is completed.
FileSystemFileEntry - Web APIs
example the following code creates an empty file called "log.txt" (if it doesn't exist) and fills it with the text "meow".
FontFace.FontFace() - Web APIs
WebAPIFontFaceFontFace
it can have the following keys: family: family style: style weight: weight stretch: stretch unicoderange: unicode range variant: variant featuresettings: feature settings example async function loadfonts() { const font = new fontface('myfont', 'url(myfont.woff)'); // wait for font to be loaded await font.load(); // add font to document document.fonts.add(font); // enable font with css class document.body.classlist.add('fonts-loaded'); } specifications specification status comment css font loading module level 3the de...
FontFace.family - Web APIs
WebAPIFontFacefamily
example var fontface = new fontface('roboto', 'url(https://fonts.example.com/roboto.woff2)'); console.log(fontface.family); // 'roboto' fontface.family = 'newroboto'; console.log(fontface.family); // 'newroboto' specifications specification status comment css font loading module level 3the definition of 'family' in that specification.
FontFaceSet.check() - Web APIs
WebAPIFontFaceSetcheck
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
WebAPIFontFaceSetload
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.
FormData() - Web APIs
WebAPIFormDataFormData
example the following line creates an empty formdata object: var formdata = new formdata(); // currently empty you could add a key/value pair to this using formdata.append: formdata.append('username', 'chris'); or you can specify the optional form argument when creating the formdata object, to prepopulate it with values from the specified form: <form id="myform" name="myform"> <div> <label f...
FormData.delete() - Web APIs
WebAPIFormDatadelete
example the following line creates an empty formdata object and prepopulates it with key/value pairs from a form: var formdata = new formdata(myform); you can delete keys and their values using delete(): formdata.delete('username'); specifications specification status comment xmlhttprequestthe definition of 'delete()' in that specification.
FormData.entries() - Web APIs
WebAPIFormDataentries
example // create a test formdata object var formdata = new formdata(); formdata.append('key1', 'value1'); formdata.append('key2', 'value2'); // display the key/value pairs for(var pair of formdata.entries()) { console.log(pair[0]+ ', '+ pair[1]); } the result is: key1, value1 key2, value2 specifications specification status comment xmlhttprequestthe definition of 'entries() (as iterator<>)' in that specification.
FormData.get() - Web APIs
WebAPIFormDataget
example the following line creates an empty formdata object: var formdata = new formdata(); if we add two username values using formdata.append: formdata.append('username', 'chris'); formdata.append('username', 'bob'); the following get() function will only return the first username value appended: formdata.get('username'); // returns "chris" specifications specification status com...
FormData.getAll() - Web APIs
WebAPIFormDatagetAll
example the following line creates an empty formdata object: var formdata = new formdata(); if we add two username values using formdata.append: formdata.append('username', 'chris'); formdata.append('username', 'bob'); the following getall() function will return both username values in an array: formdata.getall('username'); // returns ["chris", "bob"] specifications specification stat...
FormData.has() - Web APIs
WebAPIFormDatahas
example the following line creates an empty formdata object: var formdata = new formdata(); the following snippet shows the results of testing for the existence of username in the formdata object, before and after appending a username value to it with formdata.append: formdata.has('username'); // returns false formdata.append('username', 'chris'); formdata.has('username'); // returns true specifications specification status comment xmlhttprequestthe definition ...
FormData.keys() - Web APIs
WebAPIFormDatakeys
example // create a test formdata object var formdata = new formdata(); formdata.append('key1', 'value1'); formdata.append('key2', 'value2'); // display the keys for (var key of formdata.keys()) { console.log(key); } the result is: key1 key2 specifications specification status comment xmlhttprequestthe definition of 'keys() (as iterator<>)' in that specification.
FormData.set() - Web APIs
WebAPIFormDataset
example the following line creates an empty formdata object: var formdata = new formdata(); // currently empty you can set key/value pairs on this using formdata.set: formdata.set('username', 'chris'); formdata.set('userpic', myfileinput.files[0], 'chris.jpg'); if the sent value is different than string or blob it will be automatically converted to string: formdata.set('name', 72); formdata.get('na...
FormData.values() - Web APIs
WebAPIFormDatavalues
example // create a test formdata object var formdata = new formdata(); formdata.append('key1', 'value1'); formdata.append('key2', 'value2'); // display the values for (var value of formdata.values()) { console.log(value); } the result is: value1 value2 specifications specification status comment xmlhttprequestthe definition of 'values() (as iterator<>)' in that specification.
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); } // ...
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.l...
Frame Timing API - Web APIs
example code of the interfaces described in this document is included in using the frame timing api.
FullscreenOptions.navigationUI - Web APIs
example in this example, the entire document is placed into full-screen mode by calling requestfullscreen() on the document's document.documentelement, which is the document's root <html> element.
Gamepad.axes - Web APIs
WebAPIGamepadaxes
syntax readonly attribute double[] axes; example function gameloop() { if(navigator.webkitgetgamepads) { var gp = navigator.webkitgetgamepads()[0]; } else { var gp = navigator.getgamepads()[0]; } if(gp.axes[0] != 0) { b -= gp.axes[0]; } else if(gp.axes[1] != 0) { a += gp.axes[1]; } else if(gp.axes[2] != 0) { b += gp.axes[2]; } else if(gp.axes[3] != 0) { a -= gp.axes[3]; } ball.style.left = a*2 + "px"; ball.style.top =...
Gamepad.connected - Web APIs
WebAPIGamepadconnected
syntax readonly attribute boolean connected; example var gp = navigator.getgamepads()[0]; console.log(gp.connected); value a boolean.
Gamepad.hand - Web APIs
WebAPIGamepadhand
examples tbc specifications specification status comment gamepad extensionsthe definition of 'hand' in that specification.
Gamepad.hapticActuators - Web APIs
examples tbc specifications specification status comment gamepad extensionsthe definition of 'hapticactuators' in that specification.
Gamepad.index - Web APIs
WebAPIGamepadindex
syntax readonly attribute long index; example window.addeventlistener("gamepadconnected", function() { var gp = navigator.getgamepads()[0]; gamepadinfo.innerhtml = "gamepad connected at index " + gp.index + ": " + gp.id + "."; }); value a number.
Gamepad.mapping - Web APIs
WebAPIGamepadmapping
syntax readonly attribute domstring mapping; example var gp = navigator.getgamepads()[0]; console.log(gp.mapping); value a string.
Gamepad.timestamp - Web APIs
WebAPIGamepadtimestamp
syntax readonly attribute domhighrestimestamp timestamp; example var gp = navigator.getgamepads()[0]; console.log(gp.timestamp); value a domhighrestimestamp.
Gamepad - Web APIs
WebAPIGamepad
example window.addeventlistener("gamepadconnected", function(e) { console.log("gamepad connected at index %d: %s.
GamepadButton.pressed - Web APIs
syntax var ispressed = navigator.getgamepads()[0].pressed; example var gp = navigator.getgamepads()[0]; // get the first gamepad object if(gp.buttons[0].pressed == true) { // respond to button being pressed } value a boolean.
GamepadButton.value - Web APIs
syntax readonly attribute double value; example var gp = navigator.getgamepads()[0]; if(gp.buttons[0].value > 0) { // respond to analog button being pressed in } value a double.
GamepadEvent.gamepad - Web APIs
syntax readonly attribute gamepad gamepad; example the gamepad property being called on a fired window.gamepadconnected event.
GamepadEvent - Web APIs
examples the gamepad property being called on a fired window.gamepadconnected event.
GamepadHapticActuator.pulse() - Web APIs
examples tbc specifications specification status comment gamepad extensionsthe definition of 'pulse()' in that specification.
GamepadHapticActuator.type - Web APIs
examples tbc specifications specification status comment gamepad extensionsthe definition of 'gamepadhapticactuatortype' in that specification.
GamepadHapticActuator - Web APIs
examples tbd.
Geolocation.clearWatch() - Web APIs
example var id, target, option; function success(pos) { var crd = pos.coords; if (target.latitude === crd.latitude && target.longitude === crd.longitude) { console.log('congratulation, you reach the target'); navigator.geolocation.clearwatch(id); } }; function error(err) { console.warn('error(' + err.code + '): ' + err.message); }; target = { latitude : 0, longitude: 0, } options = { enablehighaccuracy: false, timeout: 5000, maximumage: 0...
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 }; opt...
GlobalEventHandlers.onabort - Web APIs
example window.onabort = function() { alert('load aborted.'); } specification specification status comment html living standardthe definition of 'onabort' in that specification.
GlobalEventHandlers.onauxclick - Web APIs
example in this example we define functions for two event handlers — onclick and onauxclick.
GlobalEventHandlers.onblur - Web APIs
example this example uses onblur and onfocus to change the text within an <input> element.
GlobalEventHandlers.onemptied - Web APIs
the emptied event is fired when the media has become empty; for example, this event is sent if the media has already been loaded (or partially loaded), and the load() method is called to reload it.
GlobalEventHandlers.onerror - Web APIs
a good example for this is when you are using an image tag, and need to specify a backup image in case the one you need is not available on the server for any reason.
GlobalEventHandlers.onfocus - Web APIs
example this example uses onblur and onfocus to change the text within an <input> element.
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 fir...
GlobalEventHandlers.ongotpointercapture - Web APIs
example function overhandler(event) { // determine the target event's gotpointercapture handler let gotcapturehandler = event.target.ongotpointercapture; } function init() { let el = document.getelementbyid('target'); el.ongotpointercapture = overhandler; } specifications specification status comment pointer events – level 2the definition of 'ongotpointercapture' in that specification.
GlobalEventHandlers.oninput - Web APIs
example this example logs the number of characters in an <input> element, every time you modify its contents.
GlobalEventHandlers.onkeydown - Web APIs
example this example logs the keyboardevent.code value whenever you press down a key inside the <input> element.
GlobalEventHandlers.onkeyup - Web APIs
example this example logs the keyboardevent.code value whenever you release a key inside the <input> element.
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 ev...
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 l...
GlobalEventHandlers.onlostpointercapture - Web APIs
example function overhandler(event) { // determine the target event's lostpointercapture handler let lostcapturehandler = event.target.onlostpointercapture; } function init() { let el = document.getelementbyid('target'); el.onlostpointercapture = overhandler; } specifications specification status comment pointer events – level 2the definition of 'onlostpointercapture' in that specification.
GlobalEventHandlers.onmousedown - Web APIs
example this example reveals part of an image when you press and hold a mouse button.
GlobalEventHandlers.onmouseover - Web APIs
syntax element.onmouseover = function; example this example adds an onmouseover and an onmouseout event to a paragraph.
GlobalEventHandlers.onmouseup - Web APIs
example in this example, a piece of "toast" hides when you click down with the mouse, and reappears when you release.
GlobalEventHandlers.onplay - Web APIs
example <p>this example demonstrates how to assign an "onplay" event to a video element.</p> <video controls onplay="alertplay()"> <source src="mov_bbb.mp4" type="video/mp4"> <source src="mov_bbb.ogg" type="video/ogg"> your browser does not support html5 video.
GlobalEventHandlers.onpointercancel - Web APIs
example this example shows two ways to use onpointercancel to handle an element's pointercancel events.
GlobalEventHandlers.onpointerenter - Web APIs
example this example shows two ways to use onpointerenter to set an element's pointerenter event handler.
GlobalEventHandlers.onpointermove - Web APIs
example this example shows two ways to use onpointermove to set an element's pointermove event handler.
GlobalEventHandlers.onpointerout - Web APIs
example this example shows two ways to use onpointerout to set an element's pointerout event handler.
GlobalEventHandlers.onpointerover - Web APIs
example this example shows two ways to use onpointerover to set an element's pointerover event handler.
GlobalEventHandlers.onpointerup - Web APIs
example this example shows two ways to use onpointerup to set an element's pointerup event handler.
GlobalEventHandlers.onreset - Web APIs
example this example logs the current event.timestamp whenever you reset the form.
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; specificatio...
GlobalEventHandlers.onscroll - Web APIs
example this example monitors scrolling on a <textarea>, and logs the element's vertical scroll position accordingly.
GlobalEventHandlers.onselect - Web APIs
examples this example logs the text you select inside a <textarea> element.
GlobalEventHandlers.onselectionchange - Web APIs
example let selection; document.onselectionchange = function() { console.log('new selection made'); selection = document.getselection(); }; for a full example, see our key quote generator demo.
GlobalEventHandlers.onselectstart - Web APIs
example document.onselectstart = function() { console.log('selection started!'); }; for a full example, see our key quote generator demo.
GlobalEventHandlers.ontouchcancel - Web APIs
example this example shows two ways to use ontouchcancel to set an element's touchcancel event handler.
GlobalEventHandlers.ontouchend - Web APIs
example this example shows two ways to use ontouchend to set an element's touchend event handler.
GlobalEventHandlers.ontouchmove - Web APIs
example this example shows two ways to use ontouchmove to set an element's touchmove event handler.
GlobalEventHandlers.ontouchstart - Web APIs
example this example shows two ways to use ontouchstart to set an element's touchstart event handler.
GlobalEventHandlers.ontransitioncancel - Web APIs
example in this example, we use the transitionrun and transitionend events to detect when the transition begins and ends, to cause a text update to occur during the transition.
GlobalEventHandlers.ontransitionend - Web APIs
example in this example, we use the transitionrun and transitionend events to detect when the transition begins and ends, to cause a text update to occur during the transition.
GlobalEventHandlers.onwheel - Web APIs
examples this example shows how to scale an element using the mouse (or other pointing device) wheel.
HTMLAnchorElement.referrerPolicy - Web APIs
examples var elt = document.createelement("a"); var linktext = document.createtextnode("my link"); elt.appendchild(linktext); elt.href = "https://developer.mozilla.org/"; elt.referrerpolicy = "no-referrer"; var div = document.getelementbyid("divaround"); div.appendchild(elt); // when clicked, the link will not send a referrer header.
HTMLAnchorElement.rel - Web APIs
syntax var relstr = anchorelt.rel; anchorelt.rel = relstr; example var anchors = document.getelementsbytagname("a"); var length = anchors.length; for (var i = 0; i < length; i++) { alert("rel: " + anchors[i].rel); } specifications specification status comment html living standardthe definition of 'rel' in that specification.
HTMLAnchorElement.relList - Web APIs
syntax var relstr = anchorelt.rellist; example var anchors = document.getelementsbytagname("a"); var length = anchors.length; for (var i = 0; i < length; i++) { var list = anchors[i].rellist; var listlength = list.length; console.log("new anchor node found with", listlength, "link types in rellist."); for (var j = 0; j < listlength; j++) { console.log(list[j]); } } specifications specification status comment ...
HTMLAreaElement.referrerPolicy - Web APIs
examples <img usemap="#maparound" width="100" height="100" src="/img/logo@2x.png" /> <map id="mymap" name="maparound" />> var elt = document.createelement("area"); elt.href = "/img2.png"; elt.shape = "rect"; elt.referrerpolicy = "no-referrer"; elt.coords = "0,0,100,100"; var map = document.getelementbyid("mymap"); map.appendchild(elt); // when clicked, the area's link will not send a referrer header.
HTMLAreaElement.rel - Web APIs
syntax var relstr = areaelt.rel; areaelt.rel = relstr; example var areas = document.getelementsbytagname("area"); var length = areas.length; for (var i = 0; i < length; i++) { alert("rel: " + areas[i].rel); } specifications specification status comment html living standardthe definition of 'rel' in that specification.
HTMLAreaElement.relList - Web APIs
syntax var relstr = areaelt.rellist; example var areas = document.getelementsbytagname("area"); var length = areas.length; for (var i = 0; i < length; i++) { var list = areas[i].rellist; var listlength = list.length; console.log("new area found."); for (var j = 0; j < listlength; j++) { console.log(list[j]); } } specifications specification status comment html living standardthe definition of '...
HTMLAudioElement - Web APIs
examples basic usage you can create a htmlaudioelement entirely with javascript using the audio() constructor: var audioelement = new audio('car_horn.wav'); then you can invoke the play() method on the element audioelement.play(); a common gotcha is trying to play an audio element immediately on page load.
HTMLButtonElement.labels - Web APIs
example html <label id="label1" for="test">label 1</label> <button id="test">button</button> <label id="label2" for="test">label 2</label> javascript window.addeventlistener("domcontentloaded", function() { const button = document.getelementbyid("test"); for(var i = 0; i < button.labels.length; i++) { console.log(button.labels[i].textcontent); // "label 1" and "label 2" } }); specifications specification status comment html living standardthe definition of 'labels' in that specificat...
HTMLButtonElement - Web APIs
htmlbuttonelement.autofocus is a boolean indicating whether or not the control should have input focus when the page loads, unless the user overrides it, for example by typing in a different control.
HTMLCanvasElement.captureStream() - Web APIs
example // find the canvas element to capture var canvaselt = document.queryselector('canvas'); // get the stream var stream = canvaselt.capturestream(25); // 25 fps // do things to the stream // e.g.
HTMLCanvasElement.height - Web APIs
syntax var pxl = canvas.height; canvas.height = pxl; examples given this <canvas> element: <canvas id="canvas" width="300" height="300"></canvas> you can get the height of the canvas with the following code: var canvas = document.getelementbyid('canvas'); console.log(canvas.height); // 300 specifications specification status comment html living standardthe definition of 'htmlcanvaselement.height' in that specification.
HTMLCanvasElement.mozFetchAsStream() - Web APIs
examples save to disk with mozfetchasstream (chrome context only) this technique also converts it to ico, however it will not work in windows xp as winxp cannot convert from png to ico.
HTMLCanvasElement.mozGetAsFile() - Web APIs
examples this example creates an image file from the <canvas> element on the page, then uses a filereader to read the image data from the file.
HTMLCanvasElement.transferControlToOffscreen() - Web APIs
examples var htmlcanvas = document.createelement('canvas'); var offscreen = htmlcanvas.transfercontroltooffscreen(); var gl = offscreen.getcontext('webgl'); // ...
HTMLCanvasElement: webglcontextcreationerror event - Web APIs
bubbles yes cancelable yes interface webglcontextevent event handler property none example var canvas = document.getelementbyid('canvas'); canvas.addeventlistener('webglcontextcreationerror', function(e) { console.log(e.statusmessage || 'unknown error'); }, false); var gl = canvas.getcontext('webgl'); // logs statusmessage or "unknown error" if unable to create webgl context specifications specification status comment webgl 1.0the definition of 'webglcon...
HTMLCanvasElement: webglcontextlost event - Web APIs
bubbles yes cancelable yes interface webglcontextevent event handler property none example with the help of the webgl_lose_context extension, you can simulate the webglcontextlost event: const canvas = document.getelementbyid('canvas'); const gl = canvas.getcontext('webgl'); canvas.addeventlistener('webglcontextlost', (event) => { console.log(event); }); gl.getextension('webgl_lose_context').losecontext(); // "webglcontextlost" event is logged.
HTMLCanvasElement: webglcontextrestored event - Web APIs
bubbles yes cancelable yes interface webglcontextevent event handler property none example with the help of the webgl_lose_context extension, you can simulate the webglcontextrestored event: var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); canvas.addeventlistener('webglcontextrestored', function(e) { console.log(e); }, false); gl.getextension('webgl_lose_context').restorecontext(); // "webglcontextrestored" event is logged.
HTMLCanvasElement.width - Web APIs
syntax var pxl = canvas.width; canvas.width = pxl; examples given this <canvas> element: <canvas id="canvas" width="300" height="300"></canvas> you can get the width of the canvas with the following code: var canvas = document.getelementbyid('canvas'); console.log(canvas.width); // 300 specifications specification status comment html living standardthe definition of 'htmlcanvaselement.width' in that specification.
HTMLCollection - Web APIs
for example, assuming there is one <form> element in the document and its id is myform: var elem1, elem2; // document.forms is an htmlcollection elem1 = document.forms[0]; elem2 = document.forms.item(0); alert(elem1 === elem2); // shows: "true" elem1 = document.forms.myform; elem2 = document.forms.nameditem("myform"); alert(elem1 === elem2); // shows: "true" elem1 = document.forms["named.item.with.per...
HTMLContentElement.getDistributedNodes() - Web APIs
syntax var nodelist = object.getdistributednodes() example // get the distributed nodes var nodes = mycontentobject.getdistributednodes(); specifications this feature is no longer defined by any specifications.
HTMLContentElement.select - Web APIs
syntax object.select = "cssselector cssselector ..."; example // select <h1> elements and elements with class="error" mycontentobject.select = "h1 .error"; specifications this feature is no longer defined by any standards.
HTMLDetailsElement: toggle event - Web APIs
examples this example logs chapters that are open.
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.show() - Web APIs
examples the following example shows a simple button that, when clicked, opens a <dialog> containing a form via the show() method.
accessKeyLabel - Web APIs
syntax label = element.accesskeylabel example javascript var node = document.getelementbyid('btn1'); if (node.accesskeylabel) { node.title += ' [' + node.accesskeylabel + ']'; } else { node.title += ' [' + node.accesskey + ']'; } node.onclick = function () { var p = document.createelement('p'); p.textcontent = 'clicked!'; node.parentnode.appendchild(p); }; html <button accesskey="h" title="caption" id="btn1">hover me</button> result specifications specification status comment html living standardthe definition of 'htmlelement.accesskeylabel' in that specification.
HTMLElement: 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 r...
HTMLElement.click() - Web APIs
WebAPIHTMLElementclick
syntax element.click() example simulate a mouse-click when moving the mouse pointer over a checkbox: html <form> <input type="checkbox" id="mycheck" onmouseover="myfunction()" onclick="alert('click event occured')"> </form> javascript // on mouse-over, execute myfunction function myfunction() { document.getelementbyid("mycheck").click(); } specification specification status comment html living standard living standard document object model (dom...
HTMLElement.contextMenu - Web APIs
syntax var elementcontextmenu = element.contextmenu; example var contextmenu = document.getelementbyid("element").contextmenu; // change the label of the first menu entry contextmenu.firstelementchild.label = "new label"; ...
HTMLElement.dir - Web APIs
WebAPIHTMLElementdir
example var parg = document.getelementbyid("para1"); parg.dir = "rtl"; // change the text direction on a paragraph identified as "para1" specifications specification status comment html living standardthe definition of 'dir' in that specification.
HTMLElement.forceSpellCheck() - Web APIs
the specific user interface of the check, for example whether red underlining appears, is determined by the user agent.
HTMLElement.hidden - Web APIs
example here's an example where a hidden block is used to contain a thank you message that is displayed after a user agrees to an unusual request.
HTMLElement.innerText - Web APIs
example this example compares innertext with node.textcontent.
HTMLElement: input event - Web APIs
examples this example logs the value whenever you change the value of the <input> element.
HTMLElement.isContentEditable - Web APIs
syntax editable = element.iscontenteditable example html <p id="mytext1">uneditable paragraph</p> <p id="mytext2" contenteditable="true">editable paragraph</p> <p id="infotext1">can edit the first paragraph?
HTMLElement.offsetLeft - Web APIs
example var colortable = document.getelementbyid("t1"); var toleft = colortable.offsetleft; if (toleft > 5) { // large left offset: do something here } this example shows a 'long' sentence that wraps within a div with a blue border, and a red box that one might think should describe the boundaries of the span.
HTMLElement.offsetTop - Web APIs
example var d = document.getelementbyid("div1"); var toppos = d.offsettop; if (toppos > 10) { // object is offset more // than 10 pixels from its parent } specification specification status comment css object model (cssom) view modulethe definition of 'offsettop' in that specification.
HTMLElement.oncopy - Web APIs
example this example blocks every copy and paste attempt from the <textarea>.
HTMLElement.oncut - Web APIs
WebAPIHTMLElementoncut
example this example allows text to be copied from the <textarea>, but doesn't allow text to be cut.
HTMLElement.onpaste - Web APIs
example this example logs every copy and paste attempt to the <textarea>.
HTMLElement.outerText - Web APIs
example see this stackoverflow answer.
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 ev...
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 sp...
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.title - Web APIs
WebAPIHTMLElementtitle
syntax var str = element.title; element.title = str; example const link = document.createelement('a'); link.innertext = 'grapes'; link.href = 'https://en.wikipedia.org/wiki/grape'; link.title = 'wikipedia page on grapes'; specifications specification status comment html living standardthe definition of 'title' in that specification.
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 th...
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> .tran...
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> ta...
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 ...
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 ...
HTMLFontElement - Web APIs
htmlfontelement.size is a domstring that reflects the size html attribute, containing either a font size number ranging from 1 to 7 or a relative size to the size attribute of the <basefont> element, for example -2 or +1.
HTMLFormControlsCollection.namedItem() - Web APIs
example html <form> <input id="my-form-control" type="textarea"> </form> javascript // returns the htmlinputelement representing #my-form-control elem1 = document.forms[0]['my-form-control']; specifications specification status comment html living standardthe definition of 'htmlformcontrolscollection.nameditem()' in that specification.
HTMLFormElement.acceptCharset - Web APIs
syntax var string = form.acceptcharset; form.acceptcharset = string; example inputs = document.forms['myform'].acceptcharset; specifications specification status comment html living standardthe definition of 'htmlformelement: acceptcharset' in that specification.
HTMLFormElement.action - Web APIs
syntax var string = form.action; form.action = string; example form.action = '/cgi-bin/publish'; specifications specification status comment html living standardthe definition of 'htmlformelement: action' in that specification.
HTMLFormElement.enctype - Web APIs
syntax var string = form.enctype; form.enctype = string; example form.enctype = 'application/x-www-form-urlencoded'; specifications specification status comment html living standardthe definition of 'htmlformelement: enctype' in that specification.
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.length - Web APIs
example if (document.getelementbyid('form1').length > 1) { // more than one form control here } specifications specification status comment html living standardthe definition of 'htmlformelement: length' in that specification.
HTMLFormElement.method - Web APIs
syntax var string = form.method; form.method = string; example document.forms['myform'].method = 'post'; const formelement = document.createelement("form"); // create a form document.body.appendchild(formelement); console.log(formelement.method); // 'get' specifications specification status comment html living standardthe definition of 'htmlformelement: method' in that specification.
HTMLFormElement.name - Web APIs
syntax var string = form.name; form.name = string; example var form1name = document.getelementbyid('form1').name; if (form1name != document.form.form1) { // browser doesn't support this form of reference } specifications specification status comment html living standardthe definition of 'htmlformelement: name' in that specification.
HTMLFormElement.reportValidity() - Web APIs
syntax htmlformelement.reportvalidity() return value boolean example document.forms['myform'].addeventlistener('submit', function() { document.forms['myform'].reportvalidity(); }, false); specifications specification status comment html living standardthe definition of 'htmlformelement.reportvalidity()' in that specification.
HTMLFormElement.requestSubmit() - Web APIs
examples in the example below, the form is submitted by attempting to send the request using requestsubmit() if it's available.
HTMLFormElement.reset() - Web APIs
syntax htmlformelement.reset() example document.getelementbyid('myform').reset(); specifications specification status comment html living standardthe definition of 'htmlformelement: reset' in that specification.
HTMLFormElement: reset event - Web APIs
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() - Web APIs
syntax htmlformelement.submit() example document.forms["myform"].submit(); specifications specification status comment html living standardthe definition of 'htmlformelement: submit' in that specification.
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.target - Web APIs
syntax string = htmlformelement.target htmlformelement.target = string example myform.target = document.frames[1].name; specifications specification status comment html living standardthe definition of 'htmlformelement: target' in that specification.
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 li...
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 li...
HTMLHyperlinkElementUtils.toString() - Web APIs
syntax string = object.tostring(); examples // let's imagine an <a id="myanchor" href="https://developer.mozilla.org/docs/htmlhyperlinkelementutils/tostring"> element is in the document var anchor = document.getelementbyid("myanchor"); var result = anchor.tostring(); // returns: 'https://developer.mozilla.org/docs/htmlhyperlinkelementutils/tostring' specifications specification status comment html living standard living standard ...
HTMLHyperlinkElementUtils.username - Web APIs
syntax string = object.username; object.username = string; examples // let's <a id="myanchor" href="https://anonymous:flabada@developer.mozilla.org/docs/htmlhyperlinkelementutils.username"> be in the document var anchor = document.getelementbyid("myanchor"); var result = anchor.username; // returns:'anonymous' specifications specification status comment html living standardthe definition of 'htmlhyperlinkelementutils.username' in that specification.
contentDocument - Web APIs
example of contentdocument var iframedocument = document.getelementsbytagname("iframe")[0].contentdocument; iframedocument.body.style.backgroundcolor = "blue"; // this would turn the iframe blue.
HTMLIFrameElement.contentWindow - Web APIs
example of contentwindow var x = document.getelementsbytagname("iframe")[0].contentwindow; //x = window.frames[0]; x.document.getelementsbytagname("body")[0].style.backgroundcolor = "blue"; // this would turn the 1st iframe in document blue.
HTMLIFrameElement.src - Web APIs
syntax refstr = iframeelt.src; iframeelt.src= refstr; example var iframe = document.createelement("iframe"); iframe.src = "/"; var body = document.getelementsbytagname("body")[0]; body.appendchild(iframe); // fetch the image using the complete url as the referrer specifications specification status comment html living standardthe definition of 'htmliframeelement: src' in that specification.
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.border - Web APIs
for example, if you have the following html: <img src="image.png" border="2"> the following will provide the same appearance using css instead of this obsolete property: <img src="image.png" style="border: 2px;"> you can further provide additional information to change the color and other features of the border: <img src="image.png" style="border: dashed 2px #333388;"> specifications specific...
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.crossOrigin - Web APIs
example in this example, a new <img> element is created and added to the document, loading the image with the anonymous state; the image will be loaded using cors and credentials will be used for all cross-origin loads.
HTMLImageElement.currentSrc - Web APIs
example in this example, two different sizes are provided for an image of a clock.
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.loading - Web APIs
example the addimagetolist() function shown below adds a photo thumbnail to a list of items, using lazy-loading to avoid loading the image from the network until it's actually needed.
HTMLImageElement.longDesc - Web APIs
for example, if the image is a png of a flowchart.
HTMLImageElement.lowSrc - Web APIs
there are a number of ways to achieve this; primary among them: higher compression levels (for example, a primary image saved as a jpeg using 85% quality might have a lowsrc version saved at 15%.
HTMLImageElement.naturalHeight - Web APIs
example this example simply displays both the natural, density-adjusted size of an image as well as its rendered size as altered by the page's css and other factors.
HTMLImageElement.naturalWidth - Web APIs
example this example simply displays both the natural, density-adjusted size of an image as well as its rendered size as altered by the page's css and other factors.
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.
HTMLImageElement - Web APIs
example var img1 = new image(); // image constructor img1.src = 'image1.png'; img1.alt = 'alt'; document.body.appendchild(img1); var img2 = document.createelement('img'); // use dom htmlimageelement img2.src = 'image2.jpg'; img2.alt = 'alt text'; document.body.appendchild(img2); // using first image in the document alert(document.images[0].src); specifications specification status co...
HTMLInputElement.labels - Web APIs
example html <label id="label1" for="test">label 1</label> <input id="test"/> <label id="label2" for="test">label 2</label> javascript window.addeventlistener("domcontentloaded", function() { const input = document.getelementbyid("test"); for(var i = 0; i < input.labels.length; i++) { console.log(input.labels[i].textcontent); // "label 1" and "label 2" } }); specifications specification status comment html living standardthe definition of 'labels' in that specification.
HTMLInputElement.mozGetFileNameArray() - Web APIs
example var numfiles = 0; var filearray = {}; inputelement.mozgetfilenamearray(numfiles, filearray); ...
HTMLInputElement.mozSetFileNameArray() - Web APIs
example var filearray = {"/foo/bar.txt", "/foo/foosball.txt"}; inputelement.mozsetfilenamearray(filearray, filearray.length); ...
HTMLInputElement.multiple - Web APIs
example // fileinput is a <input type=file multiple> let fileinput = document.getelementbyid('myfileinput'); if (fileinput.multiple == true) { for (let i = 0; i < fileinput.files.length; i++) { // loop fileinput.files } // only one file available } else { let file = fileinput.files.item(0); } ...
HTMLInputElement: 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...
HTMLInputElement.select() - Web APIs
syntax element.select(); example click the button in this example to select all the text in the <input> element.
HTMLInputElement.setRangeText() - Web APIs
example click the button in this example to replace part of the text in the text box.
HTMLInputElement.webkitEntries - Web APIs
example this example shows how to create a file selection <input> element and process the selected files.
HTMLInputElement - Web APIs
see also readonly autofocus boolean: returns / sets the element's autofocus attribute, which specifies that a form control should have input focus when the page loads, unless the user overrides it, for example by typing in a different control.
HTMLLinkElement.referrerPolicy - Web APIs
syntax domstring htmllinkelement.referrerpolicy example var links = document.getelementsbytagname("link"); links[0].referrerpolicy; // "no-referrer" specifications specification status comment referrer policythe definition of 'referrerpolicy attribute' in that specification.
HTMLLinkElement.rel - Web APIs
syntax var relstr = linkelt.rel; linkelt.rel = relstr; example var links = document.getelementsbytagname('link'); var length = links.length; for (var i = 0; i < length; i++) { alert(links[i]); } specifications specification status comment html living standardthe definition of 'rel' in that specification.
HTMLLinkElement.relList - Web APIs
syntax var relstr = linkelt.rellist; example var links = document.getelementsbytagname("link"); var length = links.length; for (var i = 0; i < length; i++) { var list = links[i].rellist; var listlength = list.length; console.log("new link found."); for (var j = 0; j < listlength; j++) { console.log(list[j]); } } specifications specification status comment html living standardthe definition of 'r...
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.audioTracks - Web APIs
examples in this example, all of the audio tracks on a given element are muted.
HTMLMediaElement.autoplay - Web APIs
examples ...
HTMLMediaElement.buffered - Web APIs
example var obj = document.createelement('video'); console.log(obj.buffered); // timeranges { length: 0 } specifications specification status comment html living standardthe definition of 'htmlmediaelement.buffered' in that specification.
HTMLMediaElement.canPlayType() - Web APIs
example var obj = document.createelement('video'); console.log(obj.canplaytype('video/mp4')); // "maybe" specifications specification status comment html living standardthe definition of 'canplaytype' in that specification.
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.controller - Web APIs
example ...
HTMLMediaElement.controls - Web APIs
example var obj = document.createelement('video'); obj.controls = true; specifications specification status comment html living standardthe definition of 'htmlmediaelement.controls' in that specification.
HTMLMediaElement.currentTime - Web APIs
example var video = document.createelement('video'); console.log(video.currenttime); usage notes reduced time precision to offer protection against timing attacks and fingerprinting, browsers may round or otherwise adjust the value returned by currenttime.
HTMLMediaElement.defaultMuted - Web APIs
example var videoele = document.createelement('video'); videoele.defaultmuted = true; console.log(videoele.outerhtml); // <video muted=""></video> specifications specification status comment html living standardthe definition of 'htmlmediaelement.defaultmuted' in that specification.
HTMLMediaElement.defaultPlaybackRate - Web APIs
example var obj = document.createelement('video'); console.log(obj.defaultplaybackrate); // 1 specifications specification status comment html living standardthe definition of 'htmlmediaelement.defaultplaybackrate' in that specification.
HTMLMediaElement.disableRemotePlayback - Web APIs
(false means "not disabled", which means "enabled") example var obj = document.createelement('audio'); obj.disableremoteplayback = true; specifications specification status comment remote playback apithe definition of 'disableremoteplayback' in that specification.
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.ended - Web APIs
example var obj = document.createelement('video'); console.log(obj.ended); // false specifications specification status comment html living standardthe definition of 'htmlmediaelement.ended' in that specification.
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.fastSeek() - Web APIs
example this example quickly seeks to 20-second position of the video element.
HTMLMediaElement.initialTime - Web APIs
example ...
HTMLMediaElement.load() - Web APIs
example this example finds a <video> element in the document and resets it by calling load().
HTMLMediaElement: loadeddata event - Web APIs
examples these examples add an event listener for the htmlmediaelement's loadeddata event, then post a message when that event handler has reacted to the event firing.
HTMLMediaElement: loadedmetadata event - Web APIs
examples these examples add an event listener for the htmlmediaelement's loadedmetadata event, then post a message when that event handler has reacted to the event firing.
HTMLMediaElement.loop - Web APIs
example var obj = document.createelement('video'); obj.loop = true; // true specifications specification status comment html living standardthe definition of 'htmlmediaelement.loop' in that specification.
HTMLMediaElement.mediaGroup - Web APIs
example ...
HTMLMediaElement.muted - Web APIs
example var obj = document.createelement('video'); console.log(obj.muted); // false specifications specification status comment html living standardthe definition of 'htmlmediaelement.muted' in that specification.
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.paused - Web APIs
example var obj = document.createelement('video'); console.log(obj.paused); // true specifications specification status comment html living standardthe definition of 'htmlmediaelement.paused' in that specification.
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 de...
HTMLMediaElement.src - Web APIs
example var obj = document.createelement('video'); console.log(obj.src); // "" specifications specification status comment html living standardthe definition of 'htmlmediaelement.src' in that specification.
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.
HTMLMedia​Element​.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.volume - Web APIs
example var obj = document.createelement('audio'); console.log(obj.volume); // 1 obj.volume = 0.75; specifications specification status comment html living standardthe definition of 'htmlmediaelement.volume' in that specification.
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.
HTMLMeterElement.labels - Web APIs
example html <label id="label1" for="test">label 1</label> <meter id="test" min="0" max="100" value="70">70</meter> <label id="label2" for="test">label 2</label> javascript window.addeventlistener("domcontentloaded", function() { const meter = document.getelementbyid("test"); for(var i = 0; i < meter.labels.length; i++) { console.log(meter.labels[i].textcontent); // "label 1" and "label 2" } }); specifications specification status comment html living standardthe definition of 'labels' in...
HTMLObjectElement.setCustomValidity - Web APIs
examples in this example, we pass the id of an input element, and set different error messages depending on whether the value is missing, too low or too high.
HTMLObjectElement.typeMustMatch - Web APIs
syntax var mustmatch = obj.typemustmatch; obj.typemustmatch = mustmatch; example html <object id="obj" data="move.swf" type="application/x-shockwave-flash" typemustmatch></object> javascript let obj = document.getelementbyid('obj'); console.log(obj.typemustmatch); specifications specification status comment html5the definition of 'htmlobjectelement' in that specification.
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</opti...
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.
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.
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).
HTMLOrForeignElement.tabIndex - Web APIs
syntax element.tabindex = index; var index = element.tabindex; value index is an integer example const b1 = document.getelementbyid('button1'); b1.tabindex = 1; specifications specification status comment html living standardthe definition of 'tabindex' in that specification.
HTMLOutputElement.labels - Web APIs
example html <label id="label1" for="test">label 1</label> <output id="test">output</output> <label id="label2" for="test">label 2</label> javascript window.addeventlistener("domcontentloaded", function() { const output = document.getelementbyid("test"); for(var i = 0; i < output.labels.length; i++) { console.log(output.labels[i].textcontent); // "label 1" and "label 2" } }); specifications specification status comment html living standardthe definition of 'labels' in that specificat...
HTMLProgressElement.labels - Web APIs
example html <label id="label1" for="test">label 1</label> <progress id="test" value="70" max="100">70%</progress> <label id="label2" for="test">label 2</label> javascript window.addeventlistener("domcontentloaded", function() { const progress = document.getelementbyid("test"); for(var i = 0; i < progress.labels.length; i++) { console.log(progress.labels[i].textcontent); // "label 1" and "label 2" } }); specifications specification status comment html living standardthe defin...
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: va...
HTMLSelectElement.autofocus - Web APIs
syntaxedit abool = aselectelement.autofocus; // get the value of autofocus aselectelement.autofocus = abool; // set the value of autofocus example html <select id="myselect" autofocus> <option>option 1</option> <option>option 2</option> </select> javascript // check if the autofocus attribute on the <select> var hasautofocus = document.getelementbyid('myselect').autofocus; specifications specification status comment html living standardthe definition of 'autofocus' in that specification.
HTMLSelectElement.disabled - Web APIs
syntax edit aselectelement.disabled = abool; example html <label> allow drinks?
HTMLSelectElement.form - Web APIs
syntax edit aform = aselectelement.form.selectname; example html <form action="http://www.google.com/search" method="get"> <label>google: <input type="search" name="q"></label> <input type="submit" value="search..."> </form> javascript a property available on all form elements, "type" returns the type of the calling form element.
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()' i...
HTMLSelectElement.labels - Web APIs
example html <label id="label1" for="test">label 1</label> <select id="test"> <option value="1">option 1</option> <option value="2">option 2</option> </select> <label id="label2" for="test">label 2</label> javascript window.addeventlistener("domcontentloaded", function() { const select = document.getelementbyid("test"); for(var i = 0; i < select.labels.length; i++) { console.log(select.labels[i].textcontent); // "label 1" and "label 2" } }); specifications specification status comment ...
HTMLSelectElement.namedItem() - Web APIs
example html <form> <select id="myformcontrol"> <option id="o1">opt 1</option> <option id="o2">opt 2</option> </select> </form> javascript elem1 = document.forms[0]['myformcontrol']['o1']; // returns the htmloptionelement representing #o1 specifications specification status comment html living standardthe definition of 'htmlselectelement.nameditem()' in that sp...
HTMLSelectElement.options - Web APIs
example html <label for="test">label</label> <select id="test"> <option value="1">option 1</option> <option value="2">option 2</option> </select> javascript window.addeventlistener("domcontentloaded", function() { const select = document.getelementbyid("test"); for(var i = 0; i < select.options.length; i++) { console.log(select.options[i].label); // "option 1" and "option 2" } }); specifications specification status comment html living standardthe definition of ...
HTMLSelectElement.remove() - Web APIs
example var sel = document.getelementbyid("existinglist"); sel.remove(1); /* takes the existing following select object: <select id="existinglist" name="existinglist"> <option value="1">option: value 1</option> <option value="2">option: value 2</option> <option value="3">option: value 3</option> </select> and changes it to: <select id="existinglist" name="existinglist"> <option value="1">option: value 1</option> <option value="3">option: v...
HTMLSelectElement.selectedIndex - Web APIs
syntax var index = selectelem.selectedindex; selectelem.selectedindex = index; example html <p id="p">selectedindex: 0</p> <select id="select"> <option selected>option a</option> <option>option b</option> <option>option c</option> <option>option d</option> <option>option e</option> </select> javascript var selectelem = document.getelementbyid('select') var pelem = document.getelementbyid('p') // when a new <option> is selected selectelem.addeventlistener('change', function() { var index = selectelem.selectedindex; // add that data to the <p> pelem.innerhtml = 'select...
HTMLSelectElement.selectedOptions - Web APIs
example in this example, a <select> element with a number of options is used to let the user order various food items.
HTMLSelectElement.type - Web APIs
example switch (select.type) { case 'select-multiple': // multiple values may be selected break; case 'select-one': // only one value may be selected break; default: // non-standard value (or this isn't a select element) } specifications specification status comment html living standardthe definition of 'htmlselectelement' in that specification.
HTMLShadowElement.getDistributedNodes() - Web APIs
syntax var nodelist = object.getdistributednodes() example // get the distributed nodes var nodes = myshadowobject.getdistributednodes(); specifications this feature is no longer defined by any specifications.
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.
HTMLStyleElement.media - Web APIs
example <!doctype html> <html> <head> <link id="linkedstyle" rel="stylesheet" href="document.css" type="text/css" media="screen" /> <style id="inlinestyle" rel="stylesheet" type="text/css" media="screen, print"> p { color: blue; } </style> </head> <body> <script> alert('linkedstyle: ' + document.getelementbyid('linkedstyle').media); // 'screen' alert('inlinestyle: ' + document.getelementbyid('inlinestyle').media); // 'screen, print' </script> </body> </html> specifications specification status comment html living standardt...
HTMLStyleElement.type - Web APIs
for gecko, the type is most often given as "text/css." from the w3c spec on css: "the expectation is that binding-specific casting methods can be used to cast down from an instance of the cssrule interface to the specific derived interface implied by the type." syntax string = style.type; example if (newstyle.type != "text/css"){ // not supported!
HTMLTableElement.align - Web APIs
syntax htmltableelement.align = alignment; var alignment = htmltableelement.align; parameters alignment domstring with one of the following values: left center right example // set the alignmnet of a table var t = document.getelementbyid('tablea'); t.align = 'center'; specification w3c dom 2 html specification htmltableelement .align.
HTMLTableElement.bgColor - Web APIs
example // set table background colour to lightblue var t = document.getelementbyid('tablea'); t.bgcolor = 'lightblue'; specification dom level 2 html:htmltableelement .bgcolor ...
HTMLTableElement.border - Web APIs
example // set the width of a table border to 2 pixels var t = document.getelementbyid('tablea'); t.border = '2'; specification w3c dom 2 html specification htmltableelement .border.
HTMLTableElement.caption - Web APIs
syntax var string = tableelement.caption; example if (table.caption) { // do something with the caption } specifications specification status comment html living standardthe definition of 'htmltableelement.caption' in that specification.
HTMLTableElement.cellPadding - Web APIs
example // set cell padding to 10 pixels let t = document.getelementbyid('tablea'); t.cellpadding = '10'; specification w3c dom 2 html specification htmltableelement .cellpadding.
HTMLTableElement.cellSpacing - Web APIs
example this example sets cell spacing for a given table to 10 pixels.
HTMLTableElement.createCaption() - Web APIs
syntax htmltableelement = table.createcaption(); return value htmltablecaptionelement example this example uses javascript to add a caption to a table that initially lacks one.
HTMLTableElement.createTFoot() - Web APIs
syntax htmltablesectionelement = table.createtfoot(); return value htmltablesectionelement example let myfoot = mytable.createtfoot(); // now this should be true: myfoot == mytable.tfoot specifications specification status comment html living standardthe definition of 'htmltableelement: createtfoot' in that specification.
HTMLTableElement.createTHead() - Web APIs
syntax htmltablesectionelement = table.createthead(); return value htmltablesectionelement example let myhead = mytable.createthead(); // now this should be true: myhead == mytable.thead specifications specification status comment html living standardthe definition of 'htmltableelement: createthead' in that specification.
HTMLTableElement.deleteCaption() - Web APIs
syntax htmltableelement.deletecaption() example this example uses javascript to delete a table's caption.
HTMLTableElement.deleteRow() - Web APIs
example this example uses javascript to delete a table's second row.
HTMLTableElement.deleteTFoot() - Web APIs
syntax htmltableelement.deletetfoot(); example this example uses javascript to delete a table's footer.
HTMLTableElement.deleteTHead() - Web APIs
syntax htmltableelement.deletethead(); example this example uses javascript to delete a table's header.
HTMLTableElement.frame - Web APIs
"above" top side "below" bottom side "hsides" top and bottom only "vsides" right and left sides only "lhs" left-hand side only "rhs" right-hand side only "box" all four sides "border" all four sides example // set the frame of tablea to 'border' var t = document.getelementbyid('tablea'); t.frame = "border"; t.border = "2px"; specification w3c dom 2 html specification ...
HTMLTableElement.insertRow() - Web APIs
example this example uses insertrow(-1) to append a new row to a table.
HTMLTableElement.rows - Web APIs
example myrows = mytable.rows; firstrow = mytable.rows[0]; lastrow = mytable.rows.item(mytable.rows.length-1); this demonstrates how you can use both array syntax (line 2) and the htmlcollection.item() method (line 3) to obtain individual rows in the table.
HTMLTableElement.rules - Web APIs
syntax htmltableelement.rules = rules; var rules = htmltableelement.rules; parameters rules is a string with one of the following values: none no rules groups lines between groups only rows lines between rows cols lines between cols all lines between all cells example // turn on all the internal borders of a table var t = document.getelementbyid("tableid"); t.rules = "all"; specification w3c dom 2 html specification ...
HTMLTableElement.summary - Web APIs
syntax htmltableelement.summary = string; varstring = htmltableelement.summary; example htmltableelement.summary = "usage statistics"; specification w3c dom 2 html specification ...
HTMLTableElement.tFoot - Web APIs
syntax htmltablesectionelementobject = table.tfoot table.tfoot = htmltablesectionelementobject example if (table.tfoot == my_foot) { // ...
HTMLTableElement.tHead - Web APIs
example if (table.thead == my_head_el) { // ...
HTMLTableElement.width - Web APIs
example mytable.width = "75%"; ...
HTMLTableRowElement.insertCell() - Web APIs
example this example uses htmltableelement.insertrow() to append a new row to a table.
HTMLTableRowElement.rowIndex - Web APIs
example this example uses javascript to label all the row numbers in a table.
HTMLTemplateElement.content - Web APIs
syntax var documentfragment = templateelement.content example var templateelement = document.queryselector("#foo"); var documentfragment = templateelement.content.clonenode(true); specifications specification status comment html living standardthe definition of 'htmltemplateelement interface' in that specification.
HTMLTextAreaElement.labels - Web APIs
example html <label id="label1" for="test">label 1</label> <textarea id="test">some text</textarea> <label id="label2" for="test">label 2</label> javascript window.addeventlistener("domcontentloaded", function() { const textarea = document.getelementbyid("test"); for(var i = 0; i < textarea.labels.length; i++) { console.log(textarea.labels[i].textcontent); // "label 1" and "label 2" } }); specifications specification status comment html living standardthe definition of 'label...
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 ...
HTMLTrackElement.src - Web APIs
example // coming soon specifications specification status comment html living standardthe definition of 'htmltrackelement.src' in that specification.
HTMLVideoElement.getVideoPlaybackQuality() - Web APIs
example this example updates an element to indicate the total number of video frames that have elapsed so far in the playback process.
HTMLVideoElement.msHorizontalMirror - Web APIs
example var myvideo = document.getelementbyid("videotag1"); myvideo.mshorizontalmirror = true; myvideo.play(); example #2: var flip = document.queryselector('#flip'); flip.addeventlistener('click', function() { video.mshorizontalmirror = true; }); see also htmlvideoelement microsoft api extensions ...
HTMLVideoElement.msInsertVideoEffect() - Web APIs
example var ovideo1 = document.getelementbyid("video1"); ovideo1.msinsertvideoeffect("windows.media.videoeffects.videostabilization", true, null); see also htmlvideoelement microsoft api extensions ...
msSetVideoRectangle - Web APIs
example htmlvideoelement.mssetvideorectangle(left: 2, top: 0, right: 4, bottom: 4); see also htmlvideoelement microsoft api extensions ...
HTMLVideoElement.msZoom - Web APIs
example this examples gets a video object and sets the mszoom property to true.
HTMLVideoElement.videoHeight - Web APIs
example this example creates a handler for the resize event that resizes the <video> element to match the intrinsic size of its contents.
HTMLVideoElement.videoWidth - Web APIs
example this example creates a handler for the resize event that resizes the <video> element to match the intrinsic size of its contents.
HashChangeEvent.newURL - Web APIs
example window.addeventlistener('hashchange', function(event) { console.log('hash changed to ' + event.newurl); }); specifications specification status comment html living standardthe definition of 'hashchangeevent: newurl' in that specification.
HashChangeEvent.oldURL - Web APIs
example window.addeventlistener('hashchange', function(event) { console.log('hash changed from ' + event.oldurl); }); specifications specification status comment html living standardthe definition of 'hashchangeevent: oldurl' in that specification.
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('hash...
Headers() - Web APIs
WebAPIHeadersHeaders
example creating an empty headers object is simple: var myheaders = new headers(); // currently empty you could add a header to this using headers.append: myheaders.append('content-type', 'image/jpeg'); myheaders.get('content-type'); // returns 'image/jpeg' or you can add the headers you want as the headers object is created.
Headers.append() - Web APIs
WebAPIHeadersappend
example creating an empty headers object is simple: var myheaders = new headers(); // currently empty you could add a header to this using append(): myheaders.append('content-type', 'image/jpeg'); myheaders.get('content-type'); // returns 'image/jpeg' if the specified header already exists, append() will change its value to the specified value.
Headers.delete() - Web APIs
WebAPIHeadersdelete
example creating an empty headers object is simple: var myheaders = new headers(); // currently empty you could add a header to this using headers.append: myheaders.append('content-type', 'image/jpeg'); myheaders.get('content-type'); // returns 'image/jpeg' you can then delete it again: myheaders.delete('content-type'); myheaders.get('content-type'); // returns null, as it has been deleted specif...
Headers.entries() - Web APIs
WebAPIHeadersentries
example // create a test headers object var myheaders = new headers(); myheaders.append('content-type', 'text/xml'); myheaders.append('vary', 'accept-language'); // display the key/value pairs for (var pair of myheaders.entries()) { console.log(pair[0]+ ': '+ pair[1]); } the result is: content-type: text/xml vary: accept-language ...
Headers.get() - Web APIs
WebAPIHeadersget
example creating an empty headers object is simple: var myheaders = new headers(); // currently empty myheaders.get('not-set'); // returns null you could add a header to this using headers.append, then retrieve it using get(): myheaders.append('content-type', 'image/jpeg'); myheaders.get('content-type'); // returns "image/jpeg" if the header has multiple values associated with it, the byte string ...
Headers.getAll() - Web APIs
WebAPIHeadersgetAll
example creating an empty headers object is simple: var myheaders = new headers(); // currently empty you could add a header to this using headers.append, then retrieve it using getall(): myheaders.append('content-type', 'image/jpeg'); myheaders.getall('content-type'); // returns [ "image/jpeg" ] if the header has multiple values associated with it, the array will contain all the values, in the ord...
Headers.has() - Web APIs
WebAPIHeadershas
example creating an empty headers object is simple: var myheaders = new headers(); // currently empty you could add a header to this using headers.append, then test for the existence of it using has(): myheaders.append('content-type', 'image/jpeg'); myheaders.has('content-type'); // returns true myheaders.has('accept-encoding'); // returns false specifications specification status c...
Headers.keys() - Web APIs
WebAPIHeaderskeys
example // create a test headers object var myheaders = new headers(); myheaders.append('content-type', 'text/xml'); myheaders.append('vary', 'accept-language'); // display the keys for(var key of myheaders.keys()) { console.log(key); } the result is: content-type vary ...
Headers.set() - Web APIs
WebAPIHeadersset
example creating an empty headers object is simple: var myheaders = new headers(); // currently empty you could add a header to this using headers.append, then set a new value for this header using set(): myheaders.append('content-type', 'image/jpeg'); myheaders.set('content-type', 'text/html'); if the specified header does not already exist, set() will create it and set its value to the specified ...
Headers.values() - Web APIs
WebAPIHeadersvalues
example // create a test headers object var myheaders = new headers(); myheaders.append('content-type', 'text/xml'); myheaders.append('vary', 'accept-language'); // display the values for (var value of myheaders.values()) { console.log(value); } the result is: text/xml accept-language ...
History.back() - Web APIs
WebAPIHistoryback
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
WebAPIHistoryforward
syntax history.forward() examples the following examples create a button that moves forward one step in the session history.
History.length - Web APIs
WebAPIHistorylength
for example, for a page loaded in a new tab this property returns 1.
History.pushState() - Web APIs
WebAPIHistorypushState
examples this creates a new browser history state setting the state, title, and url.
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.scrollRestoration - Web APIs
examples query the current scroll restoration behavior.
HkdfParams - Web APIs
examples see the examples for subtlecrypto.derivekey().
HmacImportParams - Web APIs
examples see the examples for subtlecrypto.importkey().
HmacKeyGenParams - Web APIs
examples see the examples for subtlecrypto.generatekey().
IDBDatabase.close() - Web APIs
WebAPIIDBDatabaseclose
syntax idbdatabase.close(); example // let us open our database var dbopenrequest = window.indexeddb.open("todolist", 4); // opening a database.
IDBDatabase.createObjectStore() - Web APIs
example // let us open our database var request = window.indexeddb.open("todolist", 4); // this handler is called when a new version of the database // is created, either when one has not been created before // or when a new version number is submitted by calling // window.indexeddb.open().
IDBDatabase.deleteObjectStore() - Web APIs
example var dbname = "sampledb"; var dbversion = 2; var request = indexeddb.open(dbname, dbversion); request.onupgradeneeded = function(e) { var db = request.result; if (e.oldversion < 1) { db.createobjectstore("store1"); } if (e.oldversion < 2) { db.deleteobjectstore("store1"); db.createobjectstore("store2"); } // etc.
IDBDatabase.objectStoreNames - Web APIs
example // let us open our database var dbopenrequest = window.indexeddb.open("todolist", 4); // these two event handlers act on the database being opened successfully, or not dbopenrequest.onerror = function(event) { note.innerhtml += '<li>error loading database.</li>'; }; dbopenrequest.onsuccess = function(event) { note.innerhtml += '<li>database initialised.</li>'; // store the result of opening ...
IDBDatabase.onabort - Web APIs
}; example this example shows an idbopendbrequest.onupgradeneeded block that creates a new object store; it also includes onerror and onabort functions to handle non-success cases.
IDBDatabase.onerror - Web APIs
} example this example shows an idbopendbrequest.onupgradeneeded block that creates a new object store; it also includes onerror and onabort functions to handle non-success cases.
IDBDatabase.onversionchange - Web APIs
} example this example shows an idbopendbrequest.onupgradeneeded block that creates a new object store; it also includes onerror and onabort functions to handle non-success cases, and an onversionchange function to notify when a database structure change has occurred.
IDBDatabase.version - Web APIs
example // let us open our database var dbopenrequest = window.indexeddb.open("todolist", 4); // these two event handlers act on the database // being opened successfully, or not dbopenrequest.onerror = function(event) { note.innerhtml += '<li>error loading database.</li>'; }; dbopenrequest.onsuccess = function(event) { note.innerhtml += '<li>database initialised.</li>'; // store the result of opening the database in the db variable.
IDBEnvironment - Web APIs
example the following code creates a request for a database to be opened asychronously, after which the database is opened when the request's onsuccess handler is fired: var db; function opendb() { var dbopenrequest = window.indexeddb.open("todolist"); dbopenrequest.onsuccess = function(e) { db = dbopenrequest.result; }; } browser compatibility the compatibility table on this page is generate...
databases - Web APIs
example const promise = indexeddb.databases() promise.then(databases => { console.log(databases) }) specifications specification status comment indexed database api draftthe definition of 'databases()' in that specification.
IDBFactory.deleteDatabase() - Web APIs
example var dbdeleterequest = window.indexeddb.deletedatabase("todolist"); dbdeleterequest.onerror = function(event) { console.log("error deleting database."); }; dbdeleterequest.onsuccess = function(event) { console.log("database deleted successfully"); console.log(event.result); // should be undefined }; specifications specification status comment indexed datab...
IDBIndex.getAll() - Web APIs
WebAPIIDBIndexgetAll
example var myindex = objectstore.index('index'); var getallrequest = myindex.getall(); getallrequest.onsuccess = function() { console.log(getallrequest.result); } specification specification status comment indexed database api draftthe definition of 'getall()' in that specification.
IDBIndex.getAllKeys() - Web APIs
example var myindex = objectstore.index('index'); var getallkeysrequest = myindex.getallkeys(); getallkeysrequest.onsuccess = function() { console.log(getallkeysrequest.result); } specification specification status comment indexed database api draftthe definition of 'getall()' in that specification.
IDBIndex.isAutoLocale - Web APIs
example in the following example we open a transaction and an object store, then get the index lname from a simple contacts database.
IDBIndex.openKeyCursor() - Web APIs
example in the following example we open a transaction and an object store, then get the index lname from a simple contacts database.
IDBKeyRange.includes() - Web APIs
example var keyrangevalue = idbkeyrange.bound('a', 'k', false, false); var myresult = keyrangevalue.includes('f'); // returns true var myresult = keyrangevalue.includes('w'); // returns false polyfill the includes() method was added in the second edition of the indexed db specification.
IDBObjectStore.count() - Web APIs
example in this simple fragment we create a transaction, retrieve an object store, then count the number of records in the store using count() — when the success handler fires, we log the count value (an integer) to the console.
IDBObjectStore.getKey() - Web APIs
example let openrequest = indexeddb.open("telemetry"); openrequest.onsuccess = (event) => { let db = event.target.result; let store = db.transaction("netlogs").objectstore("netlogs"); let today = new date(); let yesterday = new date(today); yesterday.setdate(today.getdate() - 1); let request = store.getkey(idbkeyrange(yesterday, today)); request.onsuccess = (event) => { let when = eve...
IDBObjectStore.openCursor() - Web APIs
example 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: var transaction = db.transaction("name", "readonly"); var objectstore = transaction.objectstore("name"); var request = objectstore.opencursor(); request.onsuccess = function(event) { var cursor = event.target.result; if(cursor) { // cursor.
IDBObjectStore.openKeyCursor() - Web APIs
example 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: var transaction = db.transaction("name", "readonly"); var objectstore = transaction.objectstore("name"); var request = objectstore.openkeycursor(); request.onsuccess = function(event) { var cursor = event.target.result; if(cursor) { // curs...
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 }); objects...
IDBOpenDBRequest.onblocked - Web APIs
}; example var db; // let us open our database var request = indexeddb.open("todolist", 4); // these two event handlers act on the database being opened // successfully, or not request.onerror = function(event) { note.innerhtml += '<li>error loading database.</li>'; }; request.onsuccess = function(event) { note.innerhtml += '<li>database initialised.</li>'; // store the result of opening the data...
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 du...
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.
IDBVersionChangeEvent.oldVersion - Web APIs
example var dbname = "sampledb"; var dbversion = 2; var request = indexeddb.open(dbname, dbversion); request.onupgradeneeded = function(e) { var db = request.result; if (e.oldversion < 1) { db.createobjectstore("store1"); } if (e.oldversion < 2) { db.deleteobjectstore("store1"); db.createobjectstore("store2"); } // etc.
IDBVersionChangeRequest.setVersion() - Web APIs
syntax idbversionchangerequest setversion ([treatnullas=emptystring] in domstring version); example tbd parameters version the version to store in the database.
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.
IIRFilterNode - Web APIs
examples you can find a simple iir filter demo live on codepen.
IdleDeadline.didTimeout - Web APIs
example see our complete example in the article cooperative scheduling of background tasks api.
IdleDeadline - Web APIs
example see our complete example in the article cooperative scheduling of background tasks api.
ImageBitmap.close() - Web APIs
WebAPIImageBitmapclose
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"); // ...
ImageCapture() constructor - Web APIs
example the following example shows how to use a call to mediadevices.getusermedia() to retrieve the mediastreamtrack needed by the imagecapture() constructor.
ImageCapture.grabFrame() - Web APIs
example this example is extracted from this simple image capture demo.
ImageCapture.takePhoto() - Web APIs
example this example is extracted from this simple image capture demo.
ImageData.height - Web APIs
WebAPIImageDataheight
syntax imagedata.height example this example creates an imagedata object that is 200 pixels wide and 100 pixels tall.
ImageData.width - Web APIs
WebAPIImageDatawidth
syntax imagedata.width example this example creates an imagedata object that is 200 pixels wide and 100 pixels tall.
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.
InputEvent.isComposing - Web APIs
syntax var bool = event.iscomposing; example var inputevent = new inputevent('syntheticinput', false); console.log(inputevent.iscomposing); // return false specifications specification status comment document object model (dom) level 3 events specificationthe definition of 'inputevent.iscomposing' in that specification.
InstallEvent.activeWorker - Web APIs
examples self.addeventlistener('install', function(event) { var myactiveworker = event.activeworker; }); ...
enabled - Web APIs
example the following code uses the startsoftwareupdate method to unconditionally trigger a download from http://royalairways/royalpkg.xpi as long as software installation is enabled on the browser: if (installtrigger.enabled() ) { installtrigger.startsoftwareupdate ("http://royalair.com/rasoft.xpi"); } ...
InstallTrigger - Web APIs
the following is a basic example of an install trigger on a web page: xpi={'xpinstall dialog display name':'simple.xpi'}; installtrigger.install(xpi); you can also use the installtrigger object to install netscape 6/mozilla skins and language packs, and perform multiple-package installations with install.
IntersectionObserver.IntersectionObserver() - Web APIs
example this example creates a new intersection observer which calls the function myobservercallback every time the visible area of the element being observed changes by at least 10%.
IntersectionObserver.observe() - Web APIs
examples <<<...>>> specifications specification status comment intersection observerthe definition of 'intersectionobserver.observe()' in that specification.
IntersectionObserver.root - Web APIs
example this example sets the border of the intersection observer's root element to be a 2-pixel medium green line.
IntersectionObserver.rootMargin - Web APIs
this lets you, for example, adjust the bounds outward so that the target element is considered 100% visible even if a certain number of pixels worth of width or height is clipped away, or treat the target as partially hidden if an edge is too close to the edge of the root's bounding box.
IntersectionObserver.takeRecords() - Web APIs
examples <<<...>>> specifications specification status comment intersection observerthe definition of 'intersectionobserver.takerecords()' in that specification.
IntersectionObserver.thresholds - Web APIs
examples <<<...>>> specifications specification status comment intersection observerthe definition of 'intersectionobserver.thresholds' in that specification.
IntersectionObserver.unobserve() - Web APIs
example this snippet simply shows an observer being created, an element being observed, and then being unobserved.
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.
IntersectionObserverEntry.intersectionRect - Web APIs
example in this simple example, an intersection callback stores the intersection rectangle for later use by the code that draws the target elements' contents, so that only the visible area is redrawn.
IntersectionObserverEntry.time - Web APIs
example see timing element visibility with the intersection observer api for a complete example which uses the time property to track how long elements are visible to the user.
Keyboard.getLayoutMap() - Web APIs
example 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.
Keyboard - Web APIs
WebAPIKeyboard
example 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.
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.ctrlKey - Web APIs
syntax var ctrlkeypressed = instanceofkeyboardevent.ctrlkey return value a boolean example <html> <head> <title>ctrlkey example</title> <script type="text/javascript"> function showchar(e){ alert( "key pressed: " + e.key + "\n" + "ctrl key pressed: " + e.ctrlkey + "\n" ); } </script> </head> <body onkeypress="showchar(event);"> <p>press any character key, with or without holding down the ctrl key.<br /> you can also use the shift key together with the ctrl key.</p> </body> </html> specifications specification status comment document object model (dom) level 3 events specificationthe definition ...
KeyboardEvent.initKeyEvent() - Web APIs
example var event = document.createevent('keyboardevent'); // create a key event // define the event event.initkeyevent("keypress", // typearg, true, // canbubblearg, true, // cancelablearg, null, // viewarg, specifies uievent.view.
KeyboardEvent.initKeyboardEvent() - Web APIs
for example, specifying "control shift" indicates that the user was holding down the control and shift keys when pressing the key described by the event.
KeyboardEvent.isComposing - Web APIs
syntax var bool = event.iscomposing; example var kbdevent = new keyboardevent("synthetickey", false); console.log(kbdevent.iscomposing); // return false specifications specification status comment ui eventsthe definition of 'keyboardevent.prototype.iscomposing' in that specification.
KeyboardEvent.keyCode - Web APIs
example window.addeventlistener("keydown", function (event) { if (event.defaultprevented) { return; // should do nothing if the default action has been cancelled } var handled = false; if (event.key !== undefined) { // handle the event with keyboardevent.key and set handled true.
KeyboardEvent.metaKey - Web APIs
syntax var metakeypressed = instanceofkeyboardevent.metakey return value a boolean example function ismetakey(e) { alert("metakey = " + e.metakey); } <button onclick="ismetakey(event)">click me with the meta key</button> specifications specification status comment document object model (dom) level 3 events specificationthe definition of 'keyboardevent.metakey' in that specification.
KeyboardEvent.shiftKey - Web APIs
syntax var shiftkeypressed = instanceofkeyboardevent.shiftkey return value a boolean example <html> <head> <title>shiftkey example</title> <script type="text/javascript"> function showchar(e){ alert( "key pressed: " + string.fromcharcode(e.charcode) + "\n" + "charcode: " + e.charcode + "\n" + "shift key pressed: " + e.shiftkey + "\n" + "alt key pressed: " + e.altkey + "\n" ); } </script> </head> <body onkeypress="showchar(event);"> <p>press any character key, with or without holding down the shift key.<br /> you can also use the shift key together with the alt key.</p> </body> </html> specifications speci...
KeyboardEvent.which - Web APIs
example <html> <head> <title>charcode/keycode/which example</title> <script type="text/javascript"> function showkeypress(evt) { alert("onkeypress handler: \n" + "keycode property: " + evt.keycode + "\n" + "which property: " + evt.which + "\n" + "charcode property: " + evt.charcode + "\n" + "character key pressed: " + string.fromcharcode(evt.charcode) + "\n" ); } f...
KeyboardLayoutMap.get() - Web APIs
example 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.
KeyboardLayoutMap.has() - Web APIs
example specification status comment keyboard mapthe definition of 'has()' in that specification.
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.composite - Web APIs
syntax // getting var compositeenumeration = keyframeeffect.composite; // setting keyframeeffect.composite = 'accumulate'; value to understand these values, take the example of a keyframeeffect value of blur(2) working on an underlying property value of blur(3).
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.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...
KeyframeEffectOptions - Web APIs
0.5 would indicate starting halfway through the first iteration for example, and with this value set, an animation with 2 iterations would end halfway through a third iteration.
LocalMediaStream - Web APIs
the example for mediastreamtrack.stop() demonstrates how to stop a multi-track stream, which is what localmediastream.stop() used to be used for.
Location: ancestorOrigins - Web APIs
you can use location.ancestororigins in the script for a document to determine, for example, whenever the document is being framed by a site which you don’t expect it to be framed by.
Location: assign() - Web APIs
WebAPILocationassign
example // navigate to the location.reload article window.location.assign('/docs/web/api/location/reload'); specifications specification status comment html living standardthe definition of 'location.assign()' in that specification.
Location: hash - Web APIs
WebAPILocationhash
syntax string = object.hash; object.hash = string; examples <a id="myanchor" href="/docs/location.href#examples">examples</a> <script> var anchor = document.getelementbyid("myanchor"); console.log(anchor.hash); // returns '#examples' </script> specifications specification status comment html living standardthe definition of 'hash' in that specification.
Location: host - Web APIs
WebAPILocationhost
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 speci...
Location: hostname - Web APIs
WebAPILocationhostname
syntax string = object.hostname; object.hostname = string; examples // let's an <a id="myanchor" href="https://developer.mozilla.org/docs/location.hostname"> element be in the document var anchor = document.getelementbyid("myanchor"); var result = anchor.hostname; // returns:'developer.mozilla.org' specifications specification status comment html living standardthe definition of 'hostname' in that specification.
Location: href - Web APIs
WebAPILocationhref
syntax string = object.href; object.href = string; examples // lets imagine an <a id="myanchor" href="https://developer.mozilla.org/location/href"> element is in the document var anchor = document.getelementbyid("myanchor"); var result = anchor.href; // returns: 'https://developer.mozilla.org/location/href' specifications specification status comment html living standardthe definition of 'href' in that specification.
Location: origin - Web APIs
WebAPILocationorigin
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
WebAPILocationpassword
syntax string = object.password; object.password = string; examples // let's <a id="myanchor" href="https://anonymous:flabada@developer.mozilla.org/docs/location.username"> be in the document var anchor = document.getelementbyid("myanchor"); var result = anchor.password; // returns:'flabada' ...
Location: pathname - Web APIs
WebAPILocationpathname
syntax string = object.pathname; object.pathname = string; examples // let's an <a id="myanchor" href="https://developer.mozilla.org/docs/location.pathname"> element be in the document var anchor = document.getelementbyid("myanchor"); var result = anchor.pathname; // returns:'/docs/location.pathname' specifications specification status comment html living standardthe definition of 'pathname' in that specification.
Location: port - Web APIs
WebAPILocationport
syntax string = object.port; object.port = string; examples // let's an <a id="myanchor" href="https://developer.mozilla.org:443/docs/location.port"> element be in the document var anchor = document.getelementbyid("myanchor"); var result = anchor.port; // returns:'443' specifications specification status comment html living standardthe definition of 'location.port' in that specification.
Location: protocol - Web APIs
WebAPILocationprotocol
syntax string = object.protocol; object.protocol = string; examples // let's an <a id="myanchor" href="https://developer.mozilla.org/location.protocol"> element be in the document var anchor = document.getelementbyid("myanchor"); var result = anchor.protocol; // returns:'https:' specifications specification status comment html living standardthe definition of 'protocol' in that specification.
Location: replace() - Web APIs
WebAPILocationreplace
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
WebAPILocationsearch
syntax string = object.search; object.search = string; examples // let an <a id="myanchor" href="https://developer.mozilla.org/docs/location.search?q=123"> element be in the document var anchor = document.getelementbyid("myanchor"); var querystring = anchor.search; // returns:'?q=123' // further parsing: let params = new urlsearchparams(querystring); let q = parseint(params.get("q")); // is the number 123 specifications specification status comment html living standardt...
Location: toString() - Web APIs
WebAPILocationtoString
syntax string = object.tostring(); examples // let's imagine an <a id="myanchor" href="https://developer.mozilla.org/docs/location/tostring"> element is in the document var anchor = document.getelementbyid("myanchor"); var result = anchor.tostring(); // returns: 'https://developer.mozilla.org/docs/location/tostring' specifications specification status comment html living standard living standard ...
Location: username - Web APIs
WebAPILocationusername
syntax string = object.username; object.username = string; examples // let's <a id="myanchor" href="https://anonymous:flabada@developer.mozilla.org/docs/location.username"> be in the document var anchor = document.getelementbyid("myanchor"); var result = anchor.username; // returns:'anonymous' ...
Locks.mode - Web APIs
WebAPILockmode
example the following examples show how the mode property is passed in the call to lockmanager.request().
Lock - Web APIs
WebAPILock
examples the following examples show how the mode and name properties are passed in the call to lockmanager.request().
LockManager.query() - Web APIs
WebAPILockManagerquery
example const state = await navigator.locks.query(); for (const lock of state.held) { console.log(`held lock: name ${lock.name}, mode ${lock.mode}`); } for (const request of state.pending) { console.log(`requested lock: name ${request.name}, mode ${request.mode}`); } specifications specification status comment web locks apithe definition of 'query()' in that specification.
Long Tasks API - Web APIs
common examples include: long running event handlers.
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); }; }); speci...
MSCandidateWindowShow - Web APIs
example in ie11, developers can detect the opening of the ime candidate window by listening to mscandidatewindowshow event, then call getcandidatewindowclientrect() function to find out where the candidate window is and position the suggestion ui away from it: var context = document.getelementbyid("mysearchbox").msgetinputcontext(); context.addeventlistener("mscandidatewindowshow", candidatewindowshowh...
MSGestureEvent - Web APIs
for example, the distance between fingers.
MSGraphicsTrust - Web APIs
example var trustobject = media.msgraphicstruststatus; ...
MSManipulationEvent.initMSManipulationEvent() - Web APIs
example interface msmanipulationevent extends uievent { readonly currentstate: number; readonly inertiadestinationx: number; readonly inertiadestinationy: number; readonly laststate: number; initmsmanipulationevent(typearg: string, canbubblearg: boolean, cancelablearg: boolean, viewarg: window, detailarg: number, laststate: number, currentstate: number): void; readonly ms_manipul...
MSManipulationEvent - Web APIs
example interface msmanipulationevent extends uievent { readonly currentstate: number; readonly inertiadestinationx: number; readonly inertiadestinationy: number; readonly laststate: number; initmsmanipulationevent(typearg: string, canbubblearg: boolean, cancelablearg: boolean, viewarg: window, detailarg: number, laststate: number, currentstate: number): void; readonly ms_manipul...
MSSiteModeEvent - Web APIs
example interface mssitemodeevent extends event { buttonid: number; actionurl: string; } declare var mssitemodeevent: { prototype: mssitemodeevent; new(): mssitemodeevent; } see also microsoft api extensions ...
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 ...
MediaCapabilities.decodingInfo() - Web APIs
example //create media configuration to be tested const mediaconfig = { type : 'file', // 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 that 1s.
MediaCapabilities.encodingInfo() - Web APIs
example //create media configuration to be tested const mediaconfig = { type : 'record', // or 'transmission' video : { contenttype : "video/webm;codecs=vp8.0", // valid content type width : 1920, // width of the video height : 1080, // height of the video bitrate : 120000, // number of bits used to encode 1s of video framerate : 48 // number of f...
MediaCapabilitiesInfo - Web APIs
example // mediaconfiguration to be tested const mediaconfig = { type : 'file', audio : { contenttype : "audio/ogg", channels : 2, bitrate : 132700, samplerate : 5200 }, }; // check support and performance navigator.mediacapabilities.decodinginfo(mediaconfig).then(result => { // result contains the media capabilities information console.log('this configu...
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 ...
MediaDeviceInfo.label - Web APIs
the label readonlyinline property of the mediadeviceinfo interface returns a domstring, that is a label describing this device (for example "external usb webcam").
MediaDevices: devicechange event - Web APIs
bubbles no cancelable no interface event event handler ondevicechange example you can use the devicechange event in an addeventlistener method: navigator.mediadevices.addeventlistener('devicechange', function(event) { updatedevicelist(); }); or use the ondevicechange event handler property: navigator.mediadevices.ondevicechange = function(event) { updatedevicelist(); } specifications specification status media capture and streamsthe definition of 'devicechange' in that specification.
MediaDevices.enumerateDevices() - Web APIs
example here's an example of using enumeratedevices().
MediaDevices.getSupportedConstraints() - Web APIs
example this example outputs a list of the constraints supported by your browser.
MediaDevices - Web APIs
example 'use strict'; // put variables in global scope to make them available to the browser console.
MediaElementAudioSourceNode() - Web APIs
example var ac = new audiocontext(); var mediaelement = document.createelement('audio'); var options = { mediaelement : mediaelement } var myaudiosource = new mediaelementaudiosourcenode(ac, options); specifications specification status comment web audio apithe definition of 'mediaelementaudiosourcenode' in that specification.
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 speci...
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 frame...
msExtendedCode - Web APIs
example var video1 = object.getelementbyid("video1"); video1.addeventlistener('error', function () { var error = video1.error.msextendedcode; //...
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
WebAPIMediaKeys
examples //tbd specifications specification status comment encrypted media extensionsthe definition of 'mediakeys' in that specification.
MediaList - Web APIs
WebAPIMediaList
examples the following would log to the console a textual representation of the medialist of the first stylesheet applied to the current document.
MediaMetadata.MediaMetadata() - Web APIs
example 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...
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.textconte...
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 landscap...
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.onchange - Web APIs
}; example var mql = window.matchmedia('(max-width: 600px)'); mql.addeventlistener( "change", (e) => { if (e.matches) { /* the viewport is 600 pixels wide or less */ console.log('this is a narrow screen — less than 600px wide.') } else { /* the viewport is more than than 600 pixels wide */ console.log('this is a wide screen — more than 600px wide.') } }) specifications ...
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 tha...
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 ...
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 tha...
MediaRecorder() - Web APIs
example this example shows how to create a media recorder for a specified stream, whose audio bit rate is set to 128 kbit/sec and whose video bit rate is set to 2.5 mbit/sec.
MediaRecorder: dataavailable event - Web APIs
examples using addeventlistener to listen for dataavailable events: ...
MediaRecorder.isTypeSupported - Web APIs
example var types = ["video/webm", "audio/webm", "video/webm\;codecs=vp8", "video/webm\;codecs=daala", "video/webm\;codecs=h264", "audio/webm\;codecs=opus", "video/mpeg"]; for (var i in types) { console.log( "is " + types[i] + " supported?
MediaRecorder.mimeType - Web APIs
example ...
MediaRecorder.ondataavailable - Web APIs
}) example ...
MediaRecorder.onpause - Web APIs
}) example ...
MediaRecorder.onresume - Web APIs
}) example ...
MediaRecorder.onstart - Web APIs
}) example ...
MediaRecorder.onstop - Web APIs
}) example ...
MediaRecorder.onwarning - Web APIs
}) example ...
MediaRecorder.pause() - Web APIs
example ...
MediaRecorder.requestData() - Web APIs
example ...
MediaRecorder.resume() - Web APIs
example ...
MediaRecorder.state - Web APIs
example ...
MediaRecorder.stop() - Web APIs
example ...
MediaRecorder.stream - Web APIs
example if (navigator.getusermedia) { console.log('getusermedia supported.'); navigator.getusermedia ( // constraints - only audio needed for this app { audio: true }, // success callback function(stream) { var mediarecorder = new mediarecorder(stream); var mystream = mediarecorder.stream; console.log(mystream); ...
MediaRecorder.videoBitsPerSecond - Web APIs
example // tbd specifications specification status comment mediastream recordingthe definition of 'videobitspersecond' in that specification.
MediaSession.metadata - Web APIs
example 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...
MediaSession.playbackState - Web APIs
example the following example sets up event handlers, for pausing and playing: var audio = document.queryselector("#player"); audio.src = "song.mp3"; navigator.mediasession.setactionhandler('play', play); navigator.mediasession.setactionhandler('pause', pause); function play() { audio.play(); navigator.mediasession.playbackstate = "playing"; } function pause() { audio.pause(); navigator.
MediaSession.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.setPositionState() - Web APIs
example in this example, a player for a non-standard media file format, written in javascript, uses setinterval() to establish a callback which fires once per second to refresh the position information by calling setpositionstate().
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.
MediaSettingsRange - Web APIs
example the following example, extracted from chrome's image capture / photo resolution sample, uses the results from getphotocapabilities().imagewidth to modify the size of an input range.
MediaSource.MediaSource() - Web APIs
example the following snippet is taken from a simple example written by nick desaulniers (view the full demo live, or download the source for further investigation.) var video = document.queryselector('video'); var asseturl = 'frag_bunny.mp4'; // need to be specific for blink regarding codecs // ./mp4info frag_bunny.mp4 | grep codec var mimecodec = 'video/mp4; codecs="avc1.42e01e, mp4a.40.2"'; if ('mediasource' in window && mediasource.istypesupported(mimecodec)) { var mediasource = new mediasource; //console.log(mediasource.readystate); // closed video.src = url.createob...
MediaSource.activeSourceBuffers - Web APIs
example the following snippet is based on a simple example written by nick desaulniers (view the full demo live, or download the source for further investigation.) function sourceopen (_) { //console.log(this.readystate); // open var mediasource = this; var sourcebuffer = mediasource.addsourcebuffer(mimecodec); fetchab(asseturl, function (buf) { sourcebuffer.addeventlistener('updateend', fu...
MediaSource.addSourceBuffer() - Web APIs
example the following snippet is from a simple example written by nick desaulniers (view the full demo live, or download the source for further investigation.) var asseturl = 'frag_bunny.mp4'; // need to be specific for blink regarding codecs // ./mp4info frag_bunny.mp4 | grep codec var mimecodec = 'video/mp4; codecs="avc1.42e01e, mp4a.40.2"'; if ('mediasource' in window && mediasource.istypesupported...
MediaSource.duration - Web APIs
their sourcebuffer.updating property is true.) example the following snippet is based on a simple example written by nick desaulniers (view the full demo live, or download the source for further investigation.) function sourceopen (_) { //console.log(this.readystate); // open var mediasource = this; var sourcebuffer = mediasource.addsourcebuffer(mimecodec); fetchab(asseturl, function (buf) { sourcebuffer.addeventlistener('updateend', fu...
MediaSource.isTypeSupported() - Web APIs
example the following snippet is from an example written by nick desaulniers (view the full demo live, or download the source for further investigation.) var asseturl = 'frag_bunny.mp4'; // need to be specific for blink regarding codecs // ./mp4info frag_bunny.mp4 | grep codec var mimecodec = 'video/mp4; codecs="avc1.42e01e, mp4a.40.2"'; if ('mediasource' in window && mediasource.istypesupported(mimec...
MediaSource.readyState - Web APIs
example the following snippet is from a simple example written by nick desaulniers (view the full demo live, or download the source for further investigation.) if ('mediasource' in window && mediasource.istypesupported(mimecodec)) { var mediasource = new mediasource; //console.log(mediasource.readystate); // closed video.src = url.createobjecturl(mediasource); mediasource.addeventlistener('sour...
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.setLiveSeekableRange() - Web APIs
return value undefined example // tbd specifications specification status comment media source extensionsthe definition of 'setliveseekablerange()' in that specification.
MediaSource.sourceBuffers - Web APIs
example the following snippet is based on a simple example written by nick desaulniers (view the full demo live, or download the source for further investigation.) function sourceopen (_) { //console.log(this.readystate); // open var mediasource = this; var sourcebuffer = mediasource.addsourcebuffer(mimecodec); fetchab(asseturl, function (buf) { sourcebuffer.addeventlistener('updateend', function (_) { mediasource.endofstream(); console.log(mediasource.sourcebuffers); // will contain the source buffe...
active - Web APIs
example in this example, a new stream whose source is the user's local camera and microphone is requested using getusermedia().
MediaStream.addTrack() - Web APIs
return value undefined example specifications specification status comment media capture and streamsthe definition of 'addtrack()' in that specification.
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.getAudioTracks() - Web APIs
example this example gets a webcam's audio and video in a stream using getusermedia(), attaches the stream to a <video> element, then sets a timer that, upon expiring, will stop the first audio track found on the stream.
MediaStream.getTrackById() - Web APIs
example this example activates a commentary track on a video by ducking the audio level of the main audio track to 50%, then enabling the commentary track.
MediaStream.getTracks() - Web APIs
example navigator.mediadevices.getusermedia({audio: false, video: true}) .then(mediastream => { document.queryselector('video').srcobject = mediastream; // stop the stream after 5 seconds settimeout(() => { const tracks = mediastream.gettracks() tracks[0].stop() }, 5000) }) specifications specification status comment media capture and streamsthe definition of 'gettracks()' in that specification.
MediaStream.getVideoTracks() - Web APIs
example the following example, extracted from chrome's image capture / photo resolution sample, uses getvideotracks() to retrieve a track for passing to the imagecapture() constructor.
MediaStream.id - Web APIs
WebAPIMediaStreamid
syntax var id = mediastream.id; example var p = navigator.mediadevices.getusermedia({ audio: true, video: true }); p.then(function(stream) { console.log(stream.id); }) specifications specification status comment media capture and streamsthe definition of 'mediastream.id' in that specification.
MediaStream.onaddtrack - Web APIs
example this example adds a listener which, when a new track is added to the stream, appends a new item to a list of tracks; the new item shows the track's kind ("audio" or "video") and label.
MediaStream.onremovetrack - Web APIs
example this example adds a listener which, when a track is removed from the stream, logs the track that was removed.
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.
MediaStreamAudioDestinationNode.MediaStreamAudioDestinationNode() - Web APIs
example var ac = new audiocontext(); var mydestination = new mediastreamaudiodestinationnode(ac); specifications specification status comment web audio apithe definition of 'mediastreamaudiodestinationnode' in that specification.
MediaStreamAudioDestinationNode.stream - Web APIs
example specifications specification status comment web audio apithe definition of 'stream' in that specification.
MediaStreamAudioDestinationNode - Web APIs
example specification specification status comment web audio apithe definition of 'mediastreamaudiodestinationnode' in that specification.
MediaStreamAudioSourceNode() - Web APIs
examples this example uses getusermedia() to obtain access to the user's camera, then creates a new mediastreamaudiosourcenode from its mediastream.
MediaStreamAudioSourceNode.mediaStream - Web APIs
examples const audioctx = new window.audiocontext(); let options = { mediastream : stream } let source = new mediastreamaudiosourcenode(audioctx, options); console.log(source.mediastream); specifications specification status comment web audio apithe definition of 'mediastreamaudiosourcenode.mediastream' in that specification.
MediaStreamAudioSourceOptions.mediaStream - Web APIs
example specifications specification status comment web audio apithe definition of 'mediastreamaudiosourceoptions.mediastream' in that specification.
MediaStreamEvent() - Web APIs
example // s is a mediastream var event = new mediastreamevent("addstream", {"stream": s}); ...
MediaStreamEvent.stream - Web APIs
syntax var stream = event.stream; example pc.onaddstream = function( ev ) { alert("a stream (id: '" + ev.stream.id + "') has been added to this connection."); }; ...
MediaStreamEvent - Web APIs
examples pc.onaddstream = function( ev ) { alert("a stream (id: '" + ev.stream.id + "') has been added to this connection."); }; ...
MediaStreamTrack: ended event - Web APIs
examples this example sets up an event handler for the ended event, which changes an on-screen icon to indicate that the track is no longer active.
MediaStreamTrack.muted - Web APIs
example this example counts the number of tracks in an array of mediastreamtrack objects which are currently muted.
MediaStreamTrack.onended - Web APIs
examples this example sets up an event handler for the ended event which changes an on-screen icon to indicate that the track is no longer active.
MediaStreamTrack.onmute - Web APIs
example in this example, an onmute handler is established to set the content html of an element to display the "muted speaker" emoji.
MediaStreamTrack.onoverconstrained - Web APIs
example dc.onoverconstrained = function() { alert("overconstrained event detected!"); }; ...
MediaStreamTrack.onunmute - Web APIs
example this example creates an unmute event handler which changes the state of a visual indicator to display the emoji character representing a "speaker" icon.
MediaStreamTrackAudioSourceNode() - Web APIs
example this example uses getusermedia() to obtain access to the user's camera, then creates a new mediastreamaudiosourcenode from the first audio track provided by the device.
MediaStreamTrackAudioSourceOptions.mediaStreamTrack - Web APIs
example this example uses getusermedia() to obtain access to the user's camera, then creates a new mediastreamaudiosourcenode from the first audio track provided by the device.
MediaStream Recording API - Web APIs
example here, we use an html canvas as source of the mediastream, and stop recording after 9 seconds.
MediaTrackConstraints.autoGainControl - Web APIs
example see example: constraint exerciser in capabilities, constraints, and settings for an example.
MediaTrackConstraints.channelCount - Web APIs
example see example: constraint exerciser in capabilities, constraints, and settings for an example.
MediaTrackConstraints.deviceId - Web APIs
example see example: constraint exerciser in capabilities, constraints, and settings for an example.
MediaTrackConstraints.echoCancellation - Web APIs
example see example: constraint exerciser in capabilities, constraints, and settings for an example.
MediaTrackConstraints.frameRate - Web APIs
example see example: constraint exerciser in capabilities, constraints, and settings for an example.
MediaTrackConstraints.height - Web APIs
example see example: constraint exerciser in capabilities, constraints, and settings for an example.
MediaTrackConstraints.latency - Web APIs
example see example: constraint exerciser in capabilities, constraints, and settings for an example.
MediaTrackConstraints.logicalSurface - Web APIs
for example, if your app needs to know if the selected display surface is a logical one: let islogicalsurface = displaystream.getvideotracks()[0].getsettings().logicalsurface; following this code, islogicalsurface is true if the display surface contained in the stream is a logical surface; that is, one which may not be entirely onscreen, or may even be entirely offscreen.
MediaTrackConstraints.noiseSuppression - Web APIs
example see example: constraint exerciser in capabilities, constraints, and settings for an example.
MediaTrackConstraints.sampleRate - Web APIs
example see example: constraint exerciser in capabilities, constraints, and settings for an example.
MediaTrackConstraints.sampleSize - Web APIs
example see example: constraint exerciser in capabilities, constraints, and settings for an example.
MediaTrackControls.volume - Web APIs
example see example: constraint exerciser in capabilities, constraints, and settings for an example.
MediaTrackConstraints.width - Web APIs
example see example: constraint exerciser in capabilities, constraints, and settings for an example.
MediaTrackConstraints - Web APIs
for example, because rtp doesn't provide some of these values during negotiation of a webrtc connection, a track associated with a rtcpeerconnection will not include certain values, such as facingmode or groupid.
MediaTrackSettings.autoGainControl - Web APIs
example see example: constraint exerciser in capabilities, constraints, and settings for an example.
MediaTrackSettings.channelCount - Web APIs
example see example: constraint exerciser in capabilities, constraints, and settings for an example.
MediaTrackSettings.frameRate - Web APIs
example see example: constraint exerciser in capabilities, constraints, and settings for an example.
MediaTrackSettings.height - Web APIs
example see example: constraint exerciser in capabilities, constraints, and settings for an example.
MediaTrackSettings.latency - Web APIs
example see example: constraint exerciser in capabilities, constraints, and settings for an example.
MediaTrackSettings.logicalSurface - Web APIs
for example, a user agent may choose to allow the user to choose whether to share the entire document (a browser with logicalsurface value of true), or just the currently visible portion of the document (where the logicalsurface of the browser surface is false).
MediaTrackSettings.noiseSuppression - Web APIs
example see example: constraint exerciser in capabilities, constraints, and settings for an example.
MediaTrackSettings.sampleRate - Web APIs
example see example: constraint exerciser in capabilities, constraints, and settings for an example.
MediaTrackSettings.volume - Web APIs
example see example: constraint exerciser in capabilities, constraints, and settings for an example.
MediaTrackSettings.width - Web APIs
example see example: constraint exerciser in capabilities, constraints, and settings for an example.
MediaTrackSupportedConstraints.aspectRatio - Web APIs
example html content <div id="result"> </div> css content #result { font: 14px "arial", sans-serif; } javascript content let result = document.getelementbyid("result"); if (navigator.mediadevices.getsupportedconstraints().aspectratio) { result.innerhtml = "supported!"; } else { result.innerhtml = "not supported!"; } result specifications specification status comment...
MediaTrackSupportedConstraints.autoGainControl - Web APIs
example this example simply displays whether or not your browser supports the autogaincontrol constraint.
MediaTrackSupportedConstraints.channelCount - Web APIs
example html content <div id="result"> </div> css content #result { font: 14px "arial", sans-serif; } javascript content let result = document.getelementbyid("result"); if (navigator.mediadevices.getsupportedconstraints().channelcount) { result.innerhtml = "supported!"; } else { result.innerhtml = "not supported!"; } result specifications specification status comment ...
MediaTrackSupportedConstraints.cursor - Web APIs
example this method sets up the constraints object specifying the options for the call to getdisplaymedia().
MediaTrackSupportedConstraints.deviceId - Web APIs
example html content <div id="result"> </div> css content #result { font: 14px "arial", sans-serif; } javascript content let result = document.getelementbyid("result"); if (navigator.mediadevices.getsupportedconstraints().deviceid) { result.innerhtml = "supported!"; } else { result.innerhtml = "not supported!"; } result specifications specification status comment ...
MediaTrackSupportedConstraints.displaySurface - Web APIs
example this method sets up the constraints object specifying the options for the call to getdisplaymedia().
MediaTrackSupportedConstraints.echoCancellation - Web APIs
example html content <div id="result"> </div> css content #result { font: 14px "arial", sans-serif; } javascript content let result = document.getelementbyid("result"); if (navigator.mediadevices.getsupportedconstraints().echocancellation) { result.innerhtml = "supported!"; } else { result.innerhtml = "not supported!"; } result specifications specification status commen...
MediaTrackSupportedConstraints.facingMode - Web APIs
example html <div id="result"> </div> css #result { font: 14px "arial", sans-serif; } javascript let result = document.getelementbyid("result"); if (navigator.mediadevices.getsupportedconstraints().facingmode) { result.innerhtml = "supported!"; } else { result.innerhtml = "not supported!"; } result specifications specification status comment media captu...
MediaTrackSupportedConstraints.groupId - Web APIs
example html content <div id="result"> </div> css content #result { font: 14px "arial", sans-serif; } javascript content let result = document.getelementbyid("result"); if (navigator.mediadevices.getsupportedconstraints().groupid) { result.innerhtml = "supported!"; } else { result.innerhtml = "not supported!"; } result specifications specification status comment ...
MediaTrackSupportedConstraints.height - Web APIs
example html content <div id="result"> </div> css content #result { font: 14px "arial", sans-serif; } javascript content let result = document.getelementbyid("result"); if (navigator.mediadevices.getsupportedconstraints().height) { result.innerhtml = "supported!"; } else { result.innerhtml = "not supported!"; } result specifications specification status comment ...
MediaTrackSupportedConstraints.latency - Web APIs
example html content <div id="result"> </div> css content #result { font: 14px "arial", sans-serif; } javascript content let result = document.getelementbyid("result"); if (navigator.mediadevices.getsupportedconstraints().latency) { result.innerhtml = "supported!"; } else { result.innerhtml = "not supported!"; } result specifications specification status comment ...
MediaTrackSupportedConstraints.logicalSurface - Web APIs
example this method sets up the constraints object specifying the options for the call to getdisplaymedia().
MediaTrackSupportedConstraints.noiseSuppression - Web APIs
example this example simply displays whether or not your browser supports the noisesuppression constraint.
MediaTrackSupportedConstraints.sampleRate - Web APIs
example html content <div id="result"> </div> css content #result { font: 14px "arial", sans-serif; } javascript content let result = document.getelementbyid("result"); if (navigator.mediadevices.getsupportedconstraints().samplerate) { result.innerhtml = "supported!"; } else { result.innerhtml = "not supported!"; } result specifications specification status comment ...
MediaTrackSupportedConstraints.sampleSize - Web APIs
example html content <div id="result"> </div> css content #result { font: 14px "arial", sans-serif; } javascript content let result = document.getelementbyid("result"); if (navigator.mediadevices.getsupportedconstraints().samplesize) { result.innerhtml = "supported!"; } else { result.innerhtml = "not supported!"; } result specifications specification status comment ...
MediaTrackSupportedConstraints.volume - Web APIs
example html content <div id="result"> </div> css content #result { font: 14px "arial", sans-serif; } javascript content let result = document.getelementbyid("result"); if (navigator.mediadevices.getsupportedconstraints().volume) { result.innerhtml = "supported!"; } else { result.innerhtml = "not supported!"; } result ...
MediaTrackSupportedConstraints.width - Web APIs
example html content <div id="result"> </div> css content #result { font: 14px "arial", sans-serif; } javascript content let result = document.getelementbyid("result"); if (navigator.mediadevices.getsupportedconstraints().width) { result.innerhtml = "supported!"; } else { result.innerhtml = "not supported!"; } result specifications specification status comment ...
Media Capabilities API - Web APIs
examples detect audio file support and expected performance this example defines a audio configuration then checks to see if the user agent supports decoding that media configuration, and whether it will perform well in terms of smoothness and power efficiency.
Media Source API - Web APIs
we can't, for example, combine/split arraybuffers.
MerchantValidationEvent.complete() - Web APIs
example in this example, we see the client-side code needed to support merchant validation for a payment request called payrequest: payrequest.onmerchantvalidation = event => { const validationdatapromise = getvalidationdata(event.validationurl); event.complete(validationdatapromise); } function getvalidationdata(url) { /* ...retrieve the validation data from the url...
MessageChannel.port1 - Web APIs
example in the following code block, you can see a new channel being created using the messagechannel() constructor.
MessageEvent.MessageEvent() - Web APIs
example var mymessage = new messageevent('worker', { data : 'hello' }); specifications specification status comment html living standardthe definition of 'messageevent()' in that specification.
MessageEvent.data - Web APIs
WebAPIMessageEventdata
example myworker.onmessage = function(e) { result.textcontent = e.data; console.log('message received from worker'); }; specifications specification status comment html living standardthe definition of 'messageevent: data' in that specification.
MessageEvent.lastEventId - Web APIs
example myworker.onmessage = function(e) { result.textcontent = e.data; console.log('message received from worker'); console.log(e.lasteventid); }; specifications specification status comment html living standardthe definition of 'messageevent: lasteventid' in that specification.
MessageEvent.origin - Web APIs
example myworker.onmessage = function(e) { result.textcontent = e.data; console.log('message received from worker'); console.log(e.origin); }; specifications specification status comment html living standardthe definition of 'messageevent: origin' in that specification.
MessageEvent.ports - Web APIs
example onconnect = function(e) { var port = e.ports[0]; port.addeventlistener('message', function(e) { var workerresult = 'result: ' + (e.data[0] * e.data[1]); port.postmessage(workerresult); }); port.start(); // required when using addeventlistener.
MessageEvent.source - Web APIs
example myworker.onmessage = function(e) { result.textcontent = e.data; console.log('message received from worker'); console.log(e.source); }; specifications specification status comment html living standardthe definition of ' messageevent: source' in that specification.
MessageEvent - Web APIs
examples in our basic shared worker example (run shared worker), we have two html pages, each of which uses some javascript to perform a simple calculation.
MessagePort.close() - Web APIs
WebAPIMessagePortclose
example in the following code block, you can see a handlemessage handler function, run when a message is sent back to this document using eventtarget.addeventlistener.
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); }) ...
MessagePort.start() - Web APIs
WebAPIMessagePortstart
example in the following code block, you can see a handlemessage handler function, run when a message is sent back to this document using onmessage: channel.port1.onmessage = handlemessage; function handlemessage(e) { para.innerhtml = e.data; } another option would be to do this using eventtarget.addeventlistener, however, when this method is used, you need to explicitly call start() to begin the flow of messages to this document: channel.port1.addeventlistener('messa...
Metadata.modificationTime - Web APIs
example this example tries to get a particular working file at tmp/workfile.json.
Metadata.size - Web APIs
WebAPIMetadatasize
example this example checks the size of a log file and removes it if it's larger than a megabyte.
MimeType - Web APIs
WebAPIMimeType
for example, a browser's content decryption module may appear in the plugin list but support more file extensions than can be anticipated.
MimeTypeArray - Web APIs
example the following example tests whether a plugin is available for the application/pdf mime type and if so, which plugin that is.
MouseEvent.button - Web APIs
WebAPIMouseEventbutton
example html <button id="button" oncontextmenu="event.preventdefault();">click here with your mouse...</button> <p id="log"></p> javascript let button = document.queryselector('#button'); let log = document.queryselector('#log'); button.addeventlistener('mouseup', logmousebutton); function logmousebutton(e) { if (typeof e === 'object') { switch (e.button) { case 0: log.textconten...
MouseEvent.ctrlKey - Web APIs
example this example logs the ctrlkey property when you trigger a click event.
MouseEvent.initMouseEvent() - Web APIs
example html <div style="background:red; width:180px; padding:10px;"> <div id="out"></div> <input type="text"> </div> javascript document.body.onclick = function(){ e = arguments[0]; var dt = e.target,stag = dt.tagname.tolowercase(); document.getelementbyid("out").innerhtml = stag; }; var simulateclick = function(){ var evt = document.createevent("mouseevents"); evt.initmouseevent("cl...
MouseEvent.movementX - Web APIs
syntax var xshift = instanceofmouseevent.movementx; return value a number example this example logs the amount of mouse movement using movementx and movementy.
MouseEvent.movementY - Web APIs
syntax var yshift = instanceofmouseevent.movementy; return value a number example this example logs the amount of mouse movement using movementx and movementy.
MouseEvent.mozInputSource - Web APIs
this lets you, for example, determine whether a mouse event was generated by an actual mouse or by a touch event (which might affect the degree of accuracy with which you interpret the coordinates associated with the event).
MouseEvent.pageY - Web APIs
WebAPIMouseEventpageY
examples var pagey = event.pagey; specifications specification status comment css object model (cssom) view modulethe definition of 'pagey' in that specification.
MouseEvent.region - Web APIs
WebAPIMouseEventregion
example example of using the event.region combined with canvasrenderingcontext2d.addhitregion() method.
MouseEvent.relatedTarget - Web APIs
example try moving your mouse cursor into and out of the red and blue boxes.
MouseEvent.screenY - Web APIs
example this example displays your mouse's coordinates whenever you trigger the mousemove event.
MouseEvent.shiftKey - Web APIs
example this example logs the shiftkey property when you trigger a click event.
msFirstPaint - Web APIs
example the following example shows how to calculate the time that is required to request the document before the document begins to display for the user.
msGraphicsTrustStatus - Web APIs
syntax status = object.msgraphicstruststatus; example //specifies the output device id that the audio will be sent to.
msPlayToPreferredSourceUri - Web APIs
example <video src="http://www.contoso.com/videos/video.mp4" msplaytopreferredsourceuri="http://www.contoso.com/catalogid=1234" /> var video = document.createelement('video'); document.body.appendchild(video); video.src = "http://www.contoso.com/videos/video.mp4"; video.msplaytopreferredsourceuri = "http://www.contoso.com/catalogid=1234"; see also microsoft playready content acc...
msPlayToPrimary - Web APIs
example // microsoft extensions interface htmlimageelement : htmlelement { attribute boolean msplaytodisabled; attribute boolean msplaytoprimary; attribute domstring msplaytopreferredsourceuri; }; see also htmlmediaelement ...
msPlayToSource - Web APIs
example <video id="videoplayer" src="http://www.contoso.com/clip.mp4" controls autoplay /> <script type="text/javascript"> // step 1: obtain playtomanager object for app’s current view.
MutationEvent - Web APIs
cross-browser support these events are not implemented consistently across different browsers, for example: ie prior to version 9 didn't support the mutation events at all and does not implement some of them correctly in version 9 (for example, domnodeinserted) webkit doesn't support domattrmodified (see webkit bug 8191 and the workaround) "mutation name events", i.e.
MutationObserver.disconnect() - Web APIs
example this example creates an observer, then disconnects from it, leaving it available for possible reuse.
MutationObserver.takeRecords() - Web APIs
example in this example, we demonstrate how to handle any undelivered mutationrecords by calling takerecords() just before disconnecting the observer.
MutationObserver - Web APIs
mutation observer & customize resize event listener & demo https://codepen.io/webgeeker/full/yjrzgg/ example the following example was adapted from this blog post.
MutationObserverInit.characterData - Web APIs
example specifications specification status comment domthe definition of 'mutationobserverinit.characterdata' in that specification.
MutationObserverInit.characterDataOldValue - Web APIs
example specifications specification status comment domthe definition of 'mutationobserverinit.characterdataoldvalue' in that specification.
MutationObserverInit.childList - Web APIs
example specifications specification status comment domthe definition of 'mutationobserverinit.childlist' in that specification.
MutationObserverInit - Web APIs
for details and an example, see monitoring text content changes in mutationobserver.
NDEFRecord.lang - Web APIs
WebAPINDEFRecordlang
the record might be missing a language tag, for example, if the recorded information is not locale-specific.
Navigator.buildID - Web APIs
WebAPINavigatorbuildID
example console.log(window.navigator.buildid); specification not part of any public standard.
Navigator.canShare() - Web APIs
examples if(navigator.canshare(data)) { // we can use share() to share the data!
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.credentials - Web APIs
example if ('credentials' in navigator) { navigator.credentials.get({password: true}) .then(function(creds) { //do something with the credentials.
Navigator.deviceMemory - Web APIs
example const memory = navigator.devicememory console.log (`this device has at least ${memory}gib of ram.`) specifications specification status comment device memory 1the definition of 'devicememory' in that specification.
Navigator.doNotTrack - Web APIs
example console.log(navigator.donottrack); // prints "1" if dnt is enabled; "0" if the user opted-in for tracking; otherwise this is "unspecified" specifications specification status comment tracking preference expression (dnt)the definition of 'navigator.donottrack' in that specification.
Navigator.getGamepads() - Web APIs
syntax var gamepads = navigator.getgamepads(); example window.addeventlistener("gamepadconnected", function(e) { var gp = navigator.getgamepads()[e.gamepad.index]; console.log( "gamepad connected at index %d: %s.
Navigator.maxTouchPoints - Web APIs
syntax touchpoints = navigator.maxtouchpoints; example if (navigator.maxtouchpoints > 1) { // browser supports multi-touch } specifications specification status comment pointer events – level 2the definition of 'maxtouchpoints' in that specification.
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.mozIsLocallyAvailable() - Web APIs
example var available = navigator.mozislocallyavailable("my-image-file.png", true); if (available) { /* the offline resource is present */ } else { console.log("certain needed resources are not available offline"); } specifications not part of any specifications.
Navigator.oscpu - Web APIs
WebAPINavigatoroscpu
t (32-bit build) windows nt x.y; wow64 windows 32-bit windows nt x.y mac os x (ppc build) powerpc mac os x version x.y mac os x (i386/x64 build) intel mac os x or macos version x.y linux 64-bit (32-bit build) output of uname -s plus "i686 on x86_64" linux output of uname -sm x.y refers to the version of the operating system example function osinfo() { alert(window.navigator.oscpu); } osinfo(); // alerts "windows nt 6.0" for example usage notes unless your code is privileged (chrome or at least has the universalbrowserread privilege), it may get the value of the general.oscpu.override preference instead of the true platform.
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.
Navigator.productSub - Web APIs
example <script> function prodsub() { var dt = document.getelementbyid("d").childnodes[0]; dt.data = window.navigator.productsub; } </script> <button onclick="prodsub();">productsub</button> // returns: 20010725 notes on ie, this property returns undefined.
Navigator.registerContentHandler() - Web APIs
example navigator.registercontenthandler( "application/vnd.mozilla.maybe.feed", "http://www.example.tld/?foo=%s", "my feed reader" ); notes for firefox 2 and above, only the application/vnd.mozilla.maybe.feed, application/atom+xml, and application/rss+xml mime types are supported.
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
WebAPINavigatorshare
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
WebAPINavigatorvibrate
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.
NavigatorID.appVersion - Web APIs
example alert('your browser version is reported as ' + navigator.appversion); notes the window.navigator.useragent property may also contain the version number (for example "mozilla/5.0 (windows; u; win98; en-us; rv:0.9.2) gecko/20010725 netscape 6/6.1"), but you should be aware of how easy it is to change the user agent string and "spoof" other browsers, platforms, or user agents, and also how cavalier the browser vendor themselves are with these properties.
NavigatorID.platform - Web APIs
for example: "macintel", "win32", "freebsd i386", "webtv os" example console.log(navigator.platform); usage notes most browsers, including chrome, edge, and firefox 63 and later, return "win32" even if running on a 64-bit version of windows.
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.
NavigatorPlugins.javaEnabled() - Web APIs
syntax result = window.navigator.javaenabled() example if (window.navigator.javaenabled()) { // browser has java } notes the return value for this method indicates whether the preference that controls java is on or off - not whether the browser offers java support in general.
NavigatorPlugins.mimeTypes - Web APIs
example function isjavapresent() { return 'application/x-java-applet' in navigator.mimetypes; } function getjavaplugindescription() { var mimetype = navigator.mimetypes['application/x-java-applet']; if (mimetype === undefined) { // no java plugin present return undefined; } return mimetype.enabledplugin.description; } specifications specification status comment ...
NetworkInformation.downlinkMax - Web APIs
examples the following example monitors the connection using the change event and logs changes as they occur.
NetworkInformation.onchange - Web APIs
} examples // get the connection type.
Node.appendChild() - Web APIs
WebAPINodeappendChild
example // create a new paragraph element, and append it to the end of the document body let p = document.createelement("p"); document.body.appendchild(p); specifications specification status comment domthe definition of 'node.appendchild()' in that specification.
Node.baseURI - Web APIs
WebAPINodebaseURI
the base url is used to resolve relative urls when the browser needs to obtain an absolute url, for example when processing the html <img> element's src attribute or xml xlink:href attribute.
Node.cloneNode() - Web APIs
WebAPINodecloneNode
example let p = document.getelementbyid("para1") let p_prime = p.clonenode(true) notes cloning a node copies all of its attributes and their values, including intrinsic (inline) listeners.
Node.contains() - Web APIs
WebAPINodecontains
syntax node.contains( othernode ) example this function checks to see if an element is in the page's body.
Node.firstChild - Web APIs
WebAPINodefirstChild
syntax var childnode = node.firstchild; example this example demonstrates the use of firstchild and how whitespace nodes might interfere with using this property.
Node.getUserData() - Web APIs
WebAPINodegetUserData
example var d = document.setuserdata('key', 15, null); console.log(document.getuserdata('key')); // 15 specifications specification status comment document object model (dom) level 3 core specificationthe definition of 'node.getuserdata()' in that specification.
Node.hasChildNodes() - Web APIs
example let foo = document.getelementbyid('foo'); if (foo.haschildnodes()) { // do something with 'foo.childnodes' } polyfill here is one possible polyfill: ;(function(prototype) { prototype.haschildnodes = prototype.haschildnodes || function() { return !!this.firstchild; } })(node.prototype); there are various ways to determine whether the node has a child node: node.haschildnodes() node.firstchild != null (or just node.firstchild) node.childnodes && node.childnodes.length (or node.childnodes.length > 0) specifications spec...
Node.isDefaultNamespace() - Web APIs
example var xulns = "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"; var el = document.getelementsbytagnamens(xulns, 'textbox')[0]; alert(el.isdefaultnamespace(xulns)); // true specifications specification status comment domthe definition of 'node: isdefaultnamespace' in that specification.
Node.isEqualNode() - Web APIs
WebAPINodeisEqualNode
example in this example, we create three <div> blocks.
Node.isSameNode() - Web APIs
WebAPINodeisSameNode
example in this example, we create three <div> blocks.
Node.isSupported() - Web APIs
WebAPINodeisSupported
example <div id="doc"> </div> <script> // get an element and check to see if its supports the dom2 html module.
Node.lastChild - Web APIs
WebAPINodelastChild
syntax var childnode = node.lastchild; example var tr = document.getelementbyid("row1"); var corner_td = tr.lastchild; specifications specification status comment domthe definition of 'node.lastchild' in that specification.
Node.namespaceURI - Web APIs
WebAPINodenamespaceURI
syntax namespace = node.namespaceuri example in this snippet, a node is being examined for its node.localname and its namespaceuri.
Node.nodeName - Web APIs
WebAPINodenodeName
ment" documentfragment "#document-fragment" documenttype the value of documenttype.name element the value of element.tagname entity the entity name entityreference the name of entity reference notation the notation name processinginstruction the value of processinginstruction.target text "#text" example given the following markup: <div id="d1">hello world</div> <input type="text" id="t"> and the following script: var div1 = document.getelementbyid("d1"); var text_field = document.getelementbyid("t"); text_field.value = div1.nodename; in xhtml (or any other xml format), text_field's value would read "div".
Node.normalize() - Web APIs
WebAPINodenormalize
syntax element.normalize(); example let wrapper = document.createelement("div"); wrapper.appendchild( document.createtextnode("part 1 ") ); wrapper.appendchild( document.createtextnode("part 2 ") ); // at this point, wrapper.childnodes.length === 2 // wrapper.childnodes[0].textcontent === "part 1 " // wrapper.childnodes[1].textcontent === "part 2 " wrapper.normalize(); // now, wrapper.childnodes.length === 1 // wrapper.childnodes[0].textcontent === "part 1 part 2 " specifications specification status comment domthe definition of 'node: normalize' in that ...
Node.ownerDocument - Web APIs
example // given a node "p", get the top-level html // child of the document object var d = p.ownerdocument; var html = d.documentelement; specifications specification status comment domthe definition of 'node: ownerdocument' in that specification.
Node.parentElement - Web APIs
example if (node.parentelement) { node.parentelement.style.color = "red"; } specifications specification status comment domthe definition of 'parentelement' in that specification.
Node.parentNode - Web APIs
WebAPINodeparentNode
example if (node.parentnode) { // remove a node from the tree, unless // it's not in the tree already node.parentnode.removechild(node); } notes document and documentfragment nodes can never have a parent, so parentnode will always return null.
Node.prefix - Web APIs
WebAPINodeprefix
syntax string = node.prefix examples the following logs "x" to the console.
Node.removeChild() - Web APIs
WebAPINoderemoveChild
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("nest...
Node.replaceChild() - Web APIs
WebAPINodereplaceChild
example // given: // <div> // <span id="childspan">foo bar</span> // </div> // create an empty element node // without an id, any attributes, or any content var sp1 = document.createelement("span"); // give it an id attribute called 'newspan' sp1.id = "newspan"; // create some content for the new element.
Node.setUserData() - Web APIs
WebAPINodesetUserData
example var d = document.implementation.createdocument('', 'test', null); d.documentelement.setuserdata('key', 15, {handle:function (o, k, d, s, ds) {console.log(o+'::'+k+'::'+d+'::'+s+'::'+ds)}}); // 2::key::15::[object element]::[object element] console.log(d.documentelement.getuserdata('key')); // 15 var e = document.importnode(d.documentelement, true); // causes handler to be called console.log(e.ge...
Node.textContent - Web APIs
WebAPINodetextContent
examples given this html fragment: <div id="diva">this is <span>some</span> text!</div> ...
NodeFilter.acceptNode() - Web APIs
example var nodeiterator = document.createnodeiterator( // node to use as root document.getelementbyid('someid'), // only consider nodes that are text nodes (nodetype 3) nodefilter.show_text, // object containing the function to use for the acceptnode method // of the nodefilter { acceptnode: function(node) { // logic to determine whether to accept, reject or skip node // i...
NodeFilter - Web APIs
example const nodeiterator = document.createnodeiterator( // node to use as root document.getelementbyid('someid'), // only consider nodes that are text nodes (nodetype 3) nodefilter.show_text, // object containing the function to use for the acceptnode method // of the nodefilter { acceptnode: function(node) { // logic to determine whether to accept, reject or skip node //...
NodeIterator.detach() - Web APIs
syntax nodeiterator.detach(); example var nodeiterator = document.createnodeiterator( document.body, nodefilter.show_element, { acceptnode: function(node) { return nodefilter.filter_accept; } }, false ); nodeiterator.detach(); // detaches the iterator nodeiterator.nextnode(); // throws an invalid_state_err exception specifications specification status comment domthe definition of 'nodeiter...
NodeIterator.expandEntityReferences - Web APIs
syntax expand = nodeiterator.expandentityreferences; example var nodeiterator = document.createnodeiterator( document.body, nodefilter.show_element, { acceptnode: function(node) { return nodefilter.filter_accept; } }, false ); expand = nodeiterator.expandentityreferences; specifications specification status comment document object model (dom) level 2 traversal and range specificationthe definition of 'nodeiterator...
NodeIterator.filter - Web APIs
syntax nodefilter = nodeiterator.filter; example const nodeiterator = document.createnodeiterator( document.body, nodefilter.show_element, { acceptnode: function(node) { return nodefilter.filter_accept; } }, false ); nodefilter = nodeiterator.filter; specifications specification status comment domthe definition of 'nodeiterator.filter' in that specification.
NodeIterator.nextNode() - Web APIs
syntax node = nodeiterator.nextnode(); example var nodeiterator = document.createnodeiterator( document.body, nodefilter.show_element, { acceptnode: function(node) { return nodefilter.filter_accept; } }, false // this optional argument is not used any more ); currentnode = nodeiterator.nextnode(); // returns the next node specifications specification status comment domthe definition of 'nodeiterator...
NodeIterator.pointerBeforeReferenceNode - Web APIs
syntax flag = nodeiterator.pointerbeforereferencenode; example var nodeiterator = document.createnodeiterator( document.body, nodefilter.show_element, { acceptnode: function(node) { return nodefilter.filter_accept; } }, false ); flag = nodeiterator.pointerbeforereferencenode; specifications specification status comment domthe definition of 'nodeiterator.pointerbeforereferencenode' in that specification.
NodeIterator.previousNode() - Web APIs
syntax node = nodeiterator.previousnode(); example var nodeiterator = document.createnodeiterator( document.body, nodefilter.show_element, { acceptnode: function(node) { return nodefilter.filter_accept; } }, false // this optional argument is not used any more ); currentnode = nodeiterator.nextnode(); // returns the next node previousnode = nodeiterator.previousnode(); // same result, since we backtracked to the previous node s...
NodeIterator.referenceNode - Web APIs
syntax node = nodeiterator.referencenode; example var nodeiterator = document.createnodeiterator( document.body, nodefilter.show_element, { acceptnode: function(node) { return nodefilter.filter_accept; } }, false ); node = nodeiterator.referencenode; specifications specification status comment domthe definition of 'nodeiterator.referencenode' in that specification.
NodeIterator.root - Web APIs
WebAPINodeIteratorroot
syntax root = nodeiterator.root; example var nodeiterator = document.createnodeiterator( document.body, nodefilter.show_element, { acceptnode: function(node) { return nodefilter.filter_accept; } }, false ); root = nodeiterator.root; // document.body in this case specifications specification status comment domthe definition of 'nodeiterator.root' in that specification.
NodeIterator.whatToShow - Web APIs
example var nodeiterator = document.createnodeiterator( document.body, nodefilter.show_element + nodefilter.show_comment + nodefilter.show_text, { acceptnode: function(node) { return nodefilter.filter_accept; } }, false ); if( (nodeiterator.whattoshow == nodefilter.show_all) || (nodeiterator.whattoshow % (nodefilter.show_comment*2)) >= nodefilter.show_comment) { // nodeiterator w...
NodeList.entries() - Web APIs
WebAPINodeListentries
example var node = document.createelement("div"); var kid1 = document.createelement("p"); var kid2 = document.createtextnode("hey"); var kid3 = document.createelement("span"); node.appendchild(kid1); node.appendchild(kid2); node.appendchild(kid3); var list = node.childnodes; // using for..of for(var entry of list.entries()) { console.log(entry); } results in: array [ 0, <p> ] array [ 1, #text "hey" ] array [ 2, <span> ] ...
NodeList.item() - Web APIs
WebAPINodeListitem
alternate syntax javascript also offers an array-like bracketed syntax for obtaining an item from a nodelist by index: nodeitem = nodelist[index] example var tables = document.getelementsbytagname("table"); var firsttable = tables.item(1); // or simply tables[1] - returns the second table in the dom specifications specification status comment domthe definition of 'nodelist: item' in that specification.
NodeList.keys() - Web APIs
WebAPINodeListkeys
example var node = document.createelement("div"); var kid1 = document.createelement("p"); var kid2 = document.createtextnode("hey"); var kid3 = document.createelement("span"); node.appendchild(kid1); node.appendchild(kid2); node.appendchild(kid3); var list = node.childnodes; // using for..of for(var key of list.keys()) { console.log(key); } the result is: 0 1 2 ...
NodeList.values() - Web APIs
WebAPINodeListvalues
example var node = document.createelement("div"); var kid1 = document.createelement("p"); var kid2 = document.createtextnode("hey"); var kid3 = document.createelement("span"); node.appendchild(kid1); node.appendchild(kid2); node.appendchild(kid3); var list = node.childnodes; // using for..of for(var value of list.values()) { console.log(value); } the result is: <p> #text "hey" <span> ...
NonDocumentTypeChildNode.nextElementSibling - Web APIs
syntax var nextnode = elementnodereference.nextelementsibling; example <div id="div-01">here is div-01</div> <div id="div-02">here is div-02</div> <script type="text/javascript"> var el = document.getelementbyid('div-01').nextelementsibling; console.log('siblings of div-01:'); while (el) { console.log(el.nodename); el = el.nextelementsibling; } </script> this example outputs the following into the console when it loads: siblings of div-01: div script polyfill for internet explorer 8 this property is unsupported prior to ie9, so the following snippet can...
NonDocumentTypeChildNode.previousElementSibling - Web APIs
syntax prevnode = elementnodereference.previouselementsibling; example <div id="div-01">here is div-01</div> <div id="div-02">here is div-02</div> <li>this is a list item</li> <li>this is another list item</li> <div id="div-03">here is div-03</div> <script> let el = document.getelementbyid('div-03').previouselementsibling; document.write('<p>siblings of div-03</p><ol>'); while (el) { document.write('<li>' + el.nodename + '</li>'); el = el.previouselementsibling; } document.write('</ol>'); </script> this example outputs the following into the page whe...
Notification.Notification() - Web APIs
example in our emogotchi demo (see source code), we run a spawnnotification() function when we want to trigger a notification.
Notification.body - Web APIs
WebAPINotificationbody
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
WebAPINotificationdata
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
WebAPINotificationdir
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
WebAPINotificationicon
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
WebAPINotificationlang
examples the following snippet fires a notification; a simple options object is created, then the notification is fired using the notification() constructor.
Notification.maxActions - Web APIs
examples the following snippet logs the maximum number of supported actions.
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 sta...
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.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.tag - Web APIs
WebAPINotificationtag
examples our using the notifications api article has a good example of tag usage.
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.
NotificationAction - Web APIs
example notifications can fire notificationclick events on the serviceworkerglobalscope.
NotificationEvent.NotificationEvent() - Web APIs
example var n = new notification('hello'); var init = { notification: n }; var mynotificationevent = new notificationevent(type, init); specifications specification status comment notifications apithe definition of 'notificationevent() constructor' in that specification.
NotificationEvent.action - Web APIs
example self.registration.shownotification("new articles available", { actions: [{action: "get", title: "get now."}] }); self.addeventlistener('notificationclick', function(event) { event.notification.close(); if (event.action === 'get') { synchronizereader(); } else { clients.openwindow("/reader"); } }, false); specifications specification status comment ...
NotificationEvent.notification - Web APIs
example self.addeventlistener('notificationclick', function(event) { console.log('on notification click'); // data can be attached to the notification so that you // can process it in the notificationclick handler.
NotificationEvent - Web APIs
example 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 = cl...
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_fbo_render_mipmap - Web APIs
examples see the sample code in the khronos 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 defi...
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.bindVertexArrayOES() - Web APIs
examples var ext = gl.getextension('oes_vertex_array_object'); var vao = ext.createvertexarrayoes(); ext.bindvertexarrayoes(vao); // ...
OES_vertex_array_object.createVertexArrayOES() - Web APIs
examples var ext = gl.getextension('oes_vertex_array_object'); var vao = ext.createvertexarrayoes(); ext.bindvertexarrayoes(vao); // ...
OES_vertex_array_object.deleteVertexArrayOES() - Web APIs
examples var ext = gl.getextension('oes_vertex_array_object'); var vao = ext.createvertexarrayoes(); ext.bindvertexarrayoes(vao); // ...
OES_vertex_array_object.isVertexArrayOES() - Web APIs
examples var ext = gl.getextension('oes_vertex_array_object'); var vao = ext.createvertexarrayoes(); ext.bindvertexarrayoes(vao); // ...
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); // ...
OVR_multiview2.framebufferTextureMultiviewOVR() - Web APIs
examples ext.framebuffertexturemultiviewovr(gl.draw_framebuffer, gl.color_attachment0, colortex, 0, 0, 2); specifications specification status ovr_multiview2 community approved ...
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 offlineaudiocon...
OfflineAudioContext.oncomplete - Web APIs
} example 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.
OffscreenCanvas() - Web APIs
examples this example creates a new offscreen canvas using the offscreencanvas() constructor.
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.transferToImageBitmap() - Web APIs
examples var offscreen = new offscreencanvas(256, 256); var gl = offscreen.getcontext("webgl"); // ...
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.populateMatrix() - Web APIs
parameters targetmatrix tbd return value undefined example // tbd specifications specification status comment orientation sensorthe definition of 'populatematrix' in that specification.
OrientationSensor.quaternion - Web APIs
example // tbd specifications specification status comment orientation sensorthe definition of 'quaternion' in that specification.
OscillatorNode.setPeriodicWave() - Web APIs
returns undefined example the following example illustrates simple usage of createperiodicwave(), recreating a sine wave from a periodic wave.
PageTransitionEvent - Web APIs
example html <!doctype html> <html> <body> </body> </html> javascript window.addeventlistener('pageshow', myfunction); function myfunction(event) { if (event.persisted) { alert("the page was cached by the browser"); } else { alert("the page was not cached by the browser"); } } specifications specification status comment html living standardthe definition...
PaintWorklet.registerPaint - Web APIs
examples the following shows registering an example worklet module.
PannerNode.PannerNode() - Web APIs
example var ctx = new audiocontext(); var options = { positionx : 1, maxdistance: 5000 } var mypanner = new pannernode(ctx, options); specifications specification status comment web audio apithe definition of 'pannernode()' in that specification.
PannerNode.coneInnerAngle - Web APIs
example in this example, we'll demonstrate how changing the orientation parameters of a pannernode in combination with coneinnerangle and coneouterangle affects volume.
PannerNode.coneOuterAngle - Web APIs
example in this example, we'll demonstrate how changing the orientation parameters of a pannernode in combination with coneinnerangle and coneouterangle affects volume.
PannerNode.coneOuterGain - Web APIs
example in this example, we'll demonstrate how changing the orientation parameters of a pannernode in combination with coneinnerangle and coneouterangle affects volume.
PannerNode.orientationX - Web APIs
example in this example, we'll demonstrate how changing the orientation parameters of a pannernode in combination with coneinnerangle and coneouterangle affects volume.
PannerNode.orientationY - Web APIs
example in this example, we'll demonstrate how changing the orientation parameters of a pannernode in combination with coneinnerangle and coneouterangle affects volume.
PannerNode.orientationZ - Web APIs
example in this example, we'll demonstrate how changing the orientation parameters of a pannernode in combination with coneinnerangle and coneouterangle affects volume.
PannerNode.positionX - Web APIs
example the following example starts an oscillator, and pans it to the left after 1 second, to the right after 2 seconds, and back to the center after 3 seconds.
PannerNode.positionY - Web APIs
example the following example starts an oscillator and pans it above the listener after 1 second, below the listener after 2 seconds, and back to the center after 3 seconds.
PannerNode.positionZ - Web APIs
example the following example starts an oscillator and moves it in front of the listener after 1 second, behind the listener after 2 seconds, and back to the listener's position after 3 seconds.
PannerNode.refDistance - Web APIs
example this example demonstrates how different values of refdistance affect how the volume of a sound decays as it moves away from the listener.
PannerNode.rolloffFactor - Web APIs
example this example demonstrates how different rollofffactor values affect how the volume of the test tone decreases with increasing distance from the listener: const context = new audiocontext(); // all our test tones will last this many seconds const note_length = 4; // this is how far we'll move the sound const z_distance = 20; // this function creates a graph for the test tone with a given rollof...
ParentNode.append() - Web APIs
WebAPIParentNodeappend
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.childElementCount - Web APIs
example var foo = document.getelementbyid('foo'); if (foo.childelementcount > 0) { // do something } polyfill for ie8 & ie9 & safari this property is completely unsupported prior to ie9.
ParentNode.children - Web APIs
example const foo = document.getelementbyid('foo'); for (let i = 0; i < foo.children.length; i++) { console.log(foo.children[i].tagname); } polyfill // overwrites native 'children' prototype.
ParentNode.firstElementChild - Web APIs
syntax var element = node.firstelementchild; example <ul id="foo"> <li>first (1)</li> <li>second (2)</li> <li>third (3)</li> </ul> <script> var foo = document.getelementbyid('foo'); // yields: first (1) console.log(foo.firstelementchild.textcontent); </script> polyfill for ie8, ie9 and safari // overwrites native 'firstelementchild' prototype.
ParentNode.lastElementChild - Web APIs
syntax const element = node.lastelementchild example <ul id="foo"> <li>first (1)</li> <li>second (2)</li> <li>third (3)</li> </ul> <script> const foo = document.getelementbyid('foo'); console.log(foo.lastelementchild.textcontent); // logs: third (3) </script> polyfill the code below adds support of lastelementchild() to document and documentfragment in internet explorer and safari.
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.textcont...
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.idName - Web APIs
example // tbd specifications specification status comment credential management level 1 working draft initial definition.
PasswordCredential.passwordName - Web APIs
example // tbd specifications specification status comment credential management level 1 working draft initial definition.
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.addPath() - Web APIs
WebAPIPath2DaddPath
examples adding a path to an existing path this example adds one path to another.
PayerErrors.email - Web APIs
WebAPIPayerErrorsemail
example function validatepayment(response) { const correctionpromises let paymenterrors = {}; let payererrors = {}; // check payer details if (!validemail(response.payeremail)) { payererrors.email = "please make sure you enter a valid email address." } if (!validname(response.payername)) { payererrors.email = "please enter a valid name, using only <appropriate characters>." } ...
PayerErrors.name - Web APIs
WebAPIPayerErrorsname
example function validatepayment(response) { const correctionpromises let paymenterrors = {}; let payererrors = {}; // check payer details if (!validemail(response.payeremail)) { payererrors.email = "please make sure you enter a valid email address." } if (!validname(response.payername)) { payererrors.email = "please enter a valid name, using only <appropriate characters>." } ...
PayerErrors.phone - Web APIs
WebAPIPayerErrorsphone
example function validatepayment(response) { const correctionpromises let paymenterrors = {}; let payererrors = {}; // check payer details if (!validemail(response.payeremail)) { payererrors.email = "please make sure you enter a valid email address." } if (!validname(response.payername)) { payererrors.email = "please enter a valid name, using only <appropriate characters>." } ...
PayerErrors - Web APIs
example specifications specification status comment payment request apithe definition of 'payererrors' in that specification.
PaymentAddress.addressLine - Web APIs
for example, the addressline array for the mozilla space in london would have the following entries: example showing addressline entries for an address in london index addressline[] value 0 metal box factory 1 suite 441, 4th floor 2 30 great guildford street these, combined with additional values for other properties of the paymentaddress, would re...
PaymentAddress.country - Web APIs
some examples of valid country values: "us", "gb", "cn", or "jp".
PaymentAddress.postalCode - Web APIs
the postalcode read-only property of the paymentaddress interface returns a string containing a code used by a jurisdiction for mail routing, for example, the zip code in the united states or the postal index number (pin code) in india.
PaymentAddress.region - Web APIs
for example, this may be a state, province, oblast, or prefecture.
PaymentCurrencyAmount.currency - Web APIs
example this example represents the price of $42.95 in us dollars.
PaymentCurrencyAmount.currencySystem - Web APIs
for example, the default is urn:iso:std:iso:4217, which specifies that the standard used is iso 4217.
PaymentDetailsBase - Web APIs
for example, you can use one to adjust the total payment amount based on the selected payment method ("5% cash discount!").
PaymentDetailsUpdate - Web APIs
for example, you can use one to adjust the total payment amount based on the selected payment method ("5% cash discount!").
PaymentMethodChangeEvent - Web APIs
for example, if methodname is basic-card, indicating that the basic card payment method is being used for validation, the methoddetails field must be a basiccardchangedetails object.
PaymentMethodChangeEvent.methodDetails - Web APIs
example this example uses the paymentmethodchange event to watch for changes to the payment method selected for apple pay, in order to compute a discount if the user chooses to use a visa card as their payment method.
PaymentMethodChangeEvent.methodName - Web APIs
example this example uses the paymentmethodchange event to watch for changes to the payment method selected for apple pay, in order to compute a discount if the user chooses to use a visa card as their payment method.
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.canMakePayment() - Web APIs
parameters none examples in the following example, is excerpted from a demo that asynchronously builds a paymentrequest object for both apple pay and credit cards.
PaymentRequest.prototype.id - Web APIs
WebAPIPaymentRequestid
example this example shows how to give a paymentrequest instance a custom id.
PaymentRequest: merchantvalidation event - Web APIs
bubbles no cancelable no interface merchantvalidationevent event handler property onmerchantvalidation examples in this example, an event handler is established for the merchantvalidation event.
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.onshippingaddresschange - Web APIs
}; examples the shippingaddresschange event is triggered by a user-agent controlled interaction.
PaymentRequest.onshippingoptionchange - Web APIs
}; examples the shippingoptionchange event is triggered by a user-agent controlled interaction.
PaymentRequest.shippingOption - Web APIs
syntax // returns the id of the selected paymentshippingoption var shippingoption = request.shippingoption; example in the example below, the paymentrequest.onshippingoptionchange and the paymentrequest.onshippingaoptionchange events are dispatched.
PaymentRequest: shippingaddresschange event - Web APIs
example in this example, a handler for the shippingaddresschange event is set up to validate that the address meets requirements set by the web application.
PaymentRequestUpdateEvent.updateWith() - Web APIs
for example, you can use one to adjust the total payment amount based on the selected payment method ("5% cash discount!").
PaymentResponse.complete() - Web APIs
examples the following example sends payment information to a secure server using the fetch api.
PaymentResponse.details - Web APIs
syntax var detailsobject = paymentresponse.details; example the following example extracts the details from the paymentresponse object to the promise returned from paymentrequest.show().
PaymentResponse.methodName - Web APIs
example the following example extracts the method name from the paymentresponse object to the promise returned from paymentrequest.show().
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.shippingOption - Web APIs
syntax var shippingoption = paymentrequest.shippingoption; example in the example below, the paymentrequest.onshippingaoptionchange event is called.
Payment Request API - Web APIs
interfaces paymentaddress an object that contains address information; used for billing and shipping addresses, for example.
Pbkdf2Params - Web APIs
examples see the examples for subtlecrypto.derivekey().
performance.clearMarks() - Web APIs
return value void example the following example shows both uses of the clearmarks() method.
performance.clearMeasures() - Web APIs
return value void example the following example shows both uses of the clearmeasures() method.
performance.clearResourceTimings() - Web APIs
example function load_resource() { var image = new image(); image.src = "https://developer.mozilla.org/static/img/opengraph-logo.png"; } function clear_performance_timings() { if (performance === undefined) { log("browser does not support web performance"); return; } // create a resource timing performance entry by loading an image load_resource(); var supported = typeof performan...
performance.mark() - Web APIs
WebAPIPerformancemark
return value void example the following example shows how to use mark() to create and retrieve performancemark entries.
Performance.onresourcetimingbufferfull - Web APIs
examples the following example sets a callback function on the onresourcetimingbufferfull property.
Performance: resourcetimingbufferfull event - Web APIs
bubbles yes cancelable yes interface event event handler property onresourcetimingbufferfull examples the following example sets a callback function on the onresourcetimingbufferfull property.
performance.setResourceTimingBufferSize() - Web APIs
example function setresourcetimingbuffersize(maxsize) { if (performance === undefined) { log("browser does not support web performance"); return; } var supported = typeof performance.setresourcetimingbuffersize == "function"; if (supported) { log("...
performance.toJSON() - Web APIs
example var js; js = window.performance.tojson(); console.log("json = " + json.stringify(js)); specifications specification status comment high resolution time level 2the definition of 'tojson() serializer' in that specification.
PerformanceEntry.duration - Web APIs
example the following example shows the use of the duration property.
PerformanceEntry.name - Web APIs
example the following example shows the use of the name property.
PerformanceEntry.startTime - Web APIs
example the following example shows the use of the starttime property.
PerformanceEntry.toJSON() - Web APIs
example the following example shows the use of the tojson() method.
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 eve...
PerformanceFrameTiming - Web APIs
example see the example in using the frame timing api.
PerformanceMark - Web APIs
example see the example in using the user timing api.
PerformanceMeasure - Web APIs
example see the example in using the user timing api.
PerformanceNavigationTiming.domComplete - Web APIs
example the following example illustrates this property's usage.
PerformanceNavigationTiming.domContentLoadedEventEnd - Web APIs
example the following example illustrates this property's usage.
PerformanceNavigationTiming.domContentLoadedEventStart - Web APIs
example the following example illustrates this property's usage.
PerformanceNavigationTiming.domInteractive - Web APIs
example the following example illustrates this property's usage.
PerformanceNavigationTiming.loadEventEnd - Web APIs
example the following example illustrates this property's usage.
PerformanceNavigationTiming.loadEventStart - Web APIs
example the following example illustrates this property's usage.
PerformanceNavigationTiming.redirectCount - Web APIs
example the following example illustrates this property's usage.
PerformanceNavigationTiming.toJSON() - Web APIs
example // get a resource performance entry var perfentries = performance.getentriesbytype("navigation"); var entry = perfentries[0]; // get the json and log it var json = entry.tojson(); var s = json.stringify(json); console.log("performancenavigationtiming.tojson() = " + s); specifications specification status comment navigation timing level 2the definition of 'tojson()' in...
PerformanceNavigationTiming.type - Web APIs
example the following example illustrates this property's usage.
PerformanceNavigationTiming.unloadEventEnd - Web APIs
example the following example illustrates this property's usage.
PerformanceNavigationTiming.unloadEventStart - Web APIs
example the following example illustrates this property's usage.
PerformanceNavigationTiming - Web APIs
for example, this interface can be used to determine how much time it takes to load or unload a document.
PerformanceObserver() - Web APIs
example var observer = new performanceobserver(function(list, obj) { var entries = list.getentries(); for (var i=0; i < entries.length; i++) { // process "mark" and "frame" events } }); observer.observe({entrytypes: ["mark", "frame"]}); function perf_observer(list, observer) { // process the "measure" event } var observer2 = new performanceobserver(perf_observer); observer2.observe({entryty...
PeformanceObserver.disconnect() - Web APIs
syntax performanceobserver.disconnect(); example var observer = new performanceobserver(function(list, obj) { var entries = list.getentries(); for (var i=0; i < entries.length; i++) { // process "mark" and "frame" events } }); observer.observe({entrytypes: ["mark", "frame"]}); function perf_observer(list, observer) { // process the "measure" event // ...
PerformanceObserver.observe() - Web APIs
examples this example creates and configures two performanceobservers; one watches for "mark" and "frame" events, and the other watches for "measure" events.
PerformanceObserver.takeRecords() - Web APIs
example var observer = new performanceobserver(function(list, obj) { var entries = list.getentries(); for (var i=0; i < entries.length; i++) { // process "mark" and "frame" events } }); observer.observe({entrytypes: ["mark", "frame"]}); var records = observer.takerecords(); console.log(records[0].name); console.log(records[0].starttime); console.log(records[0].duration); specifications specification status comment performance timeline level 2the definition of ...
PerformanceObserver - Web APIs
example function perf_observer(list, observer) { // process the "measure" event } var observer2 = new performanceobserver(perf_observer); observer2.observe({entrytypes: ["measure"]}); specifications specification status comment performance timeline level 2the definition of 'performanceobserver' in that specification.
PerformanceObserverEntryList.getEntriesByName() - Web APIs
example function print_perf_entry(pe) { console.log("name: " + pe.name + "; entrytype: " + pe.entrytype + "; starttime: " + pe.starttime + "; duration: " + pe.duration); } // create observer for all performance event types var observe_all = new performanceobserver(function(list, obs) { var perfentries; // print all entries perfentries = li...
PerformanceObserverEntryList.getEntriesByType() - Web APIs
example function print_perf_entry(pe) { console.log("name: " + pe.name + "; entrytype: " + pe.entrytype + "; starttime: " + pe.starttime + "; duration: " + pe.duration); } // create observer for all performance event types var observe_all = new performanceobserver(function(list, obs) { var perfentries; // print all entries perfentries = li...
PerformanceObserverEntryList - Web APIs
example // create observer for all performance event types // list is of type performanceobserveentrylist var observe_all = new performanceobserver(function(list, obs) { var perfentries = list.getentries(); for (var i = 0; i < perfentries.length; i++) { print_perf_entry(perfentries[i]); // do something with it } }) specifications specification status comment ...
PerformancePaintTiming - Web APIs
example function showpainttimings() { if (window.performance) { let performance = window.performance; let performanceentries = performance.getentriesbytype('paint'); performanceentries.foreach( (performanceentry, i, entries) => { console.log("the time to " + performanceentry.name + " was " + performanceentry.starttime + " milliseconds."); }); } else { console.log('performan...
PerformanceResourceTiming.connectEnd - Web APIs
example in the following example, the value of the *start and *end properties of all "resource" type events are logged.
PerformanceResourceTiming.connectStart - Web APIs
example in the following example, the value of the *start and *end properties of all "resource" type events are logged.
PerformanceResourceTiming.decodedBodySize - Web APIs
example the following example, the value of the size properties of all "resource" type events are logged.
PerformanceResourceTiming.domainLookupEnd - Web APIs
example in the following example, the value of the *start and *end properties of all "resource" type events are logged.
PerformanceResourceTiming.domainLookupStart - Web APIs
example in the following example, the value of the *start and *end properties of all "resource" type events are logged.
PerformanceResourceTiming.encodedBodySize - Web APIs
example the following example, the value of the size properties of all "resource" type events are logged.
PerformanceResourceTiming.fetchStart - Web APIs
example in the following example, the value of the *start and *end properties of all "resource" type events are logged.
PerformanceResourceTiming.initiatorType - Web APIs
example function print_performanceentries() { // use getentriesbytype() to just get the "resource" events var p = performance.getentriesbytype("resource"); for (var i=0; i < p.length; i++) { print_initiatortype(p[i]); } } function print_initiatortype(perfentry) { // print this performance entry object's initiatortype value var value = "initiatortype" in perfentry; if (value) consol...
PerformanceResourceTiming.nextHopProtocol - Web APIs
example the following example uses the nexthopprotocol property.
PerformanceResourceTiming.redirectEnd - Web APIs
example in the following example, the value of the *start and *end properties of all "resource" type events are logged.
PerformanceResourceTiming.redirectStart - Web APIs
example in the following example, the value of the *start and *end properties of all "resource" type events are logged.
PerformanceResourceTiming.requestStart - Web APIs
syntax resource.requeststart; return value a domhighrestimestamp representing the time immediately before the browser starts requesting the resource from the server example in the following example, the value of the *start and *end properties of all "resource" type events are logged.
PerformanceResourceTiming.responseEnd - Web APIs
example in the following example, the value of the *start and *end properties of all "resource" type events are logged.
PerformanceResourceTiming.responseStart - Web APIs
example in the following example, the value of the *start and *end properties of all "resource" type events are logged.
PerformanceResourceTiming.secureConnectionStart - Web APIs
example in the following example, the value of the *start and *end properties of all "resource" type events are logged.
PerformanceResourceTiming.toJSON() - Web APIs
example // get a resource performance entry var perfentries = performance.getentriesbytype("resource"); var entry = perfentries[0]; // get the json and log it var json = entry.tojson(); var s = json.stringify(json); console.log("performanceentry.tojson = " + s); specifications specification status comment resource timing level 2the definition of 'tojson' in that specification...
PerformanceResourceTiming.transferSize - Web APIs
example the following example, the value of size properties of all "resource" type events are logged.
PerformanceResourceTiming.workerStart - Web APIs
example in the following example, the value of the *start and *end properties of all "resource" type events are logged.
PerformanceServerTiming - Web APIs
example given a server that sends the server-timing header, for example a node.js server like this: const http = require('http'); function requesthandler(request, response) { const headers = { 'server-timing': ` cache;desc="cache read";dur=23.2, db;dur=53, app;dur=47.2 `.replace(/\n/g, '') }; response.writehead(200, headers); response.write(''); return settimeout(_ ...
Performance API - Web APIs
however, if the browser is unable to provide a time value accurate to 5 microseconds (because, for example, due to hardware or software constraints), the browser can represent the value as a time in milliseconds accurate to a millisecond.
Performance Timeline - Web APIs
entrytype the type of performance metric (for example, "mark").
PeriodicWave.PeriodicWave() - Web APIs
example var real = new float32array(2); var imag = new float32array(2); var ac = new audiocontext(); real[0] = 0; imag[0] = 0; real[1] = 1; imag[1] = 0; var options = { real : real, imag : imag, disablenormalization : false } var wave = new periodicwave(ac, options); specifications specification status comment web audio apithe definition of 'periodicwave' in that speci...
PeriodicWave - Web APIs
example the following example illustrates simple usage of createperiodicwave(), to create a periodicwave object containing a simple sine wave.
PermissionStatus.onchange - Web APIs
}) example navigator.permissions.query({name:'geolocation'}).then(function(permissionstatus) { console.log('geolocation permission state is ', permissionstatus.state); permissionstatus.onchange = function() { console.log('geolocation permission state has changed to ', this.state); }; }); specification specification status comment permissionsthe definition of 'onchange' in that specification.
PermissionStatus.state - Web APIs
syntax var permission = permissionstatus.state; example navigator.permissions.query({name:'geolocation'}).then(function(permissionstatus) { console.log('geolocation permission state is ', permissionstatus.state); permissionstatus.onchange = function() { console.log('geolocation permission status has changed to ', this.state); }; }); specification specification status comment permissionsthe definition of 'state' in that specification.
PermissionStatus - Web APIs
example navigator.permissions.query({name:'geolocation'}).then(function(permissionstatus) { console.log('geolocation permission status is ', permissionstatus.state); permissionstatus.onchange = function() { console.log('geolocation permission status has changed to ', this.state); }; }); specification specification status comment permissionsthe definition of 'permissio...
Permissions.revoke() - Web APIs
example this function can be used by an app to request that its own geolocation api permission be revoked.
Permissions - Web APIs
example navigator.permissions.query({name:'geolocation'}).then(function(result) { if (result.state === 'granted') { showlocalnewswithgeolocation(); } else if (result.state === 'prompt') { showbuttontoenablelocalnews(); } // don't do anything if the permission was denied.
PointerEvent.PointerEvent() - Web APIs
example var moveevent = new pointerevent("pointermove"); var downevent = new pointerevent("pointerdown", {pointerid: 1, bubbles: true, cancelable: true, pointertype: "touch", width: 100, height: 100, isprimary: true }); ...
PointerEvent.pointerId - Web APIs
example the following code snippet compares a previously saved pointerid with the one of the pointerdown event that was just fired.
PointerEvent.pointerType - Web APIs
example this example illustrates using the value of the pointertype property to call the appropriate pointer type processing function.
PointerEvent.pressure - Web APIs
example in this snippet, when a pointerdown event is fired, different functions are called depending on the value of the event's pressure property.
PointerEvent.tangentialPressure - Web APIs
example in this snippet, when a pointerdown event is fired, different functions are called depending on the value of the event's tangentialpressure property.
PointerEvent.tiltX - Web APIs
example this example illustrates simple accessing of the tiltx and tilty properties.
PointerEvent.tiltY - Web APIs
example this example illustrates simple accessing of the tiltx and tilty properties.
PointerEvent.twist - Web APIs
example when a pointerdown event is fired, different functions are called depending on the value of the event's twist property.
PointerEvent.width - Web APIs
example this example illustrates using the pointerevent interface's width and height properties to calculate the contact area.
PositionOptions.enableHighAccuracy - Web APIs
note that this can result in slower response times or increased power consumption (with a gps chip on a mobile device for example).
PositionOptions - Web APIs
note that this can result in slower response times or increased power consumption (with a gps chip on a mobile device for example).
ProcessingInstruction - Web APIs
user-defined processing instructions cannot begin with "xml", as xml-prefixed processing-instruction target names are reserved by the xml specification for particular, standard uses (see, for example, <?xml-stylesheet ?>).
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.
PromiseRejectionEvent - Web APIs
examples this simple example catches unhandled promise rejections and logs them for debugging purposes.
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@ex...
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.cred...
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", }, pubkeycredpa...
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.
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 c...
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 }).ca...
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 creden...
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 ...
PushEvent.PushEvent() - Web APIs
example var datainit = { data : 'some sample text' } var mypushevent = new pushevent('push', datainit); mypushevent.data.text(); // should return 'some sample text' browser compatibility the compatibility table on this page is generated from structured data.
PushManager.getSubscription() - Web APIs
example this code snippet is taken from a push messaging and notification sample.
PushManager.hasPermission() - Web APIs
} ); example // tbd specification specification status comment push api working draft defines the pushmanager interface.
PushManager.register() - Web APIs
example var req = navigator.push.register(); req.onsuccess = function(e) { var endpoint = req.result; debug("new endpoint: " + endpoint ); } req.onerror = function(e) { debug("error getting a new endpoint: " + json.stringify(e)); } specification specification status comment push api working draft defines the pushmanager interface.
PushManager.registrations() - Web APIs
example var req = navigator.push.registrations(); req.onsuccess = function(e) { if (req.result.length > 0) { for (var i = 0, l = req.result.length; i < l; i++) { console.log("existing registration", req.result[i].pushendpoint, req.result[i].version); } // reuse existing endpoints.
PushManager.unregister() - Web APIs
example var req = navigator.push.unregister(pushendpoint); req.onsuccess = function(e) { var endpoint = req.result; debug("unregistered endpoint: " + endpoint ); } req.onerror = function(e) { debug("error unregistering the endpoint: " + json.stringify(e)); } specification specification status comment push api working draft defines the pushmanager interface.
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 definit...
PushSubscription.endpoint - Web APIs
example navigator.serviceworker.ready.then(function(reg) { reg.pushmanager.subscribe({uservisibleonly: true}).then(function(subscription) { console.log(subscription.endpoint); // at this point you would most likely send the subscription // endpoint to your server, save it, then use it to send a // push message at a later date }) }) specifications specification s...
PushSubscription.getKey() - Web APIs
example reg.pushmanager.getsubscription() .then(function(subscription) { // enable any ui which subscribes / unsubscribes from // push messages.
PushSubscription.toJSON() - Web APIs
example navigator.serviceworker.ready.then(function(reg) { reg.pushmanager.getsubscription().then(function(subscription) { var mysubscription = subscription.tojson(); // do something with subscription details }) }); specifications specification status comment push apithe definition of 'pushsubscription: tojson' in that specification.
PushSubscription.unsubscribe() - Web APIs
example navigator.serviceworker.ready.then(function(reg) { reg.pushmanager.getsubscription().then(function(subscription) { subscription.unsubscribe().then(function(successful) { // you've successfully unsubscribed }).catch(function(e) { // unsubscription failed }) }) }); specifications specification status comment push apithe definition of 'unsubscribe()' in that specification.
PushSubscription - Web APIs
example navigator.serviceworker.ready.then(function(reg) { reg.pushmanager.getsubscription().then(function(subscription) { subscription.unsubscribe().then(function(successful) { // you've successfully unsubscribed }).catch(function(e) { // unsubscription failed }) }) }); specifications specification status comment push apithe definition of 'pushsubsc...
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.insertDTMF() - Web APIs
example tbd specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcdtmfsender.insertdtmf()' in that specification.
RTCDTMFSender.ontonechange - Web APIs
example tbd specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'ontonechange' 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>".
RTCDTMFSender - Web APIs
example see the article using dtmf with webrtc for a full example.
RTCDTMFToneChangeEvent.tone - Web APIs
syntax var tone = dtmftonechangeevent.tone; example 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.binaryType - Web APIs
example this code configures a data channel to receive binary data in arraybuffer objects, and establishes a listener for message events which constructs a string representing the received data as a list of hexadecimal byte values.
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() - Web APIs
example var pc = new rtcpeerconnection(); var dc = pc.createdatachannel("my channel"); dc.onmessage = function (event) { console.log("received: " + event.data); dc.close(); // we decided to close after the first received message }; dc.onopen = function () { console.log("datachannel open"); }; dc.onclose = function ( console.log("datachannel close"); }; // now negotiate the connection and so ...
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.id - Web APIs
WebAPIRTCDataChannelid
example var pc = new rtcpeerconnection(); var dc = pc.createdatachannel("my channel"); console.log("channel id: " + dc.id); specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcdatachannel.id' in that specification.
RTCDataChannel.label - Web APIs
example this sample creates a data channel on an rtcpeerconnection, then, some time later, sets the content of a ui element to display the channel's name.
RTCDataChannel.maxPacketLifeTime - Web APIs
example // tbd specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcdatachannel.maxpacketlifetime' in that specification.
RTCDataChannel.maxRetransmits - Web APIs
example // tbd specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcdatachannel.maxretransmits' in that specification.
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.negotiated - Web APIs
example the code snippet below checks the value of negotiated; if it's true, a function called shutdownremotechannel() is called with the channel's id; presumably this would be implemented to transmit a shutdown signal to the remote peer prior to terminating the connection.
RTCDataChannel.onbufferedamountlow - Web APIs
example this example responds to the bufferedamountlow event by fetching up to 64kb of a file represented by an object source and calling rtcdatachannel.send() to queue up the retrieved data for sending on the data channel.
RTCDataChannel.onclose - Web APIs
example in this sample from a hypothetical instant messaging client, a data channel is created, then handlers for the open and close events are set up to enable and disable user interface objects based on the state of the channel.
RTCDataChannel.onclosing - Web APIs
for example, after rtcdatachannel.close() was called but the underlying data transport might not have been closed yet.
RTCDataChannel.onerror - Web APIs
example in the example below, a data channel is established, and an onerror handler is added to it.
RTCDataChannel.onmessage - Web APIs
example this code snippet creates a peer connection, adds a data channel to it, and starts creating new <p> (paragraph) elements each time a message arrives, with the message's contents displayed inside it.
RTCDataChannel.onopen - Web APIs
example this example adds a new data channel to an existing rtcpeerconnection, mypeerconnection.
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.
RTCDataChannel.ordered - Web APIs
example var pc = new rtcpeerconnection(); var dc = pc.createdatachannel("my channel"); if (!dc.ordered) { // handle unordered messaging } specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcdatachannel.ordered' in that specification.
RTCDataChannel.readyState - Web APIs
example var datachannel = peerconnection.createdatachannel("file transfer"); var sendqueue = []; function sendmessage(msg) { switch(datachannel.readystate) { case "connecting": console.log("connection not open; queueing: " + msg); sendqueue.push(msg); break; case "open": sendqueue.foreach((msg) => datachannel.send(msg)); break; case "closing": console.l...
RTCDataChannel.reliable - Web APIs
example // tbd specifications no longer part of any specification.
RTCDataChannel.stream - Web APIs
example var datachannel = pc.createdatachannel("samplechannel"); console.log("data channel stream id: " + datachannel.stream); ...
RTCDataChannelEvent() - Web APIs
example in this example, a new datachannel event is created.
RTCDataChannelEvent.channel - Web APIs
example the first line of code in the datachannel event handler shown below takes the channel from the event object and saves it locally for use by the code handling data traffic.
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.
RTCIceCandidate.address - Web APIs
example this code snippet uses the value of address to implement an ip address based ban feature.
RTCIceCandidate.component - Web APIs
example this code snippet examines a candidate's component type and dispatches the candidate to different handlers depending on the value.
RTCIceCandidate.foundation - Web APIs
example this code snippet uses the foundation of two candidates to determine if they're actually the same candidate.
RTCIceCandidate.port - Web APIs
example this code snippet fetches the ip address and port number of the candidate, storing them into an object for future use.
RTCIceCandidate.relatedAddress - Web APIs
example in this example, the candidate's type is checked, and then debugging output is presented, based on the candidate type, including the candidate's ip and relatedaddress.
RTCIceCandidate.sdpMLineIndex - Web APIs
example ...
RTCIceCandidate.sdpMid - Web APIs
example ...
RTCIceCandidate.tcpType - Web APIs
example in this example, the candidate's protocol and tcptype are used to adjust the user interface for simultaneous-open tcp candidates.
RTCIceCandidate.type - Web APIs
example in this example, the candidate's type is used to present a modified user interface for host candidates (those where the ip refers directly to the remote peer, rather than an intermediary).
RTCIceCandidate - Web APIs
examples for examples, see the article signaling and video calling, which demonstrates the entire process.
RTCIceCandidateInit.sdpMLineIndex - Web APIs
example ...
RTCIceCandidateInit.sdpMid - Web APIs
example ...
RTCIceCandidatePair.local - Web APIs
example this one-line example simply obtains the current candidate pair and then from that gets the local candidate.
RTCIceCandidatePair.remote - Web APIs
example this one-line example simply obtains the current candidate pair and then from that gets the remote candidate.
RTCIceCandidatePair - Web APIs
example in this example, an event handler for selectedcandidatepairchange is set up to update an on-screen display showing the protocol used by the currently selected candidate pair.
RTCIceCandidatePairStats.selected - Web APIs
example the function shown in this example identifies the currently-selected candidate pair from a statistics report by first iterating over each report, looking for a transport report; when one is found, that transport's selectedcandidatepairid is used to get the rtcicecandidatepair describing the connection.
RTCIceCandidatePairStats - Web APIs
example this example computes the average time elapsed between connectivity checks if the rtcstats object rtcstats is an rtcicecandidatepairstats object.
RTCIceCandidateStats.deleted - Web APIs
example in this example, setinterval() is used to set up a function that runs periodically to display the latest statistics for candidates.
RTCIceCandidateStats.transportId - Web APIs
this can be used to compare candidates that would use the same transport, for example.
RTCIceCandidateStats - Web APIs
example this example features a function, isusablenetworktype(), whose job it is to look at an rtcicecandidatestats object's networktype and determine whether or not the type of network is acceptable for use.
RTCIceTransport: gatheringstatechange event - Web APIs
examples this example creates a handler for gatheringstatechange events on each rtcrtpsender associated with a given rtcpeerconnection.
RTCIceTransport.getLocalCandidates() - Web APIs
example this simple example gets the local candidate list from the rtcicetransport for the first rtcrtpsender on the rtcpeerconnection, then outputs to the console all of the candidates in the list.
RTCIceTransport.getRemoteCandidates() - Web APIs
example this simple example gets the remote candidate list from the rtcicetransport for the first rtcrtpsender on the rtcpeerconnection, then outputs to the console all of the candidates in the list.
RTCIceTransport.getSelectedCandidatePair() - Web APIs
example in this example, an event handler for selectedcandidatepairchange is set up to update an on-screen display showing the protocol used by the currently selected candidate pair.
RTCIceTransport.ongatheringstatechange - Web APIs
example this snippet establishes a handler for the gatheringstatechange event that checks to see if the state has changed to "complete", indicating that all ice candidates from both the local and remote peers have been received and processed.
RTCIceTransport.onselectedcandidatepairchange - Web APIs
example in this example, an event handler for selectedcandidatepairchange is set up to update an on-screen display showing the protocol used by the currently selected candidate pair.
RTCIceTransport.onstatechange - Web APIs
example this snippet establishes a handler for the statechange event that looks to see if the transport has entered the "failed" state, which indicates that the connection has failed with no chance of being automatically restored.
RTCIceTransport: selectedcandidatepairchange event - Web APIs
bubbles no cancelable no interface event event handler property onselectedcandidatepairchange examples this example creates an event handler for selectedcandidatepairchange that updates a display providing the user information about the progress of the ice negotiation for an rtcpeerconnection called pc.
RTCIceTransport: statechange event - Web APIs
bubbles no cancelable no interface event event handler property rtcicetransport.onstatechange examples given an rtcpeerconnection, pc, the following code creates an event handler that calls a function named handlefailure() if the ice transport enters a failure state.
RTCIceTransport - Web APIs
examples tbd specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcicetransport' in that specification.
RTCIdentityErrorEvent.idp - Web APIs
syntax var idp = event.idp; event.idp = "developer.mozilla.org"; example pc.onidpassertionerror = function( ev ) { alert("the idp named '" + ev.idp + "' encountered an error " + "while generating an assertion."); } ...
RTCIdentityErrorEvent.loginUrl - Web APIs
syntax var loginurl = event.loginurl; event.loginurl = "https://developer.mozilla.org/fakeurl"; example pc.onidpassertionerror = function( ev ) { alert("the idp requested an authentication" + " to be performed at th3 url '" + ev.url + "'."); } ...
RTCIdentityErrorEvent.protocol - Web APIs
syntax var protocol = event.protocol; event.protocol = "idp.html"; example pc.onidpassertionerror = function( ev ) { alert("the idp uses the following protocol '" + ev.protocol + "."); } ...
RTCIdentityErrorEvent - Web APIs
examples pc.onidpassertionerror = function( ev ) { alert("the idp named '" + ev.idp + "' encountered an error " + "while generating an assertion."); } ...
RTCIdentityEvent.assertion - Web APIs
syntax var blob = event.assertion; example pc.onidentityresult = function( ev ) { alert("a new identity assertion (blob: '" + ev.assertion + "') has been generated."); } ...
RTCIdentityEvent - Web APIs
examples pc.onidentityresult = function( ev ) { alert("a new identity assertion (blob: '" + ev.assertion + "') has been generated."); } ...
RTCInboundRtpStreamStats.fecPacketsReceived - Web APIs
note: this counter may also be incremented when fec packets arrive in-band along with media content; this can happen with opus, for example.
RTCNetworkType - Web APIs
for example, if the networktype is wifi but the user is connected using a cellular hotspot, the connection will be bottlenecked by the underlying cellular network (and any other networks between the two peers).
RTCOfferOptions.iceRestart - Web APIs
fundamentally, this renegotiation is triggered by generating and using new values for the ice username fragment ("ufrag")}} example this example shows a handler for the iceconnectionstatechange event.
RTCOutboundRtpStreamStats.qualityLimitationReason - Web APIs
examples specifications specification status comment identifiers for webrtc's statistics apithe definition of 'rtcoutboundrtpstreamstats.qualitylimitationreason' in that specification.
RTCOutboundRtpStreamStats - Web APIs
examples specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcoutboundrtpstreamstats' in that specification.
RTCPeerConnection.addStream() - Web APIs
example this simple example adds the audio and video stream coming from the user's camera to the connection.
RTCPeerConnection: addstream event - Web APIs
examples this example looks to determine if the user's browser supports the track event.
RTCPeerConnection.canTrickleIceCandidates - Web APIs
example var pc = new rtcpeerconnection(); // the following code might be used to handle an offer from a peer when // it isn't known whether it supports trickle ice.
RTCPeerConnection.close() - Web APIs
example var pc = new rtcpeerconnection(); var dc = pc.createdatachannel("my channel"); dc.onmessage = function (event) { console.log("received: " + event.data); pc.close(); // we decided to close after the first received message }; dc.onopen = function () { console.log("datachannel open"); }; dc.onclose = function () { console.log("datachannel close"); }; specifications specificati...
RTCPeerConnection.connectionState - Web APIs
example var pc = new rtcpeerconnection(configuration); /* ...
RTCPeerConnection: connectionstatechange event - Web APIs
bubbles no cancelable no interface event event handler onconnectionstatechange examples for an rtcpeerconnection, pc, this example sets up a handler for connectionstatechange messages to handle changes to the connectivity of the webrtc session.
RTCPeerConnection.createAnswer() - Web APIs
example here is a segment of code taken from the code that goes with the article signaling and video calling.
RTCPeerConnection.currentLocalDescription - Web APIs
example this example looks at the currentlocaldescription and displays an alert containing the rtcsessiondescription object's type and sdp fields.
RTCPeerConnection.currentRemoteDescription - Web APIs
example this example looks at the currentremotedescription and displays an alert containing the rtcsessiondescription object's type and sdp fields.
RTCPeerConnection: datachannel event - Web APIs
bubbles no cancelable no interface rtcdatachannelevent event handler property ondatachannel examples this example sets up a function that handles datachannel events by gathering the information needed to communicate with the newly added rtcdatachannel and by adding event handlers for the events that occur on that channel.
RTCPeerConnection.generateCertificate() - Web APIs
example rtcpeerconnection.generatecertificate({ name: 'rsassa-pkcs1-v1_5', hash: 'sha-256', moduluslength: 2048, publicexponent: new uint8array([1, 0, 1]) }).then(function(cert) { var pc = new rtcpeerconnection({certificates: [cert]}); }); specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'generat...
RTCPeerConnection.getDefaultIceServers() - Web APIs
example var pc = new rtcpeerconnection(); var iceservers = pc.getdefaulticeservers(); if (iceservers.length === 0) { // deal with the lack of default ice servers, possibly by using our own defaults } specifications specification status comment webrtc extensions ...
RTCPeerConnection.getIdentityAssertion() - Web APIs
example var pc = new peerconnection(); pc.getidentityassertion(); // not mandatory, but we know that we will need it in the future.
RTCPeerConnection.getReceivers() - Web APIs
example tbd specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcpeerconnection.getreceivers()' in that specification.
RTCPeerConnection.getSenders() - Web APIs
example in this example, a setmuting() function is shown.
RTCPeerConnection.getStats() - Web APIs
example this example creates a periodic function using setinterval() that collects statistics for an rtcpeerconnection every second, generating an html-formatted report and inserting it into a specific element in the dom.
RTCPeerConnection.getStreamById() - Web APIs
example var stream = pc.getstreambyid(mytrackid); if (stream) { console.log("found stream: " + stream.id); } polyfill running the following code before any other code will create rtcpeerconnection.prototype.getstreambyid() if it's not natively available.
RTCPeerConnection.getTransceivers() - Web APIs
example the following snippet of code stops all transceivers associated with an rtcpeerconnection.
RTCPeerConnection.iceConnectionState - Web APIs
example var pc = new rtcpeerconnection(); var state = pc.iceconnectionstate; specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcpeerconnection.iceconnectionstate' in that specification.
RTCPeerConnection: icegatheringstatechange event - Web APIs
examples this example creates a handler for icegatheringstatechange events.
RTCPeerConnection: icecandidateerror event - Web APIs
example the following example establishes a handler for icecandidateerrors that occur on the rtcpeerconnection pc.
RTCPeerConnection.localDescription - Web APIs
example this example looks at the localdescription and displays an alert containing the rtcsessiondescription object's type and sdp fields.
RTCPeerConnection.onaddstream - Web APIs
example this code, based on an older version of our signaling and video calling sample, responds to addstream events by setting the video source for a <video> element to the stream specified in the event, and then enabling a "hang up" button in the app's user interface.
RTCPeerConnection.onconnectionstatechange - Web APIs
example pc.onconnectionstatechange = function(event) { switch(pc.connectionstate) { case "connected": // the connection has become fully connected break; case "disconnected": case "failed": // one or more transports has terminated unexpectedly or in an error break; case "closed": // the connection has been closed break; } } specifications ...
RTCPeerConnection.ondatachannel - Web APIs
example pc.ondatachannel = function(ev) { console.log('data channel is created!'); ev.channel.onopen = function() { console.log('data channel is open and ready to be used.'); }; }; specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcpeerconnection.ondatachannel' in that specification.
RTCPeerConnection.onicecandidate - Web APIs
example the example below, which is based on the code from the article signaling and video calling, sets up a handler for icecandidate events to send the candidates to the remote peer.
RTCPeerConnection.onicecandidateerror - Web APIs
example pc.onicecandidateerror = function(event) { if (event.errorcode >= 300 && event.errorcode <= 699) { // stun errors are in the range 300-699.
RTCPeerConnection.oniceconnectionstatechange - Web APIs
example the example below watches the state of the ice agent for a failure or unexpected closure and takes appropriate action, such as presenting an error message or attempting to restart the ice agent.
RTCPeerConnection.onicegatheringstatechange - Web APIs
example this example updates status information presented to the user to let them know what's happening by examining the current value of the icegatheringstate property each time it changes and changing the contents of a status display based on the new information.
RTCPeerConnection.onidentityresult - Web APIs
example pc.onidentityresult = function(ev) { alert("onidentityresult event detected!"); }; ...
RTCPeerConnection.onidpassertionerror - Web APIs
example pc.onidpassertionerror = function(ev) { alert("onidpassertionerror event detected!"); }; ...
RTCPeerConnection.onidpvalidationerror - Web APIs
example pc.onidpvalidationerror = function(ev) { alert("onidpvalidationerror event detected!"); }; ...
RTCPeerConnection.onnegotiationneeded - Web APIs
example this example, derived from the example in signaling and video calling, establishes a handler for negotiationneeded events to handle creating an offer, configuring the local end of the connection, and sending the offer to the remote peer.
RTCPeerConnection.onpeeridentity - Web APIs
example pc.onpeeridentity = function(ev) { alert("onpeeridentity event detected!"); }; ...
RTCPeerConnection.onremovestream - Web APIs
example pc.onremovestream = function(ev) { alert("onremovestream event detected!"); }; ...
RTCPeerConnection.onsignalingstatechange - Web APIs
you may also, as always, set up a handler for the signalingstatechange event using addeventlistener(): myrtcpeerconnection.addeventlistener("signalingstatechange", mysignalingstatechangehandler); or, using an anonymous (inline) handler: myrtcpeerconnection.addeventlistener("signalingstatechange", event => { /* handle the event here */ }); example this snippet shows a handler for signalingstatechange that looks for the "have-local-pranswer" signaling state—indicating that a remote offer has been received and a local description of type "pranswer" has been applied in response.
RTCPeerConnection.ontrack - Web APIs
example this example, taken from the code for the article signaling and video calling, connects the incoming track to the <video> element which will be used to display the incoming video.
RTCPeerConnection.peerIdentity - Web APIs
example in this example, a function, getidentityassertion(), is created which asynchronously waits for the peer's identity to be verified, then returns the identity to the caller.
RTCPeerConnection: peeridentity event - Web APIs
examples for the correct way to detect a new peer identity, see rtcpeerconnection.peeridentity.
RTCPeerConnection.pendingLocalDescription - Web APIs
example this example looks at the pendinglocaldescription to determine whether or not there's a description change being processed.
RTCPeerConnection.pendingRemoteDescription - Web APIs
example this example looks at the pendingremotedescription to determine whether or not there's a description change being processed.
RTCPeerConnection.remoteDescription - Web APIs
example this example looks at the remotedescription and displays an alert containing the rtcsessiondescription object's type and sdp fields.
RTCPeerConnection.removeStream() - Web APIs
example var pc, videostream; navigator.getusermedia({video: true}, function(stream) { pc = new rtcpeerconnection(); videostream = stream; pc.addstream(stream); } document.getelementbyid("closebutton").addeventlistener("click", function(event) { pc.removestream(videostream); pc.close(); }, false); ...
RTCPeerConnection.removeTrack() - Web APIs
example this example adds a video track to a connection and sets up a listener on a close button which removes the track when the user clicks the button.
RTCPeerConnection.restartIce() - Web APIs
example this example creates a handler for the iceconnectionstatechange event that handles a transition to the failed state by restarting ice in order to try again.
RTCPeerConnection.sctp - Web APIs
example var pc = new rtcpeerconnection(); var channel = pc.createdatachannel("mydata"); channel.onopen = function(event) { channel.send('sending a message'); } channel.onmessage = function(event) { console.log(event.data); } // determine the largest message size that can be sent var sctp = pc.sctp; var maxmessagesize = sctp.maxmessagesize; specifications specification status com...
RTCPeerConnection.setIdentityProvider() - Web APIs
example var pc = new peerconnection(); pc.setidentityassertion("developer.mozilla.org"); specifications specification status comment identity for webrtcthe definition of 'rtcpeerconnection.setidentityprovider()' in that specification.
RTCPeerConnection: signalingstatechange event - Web APIs
bubbles no cancelable no interface event event handler property rtcpeerconnection.onsignalingstatechange examples given an rtcpeerconnection, pc, and an updatestatus() function that presents status information to the user, this code sets up an event handler to let the user know when the ice negotiation process finishes up.
RTCPeerConnection: track event - Web APIs
examples this example shows code that creates a new rtcpeerconnection, then adds a new track event handler.
RTCPeerConnection - Web APIs
this lets you detect, for example, when collection of ice candidates has finished.localdescription read only the read-only property rtcpeerconnection.localdescription returns an rtcsessiondescription describing the session for the local end of the connection.
RTCPeerConnectionIceErrorEvent - Web APIs
examples tbd specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcpeerconnectioniceerrorevent' in that specification.
RTCPeerConnectionIceEvent.candidate - Web APIs
example pc.onicecandidate = function( ev ) { alert("the ice candidate (transport address: '" + ev.candidate.candidate + "') has been added to this connection."); } specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcpeerconnectioniceevent.candidate' in that specification.
RTCPeerConnectionIceEvent - Web APIs
examples pc.onicecandidate = function( ev ) { alert("the ice candidate (transport address: '" + ev.candidate.candidate + "') has been added to this connection."); } specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcpeerconnectioniceevent' in that specification.
RTCRemoteOutboundRtpStreamStats.reportsSent - Web APIs
examples <<<--- add an example --->>> ...
RTCRtpCodecParameters - Web APIs
for example, for audio codecs, a value of 1 specifies monaural sound while 2 indicates stereo.
RTCRtpEncodingParameters.maxBitrate - Web APIs
other parameters may further reduce the bandwidth used by the track; for example, maxframerate will, if set low enough, constrain the bandwidth as well.
RTCRtpParameters - Web APIs
examples this example obtains the canonical name (cname) being used for rtcp on an rtcrtpsender or rtcrtpreceiver.
RTCRtpReceiveParameters - Web APIs
examples this example obtains the canonical name (cname) being used for rtcp on an rtcrtpreceiver.
RTCRtpReceiver.getParameters() - Web APIs
examples this example obtains the canonical name (cname) being used for rtcp on an rtcrtpreceiver.
RTCRtpReceiver.getStats() - Web APIs
example this simple example obtains the statistics for an rtcrtpreceiver and updates an element's innertext to display the number of packets lost.
RTCRtpSender.dtmf - Web APIs
WebAPIRTCRtpSenderdtmf
only audio tracks can support dtmf, and typically only one audio track per rtcpeerconnection will have an associated rtcdtmfsender example tbd specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcrtpsender.dtmf' in that specification.
RTCRtpSender.getParameters() - Web APIs
examples this example gets the sender's current transaction id; the transaction id uniquely identifies the current set of parameters, to ensure that calls to setparameters() are always handled in the correct order, avoiding inadvertently overwriting parameters with older parameters.
RTCRtpSender.getStats() - Web APIs
example this simple example obtains the statistics for an rtcrtpsender and updates an element's innertext to display the current round trip time for requests on the sender.
RTCRtpSender.setStreams() - Web APIs
example this example adds all of an rtcpeerconnection's tracks to the specified stream.
RTCRtpSender - Web APIs
this method can be used, for example, to toggle between the front- and rear-facing cameras on a device.
RTCRtpStreamStats.ssrc - Web APIs
note: the specification includes an example that generates values for ssrc using md5.
RTCRtpTransceiver.direction - Web APIs
for example, if the direction is specified as "sendrecv", the corresponding sdp a-line is: a=sendrecv specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcrtptransceiver.direction' in that specification.
RTCSctpTransport - Web APIs
methods this interface has no methods, but inherits methods from: eventtarget example tbd specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcsctptransport' in that specification.
RTCSessionDescription() - Web APIs
example this example uses the constructor to convert an sdp offer into an rtcsessiondescription object.
RTCSessionDescription.sdp - Web APIs
syntax var value = sessiondescription.sdp; sessiondescription.sdp = value; value the value is a domstring containing an sdp message like this one: v=0 o=alice 2890844526 2890844526 in ip4 host.anywhere.com s= c=in ip4 host.anywhere.com t=0 0 m=audio 49170 rtp/avp 0 a=rtpmap:0 pcmu/8000 m=video 51372 rtp/avp 31 a=rtpmap:31 h261/90000 m=video 53000 rtp/avp 32 a=rtpmap:32 mpv/90000 example // the remote description has been set previously on pc, an rtcpeerconnection alert(pc.remotedescription.sdp); specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcsessiondescription.sdp' in that specification.
RTCSessionDescription.toJSON() - Web APIs
example // sd is a rtcsessiondescriptor alert(json.stringify(sd)); // this call the tojson() method behind the scene.
RTCSessionDescription.type - Web APIs
example // the remote description has been set previously on pc, a rtcpeerconnection alert(pc.remotedescription.type); specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcsessiondescription.type' in that specification.
RTCSessionDescription - Web APIs
example signalingchannel.onmessage = function (evt) { if (!pc) start(false); var message = json.parse(evt.data); if (message.sdp) pc.setremotedescription(new rtcsessiondescription(message), function () { // if we received an offer, we need to answer if (pc.remotedescription.type == "offer") pc.createanswer(localdesccreated, logerror);...
RTCSessionDescriptionCallback - Web APIs
example var pc = new rtcpeerconnection(); var descriptioncallback = function(offer) { pc.setlocaldescription(offer); } pc.createoffer(descriptioncallback); specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcsessiondescriptioncallback' in that specification.
RTCStats - Web APIs
WebAPIRTCStats
for example, statistics about a received rtp stream are represented by rtcreceivedrtpstreamstats.
RadioNodeList.value - Web APIs
syntax value = radionodelist.value; radionodelist.value = string; example html <form> <label><input type="radio" name="color" value="blue">blue</label> <label><input type="radio" name="color" value="red">red</label> </form> javascript // get the form const form = document.forms[0]; // get the form's radio buttons const radios = form.elements['color']; // choose the "red" option radios.value = 'red'; result specifications specification status ...
Range() - Web APIs
WebAPIRangeRange
syntax range = new range() example in this example we create a new range with the range() constructor, and set its beginning and end positions using the range.setstartbefore() and range.setendafter() methods.
Range.cloneContents() - Web APIs
syntax documentfragment = range.clonecontents(); example range = document.createrange(); range.selectnode(document.getelementsbytagname("div").item(0)); documentfragment = range.clonecontents(); document.body.appendchild(documentfragment); specifications specification status comment domthe definition of 'range.clonecontents()' in that specification.
Range.cloneRange() - Web APIs
WebAPIRangecloneRange
syntax clone = range.clonerange(); example range = document.createrange(); range.selectnode(document.getelementsbytagname("div").item(0)); clone = range.clonerange(); specifications specification status comment domthe definition of 'range.clonerange()' in that specification.
Range.collapse() - Web APIs
WebAPIRangecollapse
example var range = document.createrange(); referencenode = document.getelementsbytagname("div").item(0); range.selectnode(referencenode); range.collapse(true); specifications specification status comment domthe definition of 'range.collapse()' in that specification.
Range.collapsed - Web APIs
WebAPIRangecollapsed
syntax iscollapsed = range.collapsed; example let range = document.createrange(); range.setstart(startnode, startoffset); range.setend(endnode, endoffset); iscollapsed = range.collapsed; specifications specification status comment domthe definition of 'range.collapsed' in that specification.
Range.commonAncestorContainer - Web APIs
syntax rangeancestor = range.commonancestorcontainer; example in this example, we create an event listener to handle pointerup events on a list.
Range.compareBoundaryPoints() - Web APIs
example var range, sourcerange, compare; range = document.createrange(); range.selectnode(document.getelementsbytagname("div")[0]); sourcerange = document.createrange(); sourcerange.selectnode(document.getelementsbytagname("div")[1]); compare = range.compareboundarypoints(range.start_to_end, sourcerange); specifications specification status comment domthe definition of 'range.
Range.compareNode() - Web APIs
WebAPIRangecompareNode
example range = document.createrange(); range.selectnode(document.getelementsbytagname("div").item(0)); returnvalue = range.comparenode(document.getelementsbytagname("p").item(0)); notes this method is obsolete; you should use the w3c dom range.compareboundarypoints() method.
Range.comparePoint() - Web APIs
example range = document.createrange(); range.selectnode(document.getelementsbytagname('div').item(0)); returnvalue = range.comparepoint(document.getelementsbytagname('p').item(0), 1); specification specification status comment domthe definition of 'range.comparepoint()' in that specification.
Range.createContextualFragment() - Web APIs
example var tagstring = "<div>i am a div node</div>"; var range = document.createrange(); // make the parent of the first div in the document becomes the context node range.selectnode(document.getelementsbytagname("div").item(0)); var documentfragment = range.createcontextualfragment(tagstring); document.body.appendchild(documentfragment); specification specification status comment ...
Range.deleteContents() - Web APIs
syntax range.deletecontents() example range = document.createrange(); range.selectnode(document.getelementsbytagname("div").item(0)); range.deletecontents(); specifications specification status comment domthe definition of 'range.deletecontents()' in that specification.
Range.detach() - Web APIs
WebAPIRangedetach
syntax range.detach(); example var range = document.createrange(); range.selectnode(document.getelementsbytagname("div").item(0)); range.detach(); specifications specification status comment domthe definition of 'range.detach()' in that specification.
Range.endContainer - Web APIs
syntax endrangenode = range.endcontainer; example var range = document.createrange(); range.setstart(startnode,startoffset); range.setend(endnode,endoffset); endrangenode = range.endcontainer; specifications specification status comment domthe definition of 'range.endcontainer' in that specification.
Range.endOffset - Web APIs
WebAPIRangeendOffset
syntax endrangeoffset = range.endoffset; example var range = document.createrange(); range.setstart(startnode,startoffset); range.setend(endnode,endoffset); endrangeoffset = range.endoffset; specifications specification status comment domthe definition of 'range.endoffset' in that specification.
Range.extractContents() - Web APIs
syntax documentfragment = range.extractcontents(); example basic example var range = document.createrange(); range.selectnode(document.getelementsbytagname("div").item(0)); var documentfragment = range.extractcontents(); document.body.appendchild(documentfragment); moving items between containers this example lets you move items between two containers.
Range.getBoundingClientRect() - Web APIs
syntax boundingrect = range.getboundingclientrect() example html <div id="highlight"></div> <p>this example positions a "highlight" rectangle behind the contents of a range.
Range.getClientRects() - Web APIs
syntax rectlist = range.getclientrects() example range = document.createrange(); range.selectnode(document.getelementsbytagname("div").item(0)); rectlist = range.getclientrects(); specification specification status comment css object model (cssom) view modulethe definition of 'range.getclientrects()' in that specification.
Range.insertNode() - Web APIs
WebAPIRangeinsertNode
example range = document.createrange(); newnode = document.createelement("p"); newnode.appendchild(document.createtextnode("new node inserted here")); range.selectnode(document.getelementsbytagname("div").item(0)); range.insertnode(newnode); specifications specification status comment domthe definition of 'range.insertnode()' in that specification.
Range.intersectsNode() - Web APIs
example var range = document.createrange(); range.selectnode(document.getelementsbytagname("div").item(0)); var bool = range.intersectsnode(document.getelementsbytagname("p").item(0)); specification specification status comment domthe definition of 'range.intersectnode()' in that specification.
Range.isPointInRange() - Web APIs
example range = document.createrange(); range.selectnode(document.getelementsbytagname("div").item(0)); bool = range.ispointinrange(document.getelementsbytagname("p").item(0),1); specification specification status comment domthe definition of 'range.ispointinrange()' in that specification.
Range.selectNode() - Web APIs
WebAPIRangeselectNode
example let range = document.createrange(); let referencenode = document.getelementsbytagname('div').item(0); range.selectnode(referencenode); specifications specification status comment domthe definition of 'range.selectnode()' in that specification.
Range.selectNodeContents() - Web APIs
example range = document.createrange(); referencenode = document.getelementsbytagname("div")[0]; range.selectnodecontents(referencenode); live sample this example lets the user select and deselect a paragraph with buttons.
Range.setEnd() - Web APIs
WebAPIRangesetEnd
example const range = document.createrange(); const endnode = document.getelementsbytagname('p').item(3); const endoffset = endnode.childnodes.length; range.setend(endnode, endoffset); setend() is commonly used in conjunction with setstart() to fully configure a range.
Range.setEndAfter() - Web APIs
WebAPIRangesetEndAfter
example var range = document.createrange(); var referencenode = document.getelementsbytagname('div').item(0); range.setendafter(referencenode); specifications specification status comment domthe definition of 'range.setendafter()' in that specification.
Range.setEndBefore() - Web APIs
example var range = document.createrange(); var referencenode = document.getelementsbytagname("div").item(0); range.setendbefore(referencenode); specifications specification status comment domthe definition of 'range.setendbefore()' in that specification.
Range.setStartAfter() - Web APIs
example var range = document.createrange(); var referencenode = document.getelementsbytagname("div").item(0); range.setstartafter(referencenode); specifications specification status comment domthe definition of 'range.setstartafter()' in that specification.
Range.setStartBefore() - Web APIs
example var range = document.createrange(); var referencenode = document.getelementsbytagname("div").item(0); range.setstartbefore(referencenode); specifications specification status comment domthe definition of 'range.setstartbefore()' in that specification.
Range.startContainer - Web APIs
syntax startrangenode = range.startcontainer; example range = document.createrange(); range.setstart(startnode,startoffset); range.setend(endnode,endoffset); startrangenode = range.startcontainer; specifications specification status comment domthe definition of 'range.endcontainer' in that specification.
Range.startOffset - Web APIs
WebAPIRangestartOffset
syntax startrangeoffset = range.startoffset; example var range = document.createrange(); range.setstart(startnode,startoffset); range.setend(endnode,endoffset); var startrangeoffset = range.startoffset; specifications specification status comment domthe definition of 'range.startoffset' in that specification.
Range.surroundContents() - Web APIs
example html <span class="header-text">put this in a headline</span> javascript const range = document.createrange(); const newparent = document.createelement('h1'); range.selectnode(document.queryselector('.header-text')); range.surroundcontents(newparent); result specifications specification status comment domthe definition of 'range.surroundcontents()' in that specifi...
Range.toString() - Web APIs
WebAPIRangetoString
syntax text = range.tostring(); example html <p>this example logs <b>everything</b> between the bold <b>words</b>.
ReadableByteStreamController.byobRequest - Web APIs
examples tbd.
ReadableByteStreamController.close() - Web APIs
examples tbd.
ReadableByteStreamController.desiredSize - Web APIs
examples tbd.
ReadableByteStreamController.enqueue() - Web APIs
examples tbd.
ReadableByteStreamController.error() - Web APIs
examples tbd.
ReadableByteStreamController - Web APIs
examples tbd.
ReadableStream.cancel() - Web APIs
examples in jake archibald's cancelling a fetch example, a stream is used to fetch the whatwg html spec chunk by chunk; each chunk is searched for the string "service workers".
ReadableStream.locked - Web APIs
examples const stream = new readablestream({ ...
ReadableStream.pipeTo() - Web APIs
examples // fetch the original image fetch('png-logo.png') // retrieve its body as readablestream .then(response => response.body) .then(body => body.pipethrough(new pngtransformstream())) .then(rs => rs.pipeto(new finaldestinationstream())) specifications specification status comment streamsthe definition of 'pipeto()' in that specification.
ReadableStreamBYOBReader.ReadableStreamBYOBReader() - Web APIs
examples tbd specifications specification status comment streamsthe definition of 'readablestreambyobreader()' in that specification.
ReadableStreamBYOBReader.cancel() - Web APIs
examples tbd.
ReadableStreamBYOBReader.closed - Web APIs
examples tbd.
ReadableStreamBYOBReader.read() - Web APIs
examples tbd.
ReadableStreamBYOBReader.releaseLock() - Web APIs
examples tbd.
ReadableStreamBYOBReader - Web APIs
examples tbd.
ReadableStreamBYOBRequest.respond() - Web APIs
examples tbd.
ReadableStreamBYOBRequest.respondWithNewView() - Web APIs
examples tbd.
ReadableStreamBYOBRequest.view - Web APIs
examples tbd.
ReadableStreamBYOBRequest - Web APIs
methods readablestreambyobrequest.respond() xxx readablestreambyobrequest.respondwithnewview() xxx examples tbd.
ReadableStreamDefaultController.desiredSize - Web APIs
examples the a readable stream with an underlying push source and backpressure support example in the spec provides a good example of using desiredsize to manually detect when the stream is full and apply backpressure, and also of using readablestreamdefaultcontroller.error() to manually trigger a stream error if another part of the system it relies on fails.
ReadableStreamDefaultController.error() - Web APIs
examples the a readable stream with an underlying push source and backpressure support example in the spec provides a good example of using readablestreamdefaultcontroller.desiredsize to manually detect when the stream is full and apply backpressure, and also of using error() to manually trigger a stream error if another part of the system it relies on fails.
ReadableStreamDefaultReader.closed - Web APIs
examples in this snippet, a previously-created reader is queried to see if the stream has been closed.
ReadableStreamDefaultReader.releaseLock() - Web APIs
examples function fetchstream() { const reader = stream.getreader(); ...
Report.body - Web APIs
WebAPIReportbody
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
WebAPIReporttype
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 - Web APIs
WebAPIReport
examples in our deprecation_report.html example, we create a simple reporting observer to observe usage of deprecated features on our web page: let options = { types: ['deprecation'], buffered: true } let observer = new reportingobserver(function(reports, observer) { reportbtn.onclick = () => displayreports(reports); }, options); we then tell it to start observing reports using reportingobserve...
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() // ...
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.
Request.cache - Web APIs
WebAPIRequestcache
example // download a resource with cache busting, to bypass the cache // completely.
Request.clone() - Web APIs
WebAPIRequestclone
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 clone the request.
Request.credentials - 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 request credentials in a variable: var myrequest = new request('flowers.jpg'); var mycred = myrequest.credentials; // returns "same-origin" by default specifications specification status comment fetchthe defini...
Request.headers - Web APIs
WebAPIRequestheaders
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 request headers in a variable: var myrequest = new request('flowers.jpg'); var myheaders = myrequest.headers; // headers {} to add a header to the headers object we use headers.append; we then create a new request along with a 2nd init parameter, passing headers in as an init option: var myheaders = new headers(); myheaders.append('content-type', 'image/jpeg'); var myinit = { method: 'get', headers: myheaders, mode: 'cors', cache: 'defaul...
Request.integrity - Web APIs
WebAPIRequestintegrity
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 request integrity value in a variable: var myrequest = new request('flowers.jpg'); var myintegrity = myrequest.integrity; specifications specification status comment fetchthe definition of 'integrity' in that specification.
Request.method - Web APIs
WebAPIRequestmethod
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 method of the request in a variable: var myrequest = new request('flowers.jpg'); var mymethod = myrequest.method; // get specifications specification status comment fetchthe definition of 'method' in that specification.
Request.redirect - Web APIs
WebAPIRequestredirect
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 request redirect value in a variable: var myrequest = new request('flowers.jpg'); var mycred = myrequest.redirect; specifications specification status comment fetchthe definition of 'redirect' in that specification.
Request.referrer - Web APIs
WebAPIRequestreferrer
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 request referrer in a variable: var myrequest = new request('flowers.jpg'); var myreferrer = myrequest.referrer; // returns "about:client" by default specifications specification status comment fetchthe definition of 'referrer' in that specification.
Request.referrerPolicy - 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 request referrer policy in a variable: var myrequest = new request('flowers.jpg'); var myreferrer = myrequest.referrerpolicy; // returns "" by default specifications specification status comment fetchthe defini...
Request.url - Web APIs
WebAPIRequesturl
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.
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.con...
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 ...
ResizeObserverEntry.contentRect - Web APIs
examples the following snippet is taken from the resize-observer-text.html (see source) example.
ResizeObserverEntry - Web APIs
examples the following snippet is taken from the resize-observer-text.html (see source) example.
Response() - Web APIs
WebAPIResponseResponse
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.clone() - Web APIs
WebAPIResponseclone
example in our fetch response clone example (see fetch response clone live) we create a new request object using the request() constructor, passing it a jpg path.
Response.error() - Web APIs
WebAPIResponseerror
example tbd (does not yet appear to be supported anywhere).
Response.headers - Web APIs
WebAPIResponseheaders
example in our fetch response example (see fetch response live) we create a new request object using the request() constructor, passing it a jpg path.
Response.ok - Web APIs
WebAPIResponseok
example in our fetch response example (see fetch response live) we create a new request object using the request() constructor, passing it a jpg path.
Response.redirect() - Web APIs
WebAPIResponseredirect
example responseobj.redirect('https://www.example.com', 302); specifications specification status comment fetchthe definition of 'redirect()' in that specification.
Response.status - Web APIs
WebAPIResponsestatus
example in our fetch response example (see fetch response live) we create a new request object using the request() constructor, passing it a jpg path.
Response.statusText - Web APIs
example in our fetch response example (see fetch response live) we create a new request object using the request() constructor, passing it a jpg path.
Response.type - Web APIs
WebAPIResponsetype
example in our fetch response example (see fetch response live) we create a new request object using the request() constructor, passing it a jpg path.
Response.url - Web APIs
WebAPIResponseurl
example in our fetch response example (see fetch response live) we create a new request object using the request() constructor, passing it a jpg path.
Response.useFinalURL - Web APIs
example consider a script residing in page index.html: fetch('/test').then((r) => console.log(r.url)) test.html is being controlled by the service worker sw.js: onfetch = (e) => { e.respondwith(fetch('/page2').then((r) => { r.usefinalurl = true; return r; }) } the output will be /page2 and not /test in index.html, since setting the usefinalurl means that the response's url is not set to request's url.
RsaHashedImportParams - Web APIs
examples see the examples for subtlecrypto.importkey().
RsaOaepParams - Web APIs
examples see the examples for subtlecrypto.encrypt() and subtlecrypto.decrypt().
SVGAElement.target - Web APIs
sample values can be found here example the code is taken from the "svgaelement example code" ...
SVGAElement - Web APIs
example in the example below, the target attribute of the <a> element is set to _blank and when the link is clicked, it logs to notify whether the condition is met or not.
SVGAltGlyphElement.glyphRef - Web APIs
example myglyph.glypref = "#glyphid"; specifications specification status comment scalable vector graphics (svg) 1.1 (second edition)the definition of 'glyphref' in that specification.
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-...
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; bo...
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-...
targetElement - Web APIs
if no target element is being animated (for example, because the href attribute specifies an unknown element), the value returned is null.
SVGAnimationElement - Web APIs
if no target element is being animated (for example, because the href specifies an unknown element) the value returned is null.
cx - Web APIs
example svg <svg xmlns="http://www.w3.org/2000/svg" viewbox="0 0 100 100" width="200" height="200"> <circle cx="50" cy="50" r="50" fill="gold" id="circle"/> </svg> javascript const circle = document.getelementbyid('circle'); console.log(circle.cx); specifications specification status comment scalable vector graphics (svg) 2the definition of 'svgcircleelement.cx' in that specification.
cy - Web APIs
example svg <svg xmlns="http://www.w3.org/2000/svg" viewbox="0 0 100 100" width="200" height="200"> <circle cy="50" cy="50" r="50" fill="gold" id="circle"/> </svg> javascript const circle = document.getelementbyid('circle'); console.log(circle.cy); specifications specification status comment scalable vector graphics (svg) 2the definition of 'svgcircleelement.cy' in that specification.
r - Web APIs
example svg <svg xmlns="http://www.w3.org/2000/svg" viewbox="0 0 100 100" width="200" height="200"> <circle r="50" r="50" r="50" fill="gold" id="circle"/> </svg> javascript const circle = document.getelementbyid('circle'); console.log(circle.r); specifications specification status comment scalable vector graphics (svg) 2the definition of 'svgcircleelement.r' in that specification.
SVGCircleElement - Web APIs
example svg content <svg xmlns="http://www.w3.org/2000/svg" viewbox="0 0 250 250" width="250" height="250"> <circle cx="100" cy="100" r="50" fill="gold" id="circle" onclick="clickcircle();"/> </svg> javascript content this function clickcircle() is called when the circle is clicked.
SVGDocument - Web APIs
the value is an empty string if the user navigated to the page directly (not through a link, but, for example, via a bookmark).
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.'); }) ...
SVGEllipseElement - Web APIs
example svg content <svg width="200" height="200" xmlns="http://www.w3.org/2000/svg"> <ellipse cx="100" cy="100" rx="100" ry="60" id="ellipse" onclick="outputsize();"/> </svg> javascript content function outputsize() { var ellipse = document.getelementbyid("ellipse"); // outputs "horizontal radius: 100 vertical radius: 60" console.log( 'horizontal radius: ' + ellipse.rx.baseval.val...
SVGGeometryElement.isPointInFill() - Web APIs
example svg <svg viewbox="0 0 100 100" width="150" height="150" xmlns="http://www.w3.org/2000/svg"> <circle id="circle" cx="50" cy="50" r="45" fill="white" stroke="black" stroke-width="10"/> <circle cx="10" cy="10" r="5" fill="seagreen"/> <circle cx="40" cy="30" r="5" fill="seagreen"/> </svg> javascript var circle = document.getelementbyid('circle'); // point not in circle console.l...
SVGGeometryElement.isPointInStroke() - Web APIs
example svg <svg viewbox="0 0 100 100" width="150" height="150" xmlns="http://www.w3.org/2000/svg"> <circle id="circle" cx="50" cy="50" r="45" fill="white" stroke="black" stroke-width="10"/> <circle cx="10" cy="10" r="5" fill="seagreen"/> <circle cx="40" cy="30" r="5" fill="seagreen"/> <circle cx="83" cy="17" r="5" fill="seagreen"/> </svg> javascript var circle = document.getelemen...
SVGGraphicsElement: copy event - Web APIs
example html <?xml version="1.0" encoding="utf-8"?> <svg viewbox="0 0 100 30" width="600" height="320" xmlns="http://www.w3.org/2000/svg"> <text x="5" y="10" id="text-to-copy">copy this text</text> <foreignobject x="5" y="20" width="90" height="20"> <input xmlns="http://www.w3.org/1999/xhtml" placeholder="paste it here"/> </foreignobject> </svg> css input { font-size: 10px; wi...
getBBox() - Web APIs
example html <svg viewbox="0 0 200 200" xmlns="http://www.w3.org/2000/svg"> <g id="group_text_1"> <text x="5" y="16" transform="scale(2, 2)">hello world!</text> <text x="8" y="32" transform="translate(0 20) scale(1.25 1)">hello world again!</text> </g> <!-- shows bbox in green --> <rect id="rect_1" stroke="#00ff00" stroke-width="3" fill="none"> </rect> <!-- shows bou...
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.
SVGPoint - Web APIs
WebAPISVGPoint
example // create an svgpoint in the user coordinate system let s = document.getelementbyid("svg-elementid").createsvgpoint(); // then, set the x and y values of the returned svgpoint object // (which is the variable `s`) s.y = 10; s.x = 10; ...
SVGRectElement - Web APIs
example here is a simple usage of rect interface.
Screen.availHeight - Web APIs
example if your web application needs to open a new window, such as a tool palette which can contain multiple panels, and wants to position it so that it occupies the entire vertical space available, you can do so using code similar to what's seen here.
Screen.availLeft - Web APIs
WebAPIScreenavailLeft
syntax let availleft = window.screen.availleft; example let setx = window.screen.width - window.screen.availleft; let sety = window.screen.height - window.screen.availtop; window.moveto(setx, sety); notes in most cases, this property returns 0.
Screen.availTop - Web APIs
WebAPIScreenavailTop
syntax let availtop = window.screen.availtop; example let setx = window.screen.width - window.screen.availleft; let sety = window.screen.height - window.screen.availtop; window.moveto(setx, sety); notes in most cases, this property returns 0.
Screen.availWidth - Web APIs
WebAPIScreenavailWidth
syntax var width = window.screen.availwidth example var screenavailwidth = window.screen.availwidth; console.log(screenavailwidth); specifications specification status comment css object model (cssom) view modulethe definition of 'screen.availwidth' in that specification.
Screen.colorDepth - Web APIs
WebAPIScreencolorDepth
syntax bitdepth = window.screen.colordepth; example // check the color depth of the screen if ( window.screen.colordepth < 8) { // use low-color version of page } else { // use regular, colorful page } specification specification status comment css object model (cssom) view modulethe definition of 'screen.colordepth' in that specification.
Screen.height - Web APIs
WebAPIScreenheight
syntax var height = window.screen.height example if (window.screen.availheight !== window.screen.height) { // something is occupying some screen real estate!
Screen.orientation - Web APIs
example var orientation = (screen.orientation || {}).type || screen.mozorientation || screen.msorientation; if (orientation === "landscape-primary") { console.log("that looks good."); } else if (orientation === "landscape-secondary") { console.log("mmmh...
Screen.pixelDepth - Web APIs
WebAPIScreenpixelDepth
syntax let depth = window.screen.pixeldepth example // if there is not adequate bit depth // choose a simpler color if ( window.screen.pixeldepth > 8 ) { document.style.color = "#faebd7"; } else { document.style.color = "#ffffff"; } specifications specification status comment css object model (cssom) view modulethe definition of 'screen.pixeldepth' in that specification.
Screen.unlockOrientation() - Web APIs
example var unlockorientation = screen.unlockorientation || screen.mozunlockorientation || screen.msunlockorientation || (screen.orientation && screen.orientation.unlock); if (unlockorientation()) { // orientation was unlocked } else { // orientation unlock failed } specifications specification status comment screen orientation apithe definition of 'lockorientation()'...
Screen.width - Web APIs
WebAPIScreenwidth
syntax lwidth = window.screen.width example // crude way to check that the screen is at least 1024x768 if (window.screen.width >= 1024 && window.screen.height >= 768) { // resolution is 1024x768 or above } notes note that not all of the width given by this property may be available to the window itself.
Screen - Web APIs
WebAPIScreen
void seteventhandler(domstring type, eventhandler handler) eventhandler geteventhandler(domstring type) example if (screen.pixeldepth < 8) { // use low-color version of page } else { // use regular, colorful page } specification specification status comment css object model (cssom) view modulethe definition of 'screen' in that specification.
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; ch...
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.SecurityPolicyViolationEvent() - Web APIs
example let spvevt = new securitypolicyviolationevent('foo', { ...
SecurityPolicyViolationEvent.blockedURI - Web APIs
example document.addeventlistener("securitypolicyviolation", (e) => { console.log(e.blockeduri); }); specifications specification status comment content security policy level 3the definition of 'blockeduri' in that specification.
SecurityPolicyViolationEvent.columnNumber - Web APIs
example document.addeventlistener("securitypolicyviolation", (e) => { console.log(e.columnnumber); }); specifications specification status comment content security policy level 3the definition of 'columnnumber' in that specification.
SecurityPolicyViolationEvent.disposition - Web APIs
possible values are "enforce" or "report" example document.addeventlistener("securitypolicyviolation", (e) => { console.log(e.disposition); }); specifications specification status comment content security policy level 3the definition of 'disposition' in that specification.
SecurityPolicyViolationEvent.documentURI - Web APIs
example document.addeventlistener("securitypolicyviolation", (e) => { console.log(e.documenturi); }); specifications specification status comment content security policy level 3the definition of 'documenturi' in that specification.
SecurityPolicyViolationEvent.effectiveDirective - Web APIs
example document.addeventlistener("securitypolicyviolation", (e) => { console.log(e.effectivedirective); }); specifications specification status comment content security policy level 3the definition of 'effectivedirective' in that specification.
SecurityPolicyViolationEvent.lineNumber - Web APIs
example document.addeventlistener("securitypolicyviolation", (e) => { console.log(e.linenumber); }); specifications specification status comment content security policy level 3the definition of 'linenumber' in that specification.
SecurityPolicyViolationEvent.originalPolicy - Web APIs
example document.addeventlistener("securitypolicyviolation", (e) => { console.log(e.originalpolicy); }); specifications specification status comment content security policy level 3the definition of 'originalpolicy' in that specification.
SecurityPolicyViolationEvent.referrer - Web APIs
example document.addeventlistener("securitypolicyviolation", (e) => { console.log(e.referrer); }); specifications specification status comment content security policy level 3the definition of 'referrer' in that specification.
SecurityPolicyViolationEvent.sample - Web APIs
example document.addeventlistener("securitypolicyviolation", (e) => { console.log(e.sample); }); specifications specification status comment content security policy level 3the definition of 'sample' in that specification.
SecurityPolicyViolationEvent.sourceFile - Web APIs
example document.addeventlistener("securitypolicyviolation", (e) => { console.log(e.sourcefile); }); specifications specification status comment content security policy level 3the definition of 'sourcefile' in that specification.
SecurityPolicyViolationEvent.statusCode - Web APIs
example document.addeventlistener("securitypolicyviolation", (e) => { console.log(e.statuscode); }); specifications specification status comment content security policy level 3the definition of 'statuscode' in that specification.
SecurityPolicyViolationEvent.violatedDirective - Web APIs
example document.addeventlistener("securitypolicyviolation", (e) => { console.log(e.violateddirective); }); specifications specification status comment content security policy level 3the definition of 'violateddirective' in that specification.
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.
Selection.addRange() - Web APIs
example currently only firefox supports multiple selection ranges, other browsers will not add new ranges to the selection if it already contains one.
Selection.collapse() - Web APIs
examples /* place the caret at the beginning of an html document's body.
Selection.deleteFromDocument() - Web APIs
example this example lets you delete selected text by clicking a button.
Selection.getRangeAt() - Web APIs
example let ranges = []; sel = window.getselection(); for(let i = 0; i < sel.rangecount; i++) { ranges[i] = sel.getrangeat(i); } /* each item in the ranges array is now * a range object representing one of the * ranges in the current selection */ specifications specification status comment selection apithe definition of 'selection: getrangeat()' in that specification.
Selection.rangeCount - Web APIs
syntax value = sel.rangecount example the following example will show the rangecount every second.
Selection.removeRange() - Web APIs
return value undefined examples /* programmaticaly, more than one range can be selected.
Selection.selectAllChildren() - Web APIs
example html <main> <button>select footer</button> <p>welcome to my website.</p> <p>i hope you enjoy your visit.</p> </main> <footer> <address>webmaster@example.com</address> <p>© 2019</p> </footer> javascript const button = document.queryselector('button'); const footer = document.queryselector('footer'); button.addeventlistener('click', (e) => { window.getselection().selectallchildren(footer); }); result specifications specification status comment ...
Selection.type - Web APIs
WebAPISelectiontype
example in this example, the event handler will fire each time a new selection is made.
Selection - Web APIs
WebAPISelection
can return null if selection never existed in the document (for example, in an iframe that was never clicked on).
Selection API - Web APIs
once your selection is in a variable, you perform a variety of operations on it, for example copying the selection to a text string using selection.tostring(), adding a range (as represented by a standard range object) to the selection (or removing one) with selection.addrange()/selection.removerange(), or changing the selection to be the entire contents of a dom node using selection.selectallchildren().
Sensor.stop() - Web APIs
WebAPISensorstop
return value undefined example // tbd specifications specification status comment generic sensor apithe definition of 'stop' 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).
ServiceWorker - Web APIs
examples this code snippet is from the service worker registration-events sample (live demo).
ServiceWorkerContainer.controller - Web APIs
example if ('serviceworker' in navigator) { // do a one-off check to see if a service worker's in control.
ServiceWorkerContainer.getRegistration() - Web APIs
example navigator.serviceworker.getregistration('/app').then(function(registration) { if(registration){ document.queryselector('#status').textcontent = 'serviceworkerregistration found.'; } }); specifications specification status comment service workersthe definition of 'serviceworkercontainer: getregistration' in that specification.
ServiceWorkerContainer.getRegistrations() - Web APIs
example navigator.serviceworker.getregistrations().then(function(registrations) { document.queryselector('#status').textcontent = 'serviceworkerregistrations found.'; }); specifications specification status comment service workersthe definition of 'getregistrations()' in that specification.
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(() => { // ...
ServiceWorkerContainer.oncontrollerchange - Web APIs
} example // tbd specifications specification status comment service workersthe definition of 'serviceworkercontainer: oncontrollerchange' in that specification.
ServiceWorkerContainer.onerror - Web APIs
} example navigator.serviceworker.onerror = function(errorevent) { console.log(`received error message: ${errorevent.message}`); } ...
ServiceWorkerContainer.onmessage - Web APIs
} example navigator.serviceworker.onmessage = function(messageevent) { console.log(`received data: ${messageevent.data}`); } specifications specification status comment service workersthe definition of 'serviceworkercontainer: onmessage' in that specification.
ServiceWorkerContainer.ready - Web APIs
example if ('serviceworker' in navigator) { navigator.serviceworker.ready .then(function(registration) { console.log('a service worker is active:', registration.active); // at this point, you can call methods that require an active // service worker, like registration.pushmanager.subscribe() }); } else { console.log('service workers are not supported.'); } specifications ...
ServiceWorkerContainer - Web APIs
examples the example below first checks to see if the browser supports service workers.
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: contentdelete event - Web APIs
bubbles no cancelable no interface contentindexevent event handler property oncontentdelete examples the following example uses a contentdelete event handler to remove cached content related to the deleted index item.
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.onactivate - Web APIs
}; examples the following snippet shows how you could use an activate event handler to upgrade a cache.
ServiceWorkerGlobalScope.oncontentdelete - Web APIs
}; examples the following example uses a contentdelete event handler to remove cached content related to the deleted index item.
ServiceWorkerGlobalScope.onfetch - Web APIs
}; example this code snippet is from the service worker prefetch sample (see prefetch example live.) the serviceworkerglobalscope.onfetch event handler listens for the fetch event.
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/'...
ServiceWorkerGlobalScope.onmessage - Web APIs
}; example self.addeventlistener('message', function(messageevent) { console.log('handling message event:', messageevent); }) specifications specification status comment service workersthe definition of 'event handlers' in that specification.
ServiceWorkerGlobalScope.onnotificationclick - Web APIs
}; example self.onnotificationclick = 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]; ...
onnotificationclose - Web APIs
}); example //inside a service worker.
ServiceWorkerGlobalScope: push event - Web APIs
bubbles no cancelable no interface pushevent event handler property onpush example this example sets up a handler for push events that takes json data, parses it, and dispatches the message for handling based on information contained within the message.
ServiceWorkerGlobalScope - Web APIs
examples this code snippet is from the service worker prefetch sample (see prefetch example live.) the serviceworkerglobalscope.onfetch event handler listens for the fetch event.
ServiceWorkerMessageEvent.ServiceWorkerMessageEvent() - Web APIs
examples var init = { data : 'hello message', source : messageportreference, ports : messageportlistreference } var myswme = new serviceworkermessageevent('message', init); ...
ServiceWorkerMessageEvent.data - Web APIs
examples when the following code is used inside the main thread to set up a message channel between it and a service worker for sending messages between the two, the event object of onmessage will be a serviceworkermessageevent.
ServiceWorkerMessageEvent.lastEventId - Web APIs
examples when the following code is used inside the main thread to set up a message channel between it and a service worker for sending messages between the two, the event object of onmessage will be a serviceworkermessageevent.
ServiceWorkerMessageEvent.origin - Web APIs
examples when the following code is used inside the main thread to set up a message channel between it and a service worker for sending messages between the two, the event object of onmessage will be a serviceworkermessageevent.
ServiceWorkerMessageEvent.ports - Web APIs
examples when the following code is used inside the main thread to set up a message channel between it and a service worker for sending messages between the two, the event object of onmessage will be a serviceworkermessageevent.
ServiceWorkerMessageEvent.source - Web APIs
examples when the following code is used inside the main thread to set up a message channel between it and a service worker for sending messages between the two, the event object of onmessage will be a serviceworkermessageevent.
ServiceWorkerMessageEvent - Web APIs
examples when the following code is used inside the main thread to set up a message channel between it and a service worker for sending messages between the two, the event object of onmessage will be a serviceworkermessageevent.
ServiceWorkerRegistration.getNotifications() - Web APIs
example navigator.serviceworker.register('sw.js'); var options = { tag : 'user_alerts' }; navigator.serviceworker.ready.then(function(registration) { registration.getnotifications(options).then(function(notifications) { // do something with your notifications }) }); specifications specification status comment notifications apithe definition of 'serviceworkerregistrati...
ServiceWorkerRegistration.periodicSync - Web APIs
examples // tbd specifications currently not part of any specification.
ServiceWorkerRegistration.unregister() - Web APIs
example the following simple example registers a service worker example, but then immediately unregisters it again: if ('serviceworker' in navigator) { navigator.serviceworker.register('/sw-test/sw.js', {scope: 'sw-test'}).then(function(registration) { // registration worked console.log('registration succeeded.'); registration.unregister().then(function(boolean) { // if boolean = tr...
ServiceWorkerRegistration.update() - Web APIs
example the following simple example registers a service worker example then adds an event handler to a button so you can explicitly update the service worker whenever desired: if ('serviceworker' in navigator) { navigator.serviceworker.register('/sw-test/sw.js', {scope: 'sw-test'}).then(function(registration) { // registration worked console.log('registration succeeded.'); button.onclick...
ServiceWorkerRegistration - Web APIs
examples in this example, the code first checks whether the browser supports service workers and if so registers one.
ShadowRoot.delegatesFocus - Web APIs
examples let customelem = document.queryselector('my-shadow-dom-element'); let shadow = customelem.shadowroot; ...
ShadowRoot.host - Web APIs
WebAPIShadowRoothost
examples let customelem = document.queryselector('my-shadow-dom-element'); let shadow = customelem.shadowroot; ...
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 - 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
example in our basic shared worker example (run shared worker), we have two html pages, each of which uses some javascript to perform a simple calculation.
SharedWorkerGlobalScope.applicationCache - Web APIs
example if a shared worker has an appcache associated with it, you can return a reference to the cache using self.applicationcache from inside the shared worker.
SharedWorkerGlobalScope.close() - Web APIs
syntax self.close(); example if you want to close your worker instance from inside the worker itself, you can call the following: close(); close() and self.close() are effectively equivalent — both represent close() being called from inside the worker's inner scope.
SharedWorkerGlobalScope.name - Web APIs
example if a shared worker is created using a constructor with a name option: var myworker = new sharedworker("worker.js", { name : "mysharedworker" }); the sharedworkerglobalscope will now have a name of "mysharedworker", returnable by running self.name from inside the shared worker.
SharedWorkerGlobalScope - Web APIs
for example: importscripts('foo.js', 'bar.js'); implemented from other places windowbase64.atob() decodes a string of data which has been encoded using base-64 encoding.
SourceBuffer.appendBuffer() - Web APIs
example tbd.
SourceBuffer.appendBufferAsync() - Web APIs
example this simplified example async function, fillsourcebuffer(), takes as input parameters buffersource, buffer, and a sourcebuffer to which to append the source media from the buffer.
SourceBuffer.appendStream() - Web APIs
example tbd.
SourceBuffer.appendWindowEnd - Web APIs
example tbd specifications specification status comment media source extensionsthe definition of 'appendwindowend' in that specification.
SourceBuffer.appendWindowStart - Web APIs
example tbd specifications specification status comment media source extensionsthe definition of 'appendwindowstart' in that specification.
SourceBuffer.audioTracks - Web APIs
example tbd specifications specification status comment media source extensionsthe definition of 'audiotracks' in that specification.
SourceBuffer.buffered - Web APIs
example tbd specifications specification status comment media source extensionsthe definition of 'buffered' in that specification.
SourceBuffer.mode - Web APIs
WebAPISourceBuffermode
example this snippet sets the sourcebuffer mode to 'sequence' if it is currently set to 'segments', thus setting the play order to the sequence in which media segments are appended.
SourceBuffer.remove() - Web APIs
example tbd.
SourceBuffer.removeAsync() - Web APIs
example this example establishes an asynchronous function, emptysourcebuffer(), which simply clears the contents of the specified sourcebuffer.
SourceBuffer.textTracks - Web APIs
example tbd specifications specification status comment media source extensionsthe definition of 'texttracks' in that specification.
SourceBuffer.timestampOffset - Web APIs
example tbd specifications specification status comment media source extensionsthe definition of 'timestampoffset' in that specification.
SourceBuffer.trackDefaults - Web APIs
example tbd ...
SourceBuffer.updating - Web APIs
example tbd specifications specification status comment media source extensionsthe definition of 'updating' in that specification.
SourceBuffer.videoTracks - Web APIs
example tbd specifications specification status comment media source extensionsthe definition of 'videotracks' in that specification.
SourceBufferList: indexed property getter - Web APIs
example tbd.
SourceBufferList.length - Web APIs
example tbd specifications specification status comment media source extensionsthe definition of 'length' in that specification.
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); recogni...
SpeechGrammar.src - Web APIs
WebAPISpeechGrammarsrc
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 = ...
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.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 speech...
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 ...
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() - Web APIs
examples this code is excerpted from our speech color changer example.
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 speechgramma...
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.continuous - Web APIs
true means continuous, and false means not continuous (single result each time.) examples this code is excerpted from our speech color changer example.
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 ...
SpeechRecognition.grammars - Web APIs
examples this code is excerpted from our speech color changer example.
SpeechRecognition.interimResults - Web APIs
examples this code is excerpted from our speech color changer example.
SpeechRecognition.lang - Web APIs
examples this code is excerpted from our speech color changer example.
SpeechRecognition.maxAlternatives - Web APIs
examples this code is excerpted from our speech color changer example.
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 specifica...
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.onresult - Web APIs
}; examples this code is excerpted from our speech color changer example.
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.serviceURI - Web APIs
examples var recognition = new speechrecognition(); recognition.serviceuri = 'http://www.example.com'; ...
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 even...
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 speci...
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 e...
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 event...
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 speechrecognitio...
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 speechrecognition...
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.
SpeechRecognitionAlternative.confidence - Web APIs
examples this code is excerpted from our speech color changer example.
SpeechRecognitionAlternative.transcript - Web APIs
examples this code is excerpted from our speech color changer example.
SpeechRecognitionAlternative - Web APIs
examples this code is excerpted from our speech color changer example.
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.
SpeechRecognitionErrorEvent - 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 'speechrecognitionerrorevent' in that specification.
SpeechRecognitionEvent.resultIndex - Web APIs
examples recognition.onresult = function(event) { var color = event.results[0][0].transcript; diagnostic.textcontent = 'result received: ' + color + '.'; bg.style.backgroundcolor = color; console.log(event.resultindex); // returns 0 if there is only one result } specifications specification status comment web speech apithe definition of 'resultindex' in that specification.
SpeechRecognitionEvent.results - Web APIs
examples this code is excerpted from our speech color changer example.
SpeechRecognitionEvent - Web APIs
examples this code is excerpted from our speech color changer example.
SpeechRecognitionResult.isFinal - Web APIs
examples recognition.onresult = function(event) { // the speechrecognitionevent results property returns a speechrecognitionresultlist object // the speechrecognitionresultlist object contains speechrecognitionresult objects.
SpeechRecognitionResult.item() - Web APIs
examples this code is excerpted from our speech color changer example.
SpeechRecognitionResult.length - Web APIs
examples this code is excerpted from our speech color changer example.
SpeechRecognitionResult - Web APIs
examples this code is excerpted from our speech color changer example.
SpeechRecognitionResultList.item() - Web APIs
examples this code is excerpted from our speech color changer example.
SpeechRecognitionResultList.length - Web APIs
examples this code is excerpted from our speech color changer example.
SpeechRecognitionResultList - Web APIs
examples this code is excerpted from our speech color changer example.
SpeechSynthesis.cancel() - Web APIs
examples var synth = window.speechsynthesis; var utterance1 = new speechsynthesisutterance('how about we say this now?
SpeechSynthesis.getVoices() - Web APIs
example javascript function populatevoicelist() { if(typeof speechsynthesis === 'undefined') { return; } var voices = speechsynthesis.getvoices(); for(var i = 0; i < voices.length; i++) { var option = document.createelement('option'); option.textcontent = voices[i].name + ' (' + voices[i].lang + ')'; if(voices[i].default) { option.textcontent += ' -- default'; } ...
SpeechSynthesis.onvoiceschanged - Web APIs
}; examples this could be used to populate a list of voices that the user can choose between when the event fires (see our speak easy synthesis demo.) note that firefox doesn't support it at present, and will just return a list of voices when speechsynthesis.getvoices() is fired.
SpeechSynthesis.pause() - Web APIs
examples var synth = window.speechsynthesis; var utterance1 = new speechsynthesisutterance('how about we say this now?
SpeechSynthesis.paused - Web APIs
examples var synth = window.speechsynthesis; synth.pause(); var amipaused = synth.paused; // will return true specifications specification status comment web speech apithe definition of 'paused' in that specification.
SpeechSynthesis.pending - Web APIs
examples var synth = window.speechsynthesis; var utterance1 = new speechsynthesisutterance('how about we say this now?
SpeechSynthesis.resume() - Web APIs
examples var synth = window.speechsynthesis; var utterance1 = new speechsynthesisutterance('how about we say this now?
SpeechSynthesis.speak() - Web APIs
examples this snippet is excerpted from our speech synthesiser demo.
SpeechSynthesis.speaking - Web APIs
examples var synth = window.speechsynthesis; var utterance1 = new speechsynthesisutterance('how about we say this now?
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 - 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 sp...
SpeechSynthesisUtterance.SpeechSynthesisUtterance() - Web APIs
examples the following snippet is excerpted from our speech synthesizer demo.
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 utter...
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 'speec...
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 specificat...
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: 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 specificat...
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 s...
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.appendchil...
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-la...
SpeechSynthesisVoice - Web APIs
examples the following snippet is excerpted from our speech synthesiser demo.
StaticRange.StaticRange() - Web APIs
those node types are node.document_type_node (representing the documenttype node derived from the dtd identified using the doctype preamble in the html, for example) and the attr node describing an attribute of an element on the dom..
StereoPannerNode.pan - Web APIs
example in our stereopannernode example (see source code) html we have a simple <audio> element along with a slider <input> to increase and decrease pan value.
StereoPannerNode - Web APIs
example in our stereopannernode example (see source code) html we have a simple <audio> element along with a slider <input> to increase and decrease pan value.
Storage.length - Web APIs
WebAPIStoragelength
example the following function adds three data items to the local storage for the current domain, then returns the number of items in the storage: function populatestorage() { localstorage.setitem('bgcolor', 'yellow'); localstorage.setitem('font', 'helvetica'); localstorage.setitem('image', 'cats.png'); return localstorage.length; // should return 3 } note: for a real world example, see our web storage demo.
StorageEstimate.quota - Web APIs
example in this example, we obtain the usage estimates and present the percentage of storage capacity currently used to the user.
StorageEstimate.usage - Web APIs
example in this example, we obtain the usage estimates and present the percentage of storage capacity currently used to the user.
StorageManager.estimate() - Web APIs
this variance is based on factors such as: how often the user visits public site popularity data user engagement signals like bookmarking, adding to homescreen, or accepting push notifications example in this example, we obtain the usage estimates and present the percentage of storage capacity currently used to the user.
StorageManager.persist() - Web APIs
example if (navigator.storage && navigator.storage.persist) navigator.storage.persist().then(function(persistent) { if (persistent) console.log("storage will not be cleared except by explicit user action"); else console.log("storage may be cleared by the ua under storage pressure."); }); specifications specification status comment storagethe definition of 'persist' in that specification...
StorageManager.persisted() - Web APIs
example if (navigator.storage && navigator.storage.persist) navigator.storage.persisted().then(function(persistent) { if (persistent) console.log("storage will not be cleared except by explicit user action"); else console.log("storage may be cleared by the ua under storage pressure."); }); specifications specification status comment storagethe definition of 'persisted' in that specification.
Storage API - Web APIs
for example: navigator.storage.estimate().then(estimate => { // estimate.quota is the estimated quota // estimate.usage is the estimated number of bytes used }); specifications specification status comment storage living standard initial definition.
StylePropertyMap.append() - Web APIs
example // tbd specifications specification status comment css typed om level 1the definition of 'append()' in that specification.
StylePropertyMap.clear() - Web APIs
return value undefined example // tbd specifications specification status comment css typed om level 1the definition of 'clear()' in that specification.
StylePropertyMap.delete() - Web APIs
return value undefined example // tbd specifications specification status comment css typed om level 1the definition of 'delete()' in that specification.
StylePropertyMap.set() - Web APIs
return value undefined example // tbd specifications specification status comment css typed om level 1the definition of 'set()' in that specification.
StylePropertyMapReadOnly.entries() - Web APIs
example // tbd specifications specification status comment css typed om level 1the definition of 'entries()' in that specification.
StylePropertyMapReadOnly.forEach() - Web APIs
example // tbd specifications specification status comment css typed om level 1the definition of 'foreach()' in that specification.
StylePropertyMapReadOnly.getAll() - Web APIs
example // tbd specifications specification status comment css typed om level 1the definition of 'getall()' in that specification.
StylePropertyMapReadOnly.has() - Web APIs
example // tbd specifications specification status comment css typed om level 1the definition of 'has()' in that specification.
StylePropertyMapReadOnly.keys() - Web APIs
example // tbd specifications specification status comment css typed om level 1the definition of 'keys()' in that specification.
StylePropertyMapReadOnly.size - Web APIs
example // tbd specifications specification status comment css typed om level 1the definition of 'size' in that specification.
StylePropertyMapReadOnly.values() - Web APIs
example // tbd specifications specification status comment css typed om level 1the definition of 'values()' in that specification.
StylePropertyMapReadOnly - Web APIs
examples we have to have an element to observe: <p> this is a paragraph with some text.
StyleSheet.disabled - Web APIs
syntax bool = stylesheet.disabled example // if the stylesheet is disabled...
Stylesheet.href - Web APIs
WebAPIStyleSheethref
example // on a local machine: <html> <head> <link rel="stylesheet" href="example.css" type="text/css" /> <script> function sref() { alert(document.stylesheets[0].href); } </script> </head> <body> <div class="thunder">thunder</div> <button onclick="sref()">ss</button> </body> </html> // returns "file:////c:/windows/desktop/example.css notes if the style sheet is a linked style sheet, the value of its attribute is its location.
StyleSheet.media - Web APIs
WebAPIStyleSheetmedia
example <!doctype html> <html> <head> <link rel="stylesheet" href="document.css" type="text/css" media="screen" /> <style rel="stylesheet" type="text/css" media="screen, print"> body { background-color: snow; } </style> </head> <body> <script> for (var isheetindex = 0; isheetindex < document.stylesheets.length; isheetindex++) { console.log('document.stylesheets[' + string(isheetindex) + '].media: ' + json.stringify(document.stylesheets[isheetindex].media)); if (isheetindex === 0) document.stylesheets[isheetindex].media.appendmedium('handheld'); if (ishee...
StyleSheet.ownerNode - Web APIs
syntax noderef = stylesheet.ownernode example <html lang="en"> <head> <link rel="stylesheet" href="example.css"> </head> <body> <button onclick="alert(document.stylesheets[0].ownernode)">show example.css’s ownernode</button> </body> </html> // displays "object htmllinkelement" notes for style sheets that are included by other style sheets, such as with @import, the value of this property is null.
StyleSheet.parentStyleSheet - Web APIs
syntax objref = stylesheet.parentstylesheet example // find the top level stylesheet if (stylesheet.parentstylesheet) { sheet = stylesheet.parentstylesheet; } else { sheet = stylesheet; } notes this property returns null if the current stylesheet is a top-level stylesheet or if stylesheet inclusion is not supported.
StyleSheet.type - Web APIs
WebAPIStyleSheettype
syntax string = stylesheet.type example mystylesheet.type = 'text/css'; specifications specification status comment css object model (cssom)the definition of 'stylesheet: type' in that specification.
StyleSheetList - Web APIs
examples get document stylesheet objects with for loop for (let i = 0; i < document.stylesheets.length; i++) { let stylesheet = document.stylesheets[i]; } get all css rules for the document using array methods const allcss = [...document.stylesheets] .map(stylesheet => { try { return [...stylesheet.cssrules] .map(rule => rule.csstext) .join(''); } catch (e) { console.log('access to stylesheet %s is denied.
SubmitEvent.submitter - Web APIs
examples in this example, a shopping cart may have an assortment of different submit buttons depending on factors such as the user's settings, the shop's settings, and any minimum or maximum shopping card totals established by the payment processors.
SubmitEvent - Web APIs
examples in this example, a shopping cart may have an assortment of different submit buttons depending on factors such as the user's settings, the shop's settings, and any minimum or maximum shopping card totals established by the payment processors.
SubtleCrypto.decrypt() - Web APIs
examples note: you can try the working examples on github.
SubtleCrypto.encrypt() - Web APIs
examples note: you can try the working examples out on github.
SubtleCrypto.generateKey() - Web APIs
examples note: you can try the working examples on github.
SubtleCrypto.sign() - Web APIs
WebAPISubtleCryptosign
examples note: you can try the working examples out on github.
SubtleCrypto.verify() - Web APIs
examples note: you can try the working examples out on github.
SubtleCrypto - Web APIs
this is useful if, for example, you want to derive an encryption key from a password and later derive the same key from the same password to decrypt the data.
Text() - Web APIs
WebAPITextText
syntax text1 = new text(); // create an empty text node text2 = new text("this is a text node"); example let text = new text("test"); specifications specification status comment domthe definition of 'text()' in that specification.
Text.replaceWholeText() - Web APIs
syntax replacementnode = textnode.replacewholetext(content) example see the example for the text.wholetext property.
Text.splitText() - Web APIs
WebAPITextsplitText
example in this example, the text of a <p> is split into two text nodes, and a <u> is inserted between them.
Text.wholeText - Web APIs
WebAPITextwholeText
syntax str = textnode.wholetext; notes and example suppose you have the following simple paragraph within your webpage (with some whitespace added to aid formatting throughout the code samples here), whose dom node is stored in the variable para: <p>thru-hiking is great!
TextDecoder() - Web APIs
example var textdecoder1 = new textdecoder("iso-8859-2"); var textdecoder2 = new textdecoder(); var textdecoder3 = new textdecoder("csiso2022kr", {fatal: true}); // allows encodingerror exception to be thrown.
TextDecoder.prototype.decode() - Web APIs
example this example encodes and decodes the euro symbol, €.
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 - Web APIs
example const encoder = new textencoder() const view = encoder.encode('€') console.log(view); // uint8array(3) [226, 130, 172] constructor textencoder() returns a newly constructed textencoder that will generate a byte stream with utf-8 encoding.
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.width - Web APIs
WebAPITextMetricswidth
examples given this <canvas> element: <canvas id="canvas"></canvas> ...
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 t...
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.length - Web APIs
example this snippet gets the number of text tracks in the first media element found in the dom by queryselector().
TextTrackList.onaddtrack - Web APIs
example this snippet establishes a handler for the addtrack event that calls a function, addtotracklist(), passing in the videotrack object representing the newly-added track.
TextTrackList.onchange - Web APIs
syntax texttracklist.onchange = eventhandler; example this snippet establishes a handler for the change event that looks at each of the tracks in the list, calling a function to update the state of a user interface control that indicates the current state of the track.
TextTrackList.onremovetrack - Web APIs
example this simple example just fetches the current number of text tracks in the first media element whenever a track is removed from the media element.
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...
TimeRanges.end() - Web APIs
WebAPITimeRangesend
example given a video element with the id "myvideo": var v = document.getelementbyid("myvideo"); var buf = v.buffered; var numranges = buf.length; if (buf.length == 1) { // only one range if (buf.start(0) == 0 && buf.end(0) == v.duration) { // the one range starts at the beginning and ends at // the end of the video, so the whole thing is loaded } } this example looks at the time ranges and looks to see if the entire video has been loaded.
TimeRanges.length - Web APIs
WebAPITimeRangeslength
syntax length = timeranges.length; example given a video element with the id "myvideo": var v = document.getelementbyid("myvideo"); var buf = v.buffered; var numranges = buf.length; if (buf.length == 1) { // only one range if (buf.start(0) == 0 && buf.end(0) == v.duration) { // the one range starts at the beginning and ends at // the end of the video, so the whole thing is loaded } } this example looks at the time ranges and looks to see if the entire video has been loaded.
TimeRanges.start() - Web APIs
WebAPITimeRangesstart
example given a video element with the id "myvideo": var v = document.getelementbyid("myvideo"); var buf = v.buffered; var numranges = buf.length; if (buf.length == 1) { // only one range if (buf.start(0) == 0 && buf.end(0) == v.duration) { // the one range starts at the beginning and ends at // the end of the video, so the whole thing is loaded } } this example looks at the time ranges and looks to see if the entire video has been loaded.
msManipulationViewsEnabled - Web APIs
example using a json file: { msmanipulationviewsenabled: true, } see also touch api microsoft api extensions ...
Touch() - Web APIs
WebAPITouchTouch
(for example, the user agent may use the rotationangle value from the previous touch event, to avoid sudden changes.).
Touch.identifier - Web APIs
WebAPITouchidentifier
example someelement.addeventlistener('touchmove', function(e) { // iterate through the list of touch points that changed // since the last event and print each touch point's identifier.
Touch.pageX - Web APIs
WebAPITouchpageX
example this example illustrates how to access the touch object's touch.pagex and touch.pagey properties.
Touch.pageY - Web APIs
WebAPITouchpageY
example this example illustrates how to access the touch object's touch.pagex and touch.pagey properties.
Touch.screenX - Web APIs
WebAPITouchscreenX
example this example illustrates how to access the touch object's touch.screenx and touch.screeny properties.
Touch.screenY - Web APIs
WebAPITouchscreenY
example the touch.screenx example includes an example of this property's usage.
Touch.target - Web APIs
WebAPITouchtarget
example this example illustrates how to access the touch object's touch.target property.
Touch - Web APIs
WebAPITouch
note: many of the properties' values are hardware-dependent; for example, if the device doesn't have a way to detect the amount of pressure placed on the surface, the force value will always be 0.
TouchEvent.altKey - Web APIs
WebAPITouchEventaltKey
example this example illustrates how to access the touchevent key modifier properties: touchevent.altkey, touchevent.ctrlkey, touchevent.metakey and touchevent.shiftkey.
TouchEvent.changedTouches - Web APIs
example this example illustrates the touchevent object's touchevent.changedtouches property.
TouchEvent.ctrlKey - Web APIs
example the touchevent.altkey example includes an example of this property's usage.
TouchEvent.metaKey - Web APIs
example the touchevent.altkey example includes an example of this property's usage.
TouchEvent.shiftKey - Web APIs
example the touchevent.altkey example includes an example of this property's usage.
TouchEvent.targetTouches - Web APIs
example this example illustrates the touchevent object's touchevent.targettouches property.
TouchEvent.touches - Web APIs
example this example illustrates the touchevent object's touchevent.touches property.
TouchList.item() - Web APIs
WebAPITouchListitem
example this code example illustrates the use of the touchlist interface's item method and the length property.
TouchList.length - Web APIs
WebAPITouchListlength
example this code example illustrates the use of the touchlist interface's item method and the length property.
TrackDefault.TrackDefault() - Web APIs
example tbd ...
TrackDefault.byteStreamTrackID - Web APIs
example tbd ...
TrackDefault.kinds - Web APIs
example tbd ...
TrackDefault.label - Web APIs
example tbd ...
TrackDefault.language - Web APIs
example tbd ...
TrackDefault.type - Web APIs
WebAPITrackDefaulttype
example tbd ...
TrackDefaultList.TrackDefault() - Web APIs
example tbd.
TrackDefaultList.TrackDefaultList() - Web APIs
example tbd.
TrackDefaultList.length - Web APIs
example tbd ...
TrackDefaultList - Web APIs
[].) examples tbd.
TrackEvent - Web APIs
example this example sets up a function, handletrackevent(), which is callled for any addtrack or removetrack event on the first <video> element found in the document.
TreeWalker.currentNode - Web APIs
syntax node = treewalker.currentnode; treewalker.currentnode = node; example var treewalker = document.createtreewalker( document.body, nodefilter.show_element, { acceptnode: function(node) { return nodefilter.filter_accept; } }, false ); root = treewalker.currentnode; // the root element as it is the first element!
TreeWalker.expandEntityReferences - Web APIs
syntax expand = treewalker.expandentityreferences; example var treewalker = document.createtreewalker( document.body, nodefilter.show_element, { acceptnode: function(node) { return nodefilter.filter_accept; } }, false ); expand = treewalker.expandentityreferences; specifications document object model (dom) level 2 traversal and range specificationthe definition of 'treewalker.expandentityreferences' in that specification.
TreeWalker.filter - Web APIs
WebAPITreeWalkerfilter
syntax nodefilter = treewalker.filter; example var treewalker = document.createtreewalker( document.body, nodefilter.show_element, { acceptnode: function(node) { return nodefilter.filter_accept; } }, false ); nodefilter = treewalker.filter; // document.body in this case specifications specification status comment domthe definition of 'treewalker.filter' in that specification.
TreeWalker.firstChild() - Web APIs
syntax node = treewalker.firstchild; example var treewalker = document.createtreewalker( document.body, nodefilter.show_element, { acceptnode: function(node) { return nodefilter.filter_accept; } }, false ); var node = treewalker.firstchild(); // returns the first child of the root element, or null if none specifications specification status comment domthe definition of 'treewalker.firstchild' in that specification.
TreeWalker.lastChild() - Web APIs
syntax node = treewalker.lastchild(); example var treewalker = document.createtreewalker( document.body, nodefilter.show_element, { acceptnode: function(node) { return nodefilter.filter_accept; } }, false ); var node = treewalker.lastchild(); // returns the last visible child of the root element specifications specification status comment domthe definition of 'treewalker.lastchild' in that specification.
TreeWalker.nextNode() - Web APIs
syntax node = treewalker.nextnode(); example var treewalker = document.createtreewalker( document.body, nodefilter.show_element, { acceptnode: function(node) { return nodefilter.filter_accept; } }, false ); var node = treewalker.nextnode(); // returns the first child of root, as it is the next node in document order specifications specification status comment domthe definition of 'treewalker.nextnode' in that specification.
TreeWalker.nextSibling() - Web APIs
syntax node = treewalker.nextsibling(); example var treewalker = document.createtreewalker( document.body, nodefilter.show_element, { acceptnode: function(node) { return nodefilter.filter_accept; } }, false ); treewalker.firstchild(); var node = treewalker.nextsibling(); // returns null if the first child of the root element has no sibling specifications specification status comment domthe definition of 'treewalker.nextsibling' in that specification.
TreeWalker.parentNode() - Web APIs
syntax node = treewalker.parentnode(); example var treewalker = document.createtreewalker( document.body, nodefilter.show_element, { acceptnode: function(node) { return nodefilter.filter_accept; } }, false ); var node = treewalker.parentnode(); // returns null as there is no parent specifications specification status comment domthe definition of 'treewalker.parentnode' in that specification.
TreeWalker.previousNode() - Web APIs
syntax node = treewalker.previousnode(); example var treewalker = document.createtreewalker( document.body, nodefilter.show_element, { acceptnode: function(node) { return nodefilter.filter_accept; } }, false ); var node = treewalker.previousnode(); // returns null as there is no parent specifications specification status comment domthe definition of 'treewalker.previousnode' in that specification.
TreeWalker.previousSibling() - Web APIs
syntax node = treewalker.previoussibling(); example var treewalker = document.createtreewalker( document.body, nodefilter.show_element, { acceptnode: function(node) { return nodefilter.filter_accept; } }, false ); var node = treewalker.previoussibling(); // returns null as there is no previous sibiling specifications specification status comment domthe definition of 'treewalker.previoussibling' in that specification.
TreeWalker.root - Web APIs
WebAPITreeWalkerroot
syntax root = treewalker.root; example var treewalker = document.createtreewalker( document.body, nodefilter.show_element, { acceptnode: function(node) { return nodefilter.filter_accept; } }, false ); root = treewalker.root; // document.body in this case specifications specification status comment domthe definition of 'treewalker.root' in that specification.
TreeWalker.whatToShow - Web APIs
syntax nodetypes = treewalker.whattoshow; example var treewalker = document.createtreewalker( document.body, nodefilter.show_element + nodefilter.show_comment + nodefilter.show_text, { acceptnode: function(node) { return nodefilter.filter_accept; } }, false ); if( (treewalker.whattoshow == nodefilter.show_all) || (treewalker.whattoshow % (nodefilter.show_comment*2)) >= nodefilter.show_comment) { // treewalker will show c...
UIEvent.initUIEvent() - Web APIs
example var e = document.createevent("uievent"); // creates a click event that bubbles, can be cancelled, // and with its view and detail property initialized to window and 1, // respectively e.inituievent("click", true, true, window, 1); specifications specification status comment document object model (dom) level 3 events specificationthe definition of 'uievent.inituievent()...
UIEvent.layerX - Web APIs
WebAPIUIEventlayerX
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.laye...
UIEvent.layerY - Web APIs
WebAPIUIEventlayerY
example <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
WebAPIUIEventpageX
examples for an example, see the documentation for the standard mouseevent.pagex property, which you should use instead.
UIEvent.pageY - Web APIs
WebAPIUIEventpageY
example <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.layery; } </script> <style type="text/css...
URL.createObjectURL() - Web APIs
examples see using object urls to display images.
URL.hash - Web APIs
WebAPIURLhash
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
WebAPIURLhost
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
WebAPIURLhostname
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
WebAPIURLhref
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
WebAPIURLorigin
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
WebAPIURLpassword
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
WebAPIURLpathname
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
WebAPIURLport
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
WebAPIURLprotocol
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.revokeObjectURL() - Web APIs
examples see using object urls to display images.
URL.search - Web APIs
WebAPIURLsearch
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
WebAPIURLsearch?q=123
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
WebAPIURLsearchParams
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
WebAPIURLtoJSON
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
WebAPIURLtoString
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
WebAPIURLusername
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.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.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.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.
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.
USB.getDevices() - Web APIs
WebAPIUSBgetDevices
example the following example logs the product name and serial number of paired devices to the console.
USBDevice.claimInterface() - Web APIs
example the following example shows claiminterface() in the context of connecting to a usb device.
USBDevice.clearHalt() - Web APIs
example the following example shows how to test for and clear a 'stall' condition in the result of a data transfer.
USBDevice.configuration - Web APIs
example the following example uses this property to test for the existence of a usbconfiguration property to select a configuration before claiming an interface.
USBDevice.opened - Web APIs
WebAPIUSBDeviceopened
example this example is for a hypothetical usb device with a multi-colored led.
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 ...
VTTCue - Web APIs
WebAPIVTTCue
example html <video controls src="https://udn.realityripple.com/samples/c6/f8a3489533.webm"></video> css video { width: 320px; height: 180px; } javascript let video = document.queryselector('video'); video.addeventlistener('loadedmetadata', () => { const track = video.addtexttrack("captions", "简体中文subtitles", "zh_cn"); track.mode = "showing"; const cuecn = new vttcue(0, 2.500, '�...
VTTRegion - Web APIs
WebAPIVTTRegion
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-d...
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...
VideoPlaybackQuality.corruptedVideoFrames - Web APIs
example this example determines the percentage of frames which have been corrupted, and if the value is greater than 5%, calls a funciton called downgradevideo() that would be implemented to switch to a different video that might tax the network less.
VideoPlaybackQuality.creationTime - Web APIs
example this example calls getvideoplaybackquality() to obtain a videoplaybackquality object, then determines what percentage of frames have been lost by either corruption or being dropped.
VideoPlaybackQuality.droppedVideoFrames - Web APIs
example this example calls getvideoplaybackquality() to obtain a videoplaybackquality object, then determines what percentage of frames have been dropped.
VideoPlaybackQuality.totalFrameDelay - Web APIs
syntax value = videoplaybackquality.totalframedelay; example var videoelt = document.getelementbyid('my_vid'); var quality = videoelt.getvideoplaybackquality(); alert(quality.totalframedelay); ...
VideoPlaybackQuality.totalVideoFrames - Web APIs
example this example calls getvideoplaybackquality() to obtain a videoplaybackquality object, then determines what percentage of frames have been lost by either corruption or being dropped.
VideoTrack.kind - Web APIs
WebAPIVideoTrackkind
this might be used to contain the director's commentary track on a movie, for example.
Videotrack.language - Web APIs
for example, if the primary language used in the track is united states english, this value would be "en-us".
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.length - Web APIs
example this snippet gets the number of video tracks in the first <video> element found in the dom by queryselector().
VideoTrackList.onaddtrack - Web APIs
example this snippet establishes a handler for the addtrack event that calls a function, addtotracklist(), passing in the videotrack object representing the newly-added track.
VideoTrackList.onremovetrack - Web APIs
example this simple example just fetches the current number of video tracks in the media element whenever a track is removed from the media element.
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.onresize - Web APIs
} examples visualviewport.onresize = function(e) { ...
VisualViewport.onscroll - Web APIs
} examples visualviewport.onscroll = function(e) { ...
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() { ...
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 - 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 tha...
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 specifi...
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 specif...
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 spe...
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_...
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 = ...
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.drawBuffersWEBGL() - Web APIs
examples see webgl_draw_buffers for more context with this example code.
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.request() - Web APIs
WebAPIWakeLockrequest
examples the following asynchronous function requests a wakelocksentinel object.
WakeLock - Web APIs
WebAPIWakeLock
examples the following asynchronous function requests a wakelocksentinel object.
WakeLockSentinel.release() - Web APIs
examples in this example, when a user clicks a button the wakelocksentinel is released.
WakeLockSentinel.type - Web APIs
examples this example shows an asynchronous function that acquires a wakelocksentinel, then logs the type to the console.
WakeLockSentinel - Web APIs
examples in this example we create an asynchronous function which requests a wakelocksentinel.
WebGL2RenderingContext.beginQuery() - Web APIs
examples var query = gl.createquery(); gl.beginquery(gl.any_samples_passed, query); // ...
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.bindBufferBase() - Web APIs
examples gl.bindbufferbase(gl.transform_feedback_buffer, 0, buffer); specifications specification status comment webgl 2.0the definition of 'bindbufferbase' in that specification.
WebGL2RenderingContext.bindBufferRange() - Web APIs
examples gl.bindbufferrange(gl.transform_feedback_buffer, 1, buffer, 0, 4); specifications specification status comment webgl 2.0the definition of 'bindbufferrange' in that specification.
WebGL2RenderingContext.bindSampler() - Web APIs
examples var sampler = gl.createsampler(); gl.bindsampler(0, sampler); specifications specification status comment webgl 2.0the definition of 'bindsampler' 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.bindVertexArray() - Web APIs
examples var vao = gl.createvertexarray(); gl.bindvertexarray(vao); // ...
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.compressedTexSubImage3D() - Web APIs
examples gl.compressedtexsubimage3d(gl.texture_3d, 0, 0, 0, 512, 512, 512, gl.compressed_r11_eac, texturedata); specifications specification status comment webgl 2.0the definition of 'compressedtexsubimage3d' in that specification.
WebGL2RenderingContext.copyBufferSubData() - Web APIs
examples var srcbuffer = gl.createbuffer(); var dstbuffer = gl.createbuffer(); var data = new float32array(vertices); var length = vertices.length * 4; gl.bindbuffer(gl.array_buffer, srcbuffer); gl.bufferdata(gl.array_buffer, data, gl.static_draw); gl.bindbuffer(gl.copy_read_buffer, srcbuffer); gl.bindbuffer(gl.array_buffer, dstbuffer); gl.bufferdata(gl.array_buffer, new float32array(length), gl.stat...
WebGL2RenderingContext.copyTexSubImage3D() - Web APIs
examples gl.copytexsubimage3d(gl.texture_3d, 0, 0, 0, 0, 0, 0, 16, 16); specifications specification status comment webgl 2.0the definition of 'copytexsubimage3d' in that specification.
WebGL2RenderingContext.createQuery() - Web APIs
examples gl must be a webgl2renderingcontext.
WebGL2RenderingContext.createSampler() - Web APIs
examples gl must be a webgl2renderingcontext.
WebGL2RenderingContext.createTransformFeedback() - Web APIs
examples gl must be a webgl2renderingcontext.
WebGL2RenderingContext.createVertexArray() - Web APIs
examples var vao = gl.createvertexarray(); gl.bindvertexarray(vao); // ...
WebGL2RenderingContext.deleteQuery() - Web APIs
examples gl must be a webgl2renderingcontext.
WebGL2RenderingContext.deleteSampler() - Web APIs
examples gl must be a webgl2renderingcontext.
WebGL2RenderingContext.deleteSync() - Web APIs
examples gl must be a webgl2renderingcontext.
WebGL2RenderingContext.deleteTransformFeedback() - Web APIs
examples gl must be a webgl2renderingcontext.
WebGL2RenderingContext.deleteVertexArray() - Web APIs
examples var vao = gl.createvertexarray(); gl.bindvertexarray(vao); // ...
WebGL2RenderingContext.drawArraysInstanced() - Web APIs
examples gl.drawarraysinstanced(gl.points, 0, 8, 4); specifications specification status comment webgl 2.0the definition of 'drawarraysinstanced' in that specification.
WebGL2RenderingContext.drawBuffers() - Web APIs
examples gl.drawbuffers([gl.none, gl.color_attachment1]); specifications specification status comment webgl 2.0the definition of 'drawbuffers' in that specification.
WebGL2RenderingContext.drawElementsInstanced() - Web APIs
examples gl.drawelementsinstanced(gl.points, 2, gl.unsigned_short, 0, 4); specifications specification status comment webgl 2.0the definition of 'drawelementsinstanced' in that specification.
WebGL2RenderingContext.drawRangeElements() - Web APIs
examples gl.drawrangeelements(gl.points, 0, 7, 8, gl.unsigned_byte, 0); specifications specification status comment webgl 2.0the definition of 'drawrangeelements' in that specification.
WebGL2RenderingContext.endQuery() - Web APIs
examples var query = gl.createquery(); gl.beginquery(gl.any_samples_passed, query); // ...
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.fenceSync() - Web APIs
examples gl must be a webgl2renderingcontext.
WebGL2RenderingContext.framebufferTextureLayer() - Web APIs
examples gl.framebuffertexturelayer(gl.framebuffer, gl.color_attachment0, texture, 0, 8); specifications specification status comment webgl 2.0the definition of 'framebuffertexturelayer' in that specification.
WebGL2RenderingContext.getActiveUniformBlockName() - Web APIs
examples var blockname = gl.getactiveuniformblockname(program, 0); specifications specification status comment webgl 2.0the definition of 'getactiveuniformblockname' in that specification.
WebGL2RenderingContext.getActiveUniformBlockParameter() - Web APIs
examples var blocksize = gl.getactiveuniformblockparameter(program, blockindex, gl.uniform_block_data_size); specifications specification status comment webgl 2.0the definition of 'getactiveuniformblockparameter' 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 'getbuffersubda...
WebGL2RenderingContext.getFragDataLocation() - Web APIs
examples // program is a linked webglprogram gl.getfragdatalocation(program, 'fragcolor'); specifications specification status comment webgl 2.0the definition of 'getfragdatalocation' in that specification.
WebGL2RenderingContext.getIndexedParameter() - Web APIs
examples var binding = gl.getindexedparameter(gl.transform_feedback_buffer_binding, 0); specifications specification status comment webgl 2.0the definition of 'getindexedparameter' in that specification.
WebGL2RenderingContext.getInternalformatParameter() - Web APIs
examples var samples = gl.getinternalformatparameter(gl.renderbuffer, gl.rgba8, gl.samples); specifications specification status comment webgl 2.0the definition of 'getinternalformatparameter' in that specification.
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.getSamplerParameter() - Web APIs
examples var sampler = gl.createsampler(); gl.getsamplerparameter(sampler, gl.texture_compare_func); specifications specification status comment webgl 2.0the definition of 'getsamplerparameter' in that specification.
WebGL2RenderingContext.getSyncParameter() - Web APIs
examples var sync = gl.fencesync(gl.sync_gpu_commands_complete, 0); gl.getsyncparameter(sync, gl.sync_status); specifications specification status comment webgl 2.0the definition of 'getsyncparameter' in that specification.
WebGL2RenderingContext.getTransformFeedbackVarying() - Web APIs
examples activeinfo = gl.gettransformfeedbackvarying(program, 0); specifications specification status comment webgl 2.0the definition of 'gettransformfeedbackvarying' in that specification.
WebGL2RenderingContext.getUniformBlockIndex() - Web APIs
examples // assuming a shader with the following declaration: // uniform ubodata { // mat4 foo; // } instancename; // use the block name, not the instance name: var blockindex = gl.getuniformblockindex(program, 'ubodata'); specifications specification status comment webgl 2.0the definition of 'getuniformblockindex' in that specification.
WebGL2RenderingContext.getUniformIndices() - Web APIs
examples var uniformindices = gl.getuniformindices(program, ['ubored', 'ubogreen', 'uboblue']); specifications specification status comment webgl 2.0the definition of 'getuniformindices' in that specification.
WebGL2RenderingContext.invalidateFramebuffer() - Web APIs
examples gl.invalidateframebuffer(gl.read_framebuffer, [gl.color_attachment0, gl.color_attachment1]); specifications specification status comment webgl 2.0the definition of 'invalidateframebuffer' in that specification.
WebGL2RenderingContext.invalidateSubFramebuffer() - Web APIs
examples gl.invalidatesubframebuffer(gl.read_framebuffer, [gl.color_attachment0, gl.color_attachment1], 0, 0, 256, 256); specifications specification status comment webgl 2.0the definition of 'invalidatesubframebuffer' in that specification.
WebGL2RenderingContext.isQuery() - Web APIs
examples gl must be a webgl2renderingcontext.
WebGL2RenderingContext.isSampler() - Web APIs
examples gl must be a webgl2renderingcontext.
WebGL2RenderingContext.isSync() - Web APIs
examples gl must be a webgl2renderingcontext.
WebGL2RenderingContext.isTransformFeedback() - Web APIs
examples gl must be a webgl2renderingcontext.
WebGL2RenderingContext.isVertexArray() - Web APIs
examples var vao = gl.createvertexarray(); gl.bindvertexarray(vao); // ...
WebGL2RenderingContext.pauseTransformFeedback() - Web APIs
examples var transformfeedback = gl.createtransformfeedback(); gl.bindtransformfeedback(gl.transform_feedback, transformfeedback); gl.begintransformfeedback(gl.triangles); gl.pausetransformfeedback(); //...
WebGL2RenderingContext.readBuffer() - Web APIs
examples gl.readbuffer(gl.color_attachment0); specifications specification status comment webgl 2.0the definition of 'readbuffer' in that specification.
WebGL2RenderingContext.renderbufferStorageMultisample() - Web APIs
examples gl.renderbufferstoragemultisample(gl.renderbuffer, 4, gl.rbga4, 256, 256); specifications specification status comment webgl 2.0the definition of 'glrenderbufferstoragemultisample' in that specification.
WebGL2RenderingContext.resumeTransformFeedback() - Web APIs
examples var transformfeedback = gl.createtransformfeedback(); gl.bindtransformfeedback(gl.transform_feedback, transformfeedback); gl.begintransformfeedback(gl.triangles); gl.pausetransformfeedback(); //...
WebGL2RenderingContext.samplerParameter[if]() - Web APIs
examples var sampler = gl.createsampler(); gl.samplerparameteri(sampler, gl.texture_mag_filter, gl.nearest); specifications the compatibility table in this page is generated from structured data.
WebGL2RenderingContext.texImage3D() - Web APIs
examples gl.teximage3d(gl.texture_3d, 0, // level gl.rgba, // internalformat 1, // width 1, // height 1, // depth 0, ...
WebGL2RenderingContext.texStorage2D() - Web APIs
examples gl.texstorage2d(gl.texture_2d, 1, gl.rgb8, 256, 256); specifications specification status comment webgl 2.0the definition of 'texstorage2d' in that specification.
WebGL2RenderingContext.texStorage3D() - Web APIs
examples gl.texstorage3d(gl.texture_3d, 1, gl.rgb8, 256, 256, 256); specifications specification status comment webgl 2.0the definition of 'texstorage3d' 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 commen...
WebGL2RenderingContext.uniformBlockBinding() - Web APIs
examples gl.uniformblockbinding(program, 0, 1); specifications specification status comment webgl 2.0the definition of 'uniformblockbinding' in that specification.
WebGL2RenderingContext.uniformMatrix[234]x[234]fv() - Web APIs
examples gl.uniformmatrix2x3fv(loc, false, [1, 2, 3, 4, 5, 6]); specifications specification status comment webgl 2.0the definition of 'uniformmatrix' in that specification.
WebGL2RenderingContext.vertexAttribDivisor() - Web APIs
examples gl.vertexattribdivisor(0, 2); specifications specification status comment webgl 2.0the definition of 'vertexattribdivisor' in that specification.
WebGL2RenderingContext.vertexAttribI4[u]i[v]() - Web APIs
examples gl.vertexattribi4i(a_foobar, 10); specifications specification status comment webgl 2.0the definition of 'vertexattribi' in that specification.
WebGL2RenderingContext.vertexAttribIPointer() - Web APIs
examples linear blend skinning //describe the layout of the buffer: //1.
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.
WebGL2RenderingContext - Web APIs
the webgl tutorial has more information, examples, and resources on how to get started with webgl.
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 "webglcon...
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.
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.activeTexture() - Web APIs
examples the following call selects gl.texture1 as the current texture.
WebGLRenderingContext.attachShader() - Web APIs
examples the following code attaches pre-existing shaders to a webglprogram.
WebGLRenderingContext.bindAttribLocation() - Web APIs
examples gl.bindattriblocation(program, colorlocation, 'vcolor'); specifications specification status comment webgl 1.0the definition of 'bindattriblocation' 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.blendColor() - Web APIs
examples to set the blend color, use: gl.blendcolor(0, 0.5, 1, 1); to get the blend color, query the blend_color constant which returns a float32array.
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.blendFunc() - Web APIs
examples to use the blend function, you first have to activate blending with webglrenderingcontext.enable() with the argument gl.blend.
WebGLRenderingContext.blendFuncSeparate() - Web APIs
examples to use the blend function, you first have to activate blending with webglrenderingcontext.enable() with the argument gl.blend.
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 th...
WebGLRenderingContext.canvas - Web APIs
examples canvas element given this <canvas> element: <canvas id="canvas"></canvas> you can get back a reference to it from the webglrenderingcontext using the canvas property: var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); gl.canvas; // htmlcanvaselement offscreen canvas example using the experimental offscreencanvas object.
WebGLRenderingContext.checkFramebufferStatus() - Web APIs
examples var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); var framebuffer = gl.createframebuffer(); // ...
WebGLRenderingContext.clear() - Web APIs
examples the clear() method accepts multiple values.
WebGLRenderingContext.clearColor() - Web APIs
examples gl.clearcolor(1, 0.5, 0.5, 3); to get the current clear color, query the color_clear_value constant which returns a float32array.
WebGLRenderingContext.clearDepth() - Web APIs
examples gl.cleardepth(0.5); to get the current depth clear value, query the depth_clear_value constant.
WebGLRenderingContext.clearStencil() - Web APIs
examples gl.clearstencil(1); to get the current stencil clear value, query the stencil_clear_value constant.
WebGLRenderingContext.colorMask() - Web APIs
examples gl.colormask(true, true, true, false); to get the current color mask, query the color_writemask constant which returns an array.
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, g...
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.copyTexImage2D() - Web APIs
examples gl.copyteximage2d(gl.texture_2d, 0, gl.rgba, 0, 0, 512, 512, 0); specifications specification status comment webgl 1.0the definition of 'copyteximage2d' in that specification.
WebGLRenderingContext.copyTexSubImage2D() - Web APIs
examples gl.copytexsubimage2d(gl.texture_2d, 0, 0,0, 0, 0, 16, 16); specifications specification status comment webgl 1.0the definition of 'copytexsubimage2d' in that specification.
WebGLRenderingContext.createBuffer() - Web APIs
examples creating a buffer var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); var buffer = gl.createbuffer(); specifications specification status comment webgl 1.0the definition of 'createbuffer' in that specification.
WebGLRenderingContext.createFramebuffer() - Web APIs
examples creating a frame buffer var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); var framebuffer = gl.createframebuffer(); specifications specification status comment webgl 1.0the definition of 'createframebuffer' in that specification.
WebGLRenderingContext.createRenderbuffer() - Web APIs
examples creating a render buffer var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); var renderbuffer = gl.createrenderbuffer(); specifications specification status comment webgl 1.0the definition of 'createrenderbuffer' in that specification.
WebGLRenderingContext.createShader() - Web APIs
syntax webglshader gl.createshader(type); parameters type either gl.vertex_shader or gl.fragment_shader examples see webglshader for usage and examples.
WebGLRenderingContext.createTexture() - Web APIs
examples see also the webgl tutorial on using textures in webgl.
WebGLRenderingContext.cullFace() - Web APIs
examples polygon culling is disabled by default.
WebGLRenderingContext.deleteBuffer() - Web APIs
examples deleting a buffer var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); var buffer = gl.createbuffer(); // ...
WebGLRenderingContext.deleteFramebuffer() - Web APIs
examples deleting a frame buffer var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); var framebuffer = gl.createframebuffer(); // ...
WebGLRenderingContext.deleteProgram() - Web APIs
examples deleting a program var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); var program = gl.createprogram(); // ...
WebGLRenderingContext.deleteRenderbuffer() - Web APIs
examples deleting a renderbuffer var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); var renderbuffer = gl.createrenderbuffer(); // ...
WebGLRenderingContext.deleteShader() - Web APIs
examples deleting a shader gl.deleteshader(shader); specifications specification status comment webgl 1.0the definition of 'deleteshader' in that specification.
WebGLRenderingContext.deleteTexture() - Web APIs
examples deleting a texture var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); var texture = gl.createtexture(); // ...
WebGLRenderingContext.depthFunc() - Web APIs
examples the depth testing is disabled by default.
WebGLRenderingContext.depthMask() - Web APIs
examples gl.depthmask(false); to get the current depth mask, query the depth_writemask constant which returns a boolean.
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.disableVertexAttribArray() - Web APIs
examples gl.disablevertexattribarray(0); specifications specification status comment webgl 1.0the definition of 'disablevertexattribarray' in that specification.
WebGLRenderingContext.drawArrays() - Web APIs
examples gl.drawarrays(gl.points, 0, 8); specifications specification status comment webgl 1.0the definition of 'drawarrays' in that specification.
WebGLRenderingContext.drawElements() - Web APIs
examples gl.drawelements(gl.points, 8, gl.unsigned_byte, 0); specifications specification status comment webgl 1.0the definition of 'drawelements' 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.framebufferRenderbuffer() - Web APIs
examples gl.framebufferrenderbuffer(gl.framebuffer, gl.color_attachment0, gl.renderbuffer, renderbuffer); specifications specification status comment webgl 1.0the definition of 'framebufferrenderbuffer' in that specification.
WebGLRenderingContext.framebufferTexture2D() - Web APIs
examples gl.framebuffertexture2d(gl.framebuffer, gl.color_attachment0, gl.texture_2d, texture, 0); specifications specification status comment webgl 1.0the definition of 'framebuffertexture2d' in that specification.
WebGLRenderingContext.frontFace() - Web APIs
examples gl.frontface(gl.cw); specifications specification status comment webgl 1.0the definition of 'frontface' in that specification.
WebGLRenderingContext.generateMipmap() - Web APIs
examples gl.generatemipmap(gl.texture_2d); specifications specification status comment webgl 1.0the definition of 'generatemipmap' 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.getAttribLocation() - Web APIs
examples gl.getattriblocation(program, 'vcolor'); specifications specification status comment webgl 1.0the definition of 'getattriblocation' in that specification.
WebGLRenderingContext.getBufferParameter() - Web APIs
examples gl.getbufferparameter(gl.array_buffer, gl.buffer_size); specifications specification status comment webgl 1.0the definition of 'getbufferparameter' 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", premultip...
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.getExtension() - Web APIs
examples once a webgl extension is enabled, you are able to use the methods, properties or constants that this extension object provides.
WebGLRenderingContext.getFramebufferAttachmentParameter() - Web APIs
examples gl.getframebufferattachmentparameter(gl.framebuffer, gl.color_attachment0, gl.framebuffer_attachment_object_type); specifications specification status comment webgl 1.0the definition of 'getframebufferattachmentparameter' 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.getProgramParameter() - Web APIs
examples gl.getprogramparameter(program, gl.delete_status); specifications specification status comment webgl 1.0the definition of 'getprogramparameter' in that specification.
WebGLRenderingContext.getRenderbufferParameter() - Web APIs
examples gl.getrenderbufferparameter(gl.renderbuffer, gl.renderbuffer_width); specifications specification status comment webgl 1.0the definition of 'getrenderbufferparameter' in that specification.
WebGLRenderingContext.getShaderInfoLog() - Web APIs
examples checking compilation messages /* load shader source code.
WebGLRenderingContext.getShaderParameter() - Web APIs
examples gl.getshaderparameter(shader, gl.shader_type); specifications specification status comment webgl 1.0the definition of 'getshaderparameter' in that specification.
WebGLRenderingContext.getShaderPrecisionFormat() - Web APIs
examples the following code gets the precision format of a gl.vertex_shader with a gl.medium_float precision type.
WebGLRenderingContext.getShaderSource() - 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 'getshadersource' in that specification.
WebGLRenderingContext.getSupportedExtensions() - Web APIs
examples var canvas = document.getelementbyid('canvas'); gl = canvas.getcontext('webgl'); var extensions = gl.getsupportedextensions(); // array [ 'angle_instanced_arrays', 'ext_blend_minmax', ...
WebGLRenderingContext.getTexParameter() - Web APIs
examples gl.gettexparameter(gl.texture_2d, gl.texture_mag_filter); specifications specification status comment webgl 1.0the definition of 'gettexparameter' in that specification.
WebGLRenderingContext.getUniform() - Web APIs
ements) uvec4 uint32array (with 4 elements) mat2x3 float32array (with 6 elements) mat2x4 float32array (with 8 elements) mat3x2 float32array (with 6 elements) mat3x4 float32array (with 12 elements) mat4x2 float32array (with 8 elements) mat4x3 float32array (with 12 elements) any sampler type glint examples var loc = gl.getuniformlocation(program, 'u_foobar'); gl.getuniform(program, loc); specifications specification status comment webgl 1.0the definition of 'getuniform' in that specification.
WebGLRenderingContext.getVertexAttrib() - Web APIs
examples gl.getvertexattrib(0, gl.vertex_attrib_array_buffer_binding); specifications specification status comment webgl 1.0the definition of 'getvertexattrib' in that specification.
WebGLRenderingContext.getVertexAttribOffset() - Web APIs
examples gl.getvertexattriboffset(i, gl.vertex_attrib_array_pointer); specifications specification status comment webgl 1.0the definition of 'getvertexattriboffset' in that specification.
WebGLRenderingContext.hint() - Web APIs
examples the following example hints that the quality of filtering when generating mipmap images should be most efficient instead of best quality.
WebGLRenderingContext.isBuffer() - Web APIs
examples creating a buffer var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); var buffer = gl.createbuffer(); gl.isbuffer(buffer); specifications specification status comment webgl 1.0the definition of 'isbuffer' in that specification.
WebGLRenderingContext.isEnabled() - Web APIs
examples gl.isenabled(gl.stencil_test); // false to activate or deactivate a specific capability, use the webglrenderingcontext.enable() and webglrenderingcontext.disable() methods: gl.enable(gl.stencil_test); gl.disable(gl.stencil_test); specifications specification status comment webgl 1.0the definition of 'isenabled' in that specification.
WebGLRenderingContext.isFramebuffer() - Web APIs
examples checking a frame buffer var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); var framebuffer = gl.createframebuffer(); gl.isframebuffer(framebuffer); specifications specification status comment webgl 1.0the definition of 'isframebuffer' in that specification.
WebGLRenderingContext.isProgram() - Web APIs
examples checking a program var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); var program = gl.createprogram(); // ...
WebGLRenderingContext.isRenderbuffer() - Web APIs
examples checking a renderbuffer var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); var renderbuffer = gl.createrenderbuffer(); gl.isrenderbuffer(renderbuffer); specifications specification status comment webgl 1.0the definition of 'isrenderbuffer' in that specification.
WebGLRenderingContext.isShader() - Web APIs
examples checking a shader var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); var shader = gl.createshader(gl.vertex_shader); // ...
WebGLRenderingContext.isTexture() - Web APIs
examples checking a texture var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); var texture = gl.createtexture(); gl.istexture(texture); specifications specification status comment webgl 1.0the definition of 'istexture' in that specification.
WebGLRenderingContext.lineWidth() - Web APIs
examples setting the line width: gl.linewidth(5); getting the line width: gl.getparameter(gl.line_width); getting the range of available widths.
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.polygonOffset() - Web APIs
examples the polygon offset fill is disabled by default.
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 definitio...
WebGLRenderingContext.renderbufferStorage() - Web APIs
examples gl.renderbufferstorage(gl.renderbuffer, gl.rgba4, 256, 256); specifications specification status comment webgl 1.0the definition of 'renderbufferstorage' in that specification.
WebGLRenderingContext.sampleCoverage() - Web APIs
examples multi-sampling is disabled by default.
WebGLRenderingContext.scissor() - Web APIs
examples when the scissor test is enabled, only pixels within the scissor box can be modified by drawing commands.
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.stencilFunc() - Web APIs
examples the stencil testing is disabled by default.
WebGLRenderingContext.stencilFuncSeparate() - Web APIs
examples the stencil testing is disabled by default.
WebGLRenderingContext.stencilMask() - Web APIs
examples gl.stencilmask(110101); to get the current stencil masks, query the stencil_writemask, stencil_back_writemask, or stencil_bits constants.
WebGLRenderingContext.stencilMaskSeparate() - Web APIs
examples gl.stencilmaskseparate(gl.front, 110101); to get the current stencil masks, query the stencil_writemask, stencil_back_writemask, or stencil_bits constants.
WebGLRenderingContext.stencilOp() - Web APIs
examples the stencil testing is disabled by default.
WebGLRenderingContext.stencilOpSeparate() - Web APIs
examples the stencil testing is disabled by default.
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.uniformMatrix[234]fv() - Web APIs
return value undefined examples gl.uniformmatrix2fv(loc, false, [2,1, 2,2]); specifications specification status comment webgl 1.0the definition of 'uniformmatrix' 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.viewport() - Web APIs
examples when you first create a webgl context, the size of the viewport will match the size of the canvas.
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.
WebGLShaderPrecisionFormat.precision - Web APIs
examples var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); gl.getshaderprecisionformat(gl.vertex_shader, gl.medium_float).precision; // 23 gl.getshaderprecisionformat(gl.fragment_shader, gl.low_int).precision; // 0 specifications specification status comment webgl 1.0the definition of 'webglshaderprecisionformat.precision' in that specification.
WebGLShaderPrecisionFormat.rangeMax - Web APIs
examples var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); gl.getshaderprecisionformat(gl.vertex_shader, gl.medium_float).rangemax; // 127 gl.getshaderprecisionformat(gl.fragment_shader, gl.low_int).rangemax; // 24 specifications specification status comment webgl 1.0the definition of 'webglshaderprecisionformat.rangemax' in that specification.
WebGLShaderPrecisionFormat.rangeMin - Web APIs
examples var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); gl.getshaderprecisionformat(gl.vertex_shader, gl.medium_float).rangemin; // 127 gl.getshaderprecisionformat(gl.fragment_shader, gl.low_int).rangemin; // 24 specifications specification status comment webgl 1.0the definition of 'webglshaderprecisionformat.rangemin' in that specification.
WebGLShaderPrecisionFormat - Web APIs
examples a webglshaderprecisionformat object is returned by the webglrenderingcontext.getshaderprecisionformat() method.
WebGLSync - Web APIs
WebAPIWebGLSync
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.
WebGLVertexArrayObject - Web APIs
examples var vao = gl.createvertexarray(); gl.bindvertexarray(vao); // ...
Video textures - Web APIs
« previous this example demonstrates how to use video files as textures for webgl surfaces.
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/foobar512x5...
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.
Creating 3D objects using WebGL - Web APIs
this example uses the glmatrix library to perform its matrix and vertex math.
Getting started with WebGL - Web APIs
the code examples in this tutorial can also be found in the webgl-examples github repository.
Using shaders to apply color in WebGL - Web APIs
this example uses the glmatrix library to perform its matrix and vertex math.
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 types - Web APIs
WebAPIWebGL APITypes
used for example in webglrenderingcontext.clear().
Using WebGL extensions - Web APIs
for example: var float_texture_ext = gl.getextension('oes_texture_float'); the return value is null if the extension is not supported, or an extension object otherwise.
WebRTC connectivity - Web APIs
for example, when renegotiating a connection—for example, to adapt to changing hardware or network configurations—it's possible that negotiation could reach a dead end, or some form of error might occur that prevents negotiation at all.
Introduction to WebRTC protocols - Web APIs
for example, lines providing media descriptions have the type "m", so those lines are referred to as "m-lines." for more information to learn more about sdp, see the following useful resources: specification: rfc 4566: sdp: session description protocol iana registry of sdp parameters ...
Using WebRTC data channels - Web APIs
for example, both firefox and google chrome use the usrsctp library to implement sctp, but there are still situations in which data transfer on an rtcdatachannel can fail due to differences in how they call the library and react to errors it returns.
WebRTC API - Web APIs
signaling and two-way video calling a tutorial and example which turns a websocket-based chat system created for a previous example and adds support for opening video calls among participants.
WebSocket() - Web APIs
these strings are used to indicate sub-protocols, so that a single server can implement multiple websocket sub-protocols (for example, you might want one server to be able to handle different types of interactions depending on the specified protocol).
WebSocket: message event - Web APIs
bubbles no cancelable no interface messageevent event handler property onmessage examples // create websocket connection.
WebSocket.onerror - Web APIs
WebAPIWebSocketonerror
example websocket.onerror = function(event) { console.error("websocket error observed:", event); }; specifications specification status comment html living standardthe definition of 'websocket: onerror' in that specification.
WebSocket: open event - Web APIs
bubbles no cancelable no interface event event handler property onopen examples // create websocket connection.
WebSocket.send() - Web APIs
WebAPIWebSocketsend
if the data can't be sent (for example, because it needs to be buffered but the buffer is full), the socket is closed automatically.
WebSocket - Web APIs
WebAPIWebSocket
examples // create websocket connection.
The WebSocket API (WebSockets) - Web APIs
total.js: web application framework for node.js (example: websocket chat) faye: a websocket (two-ways connections) and eventsource (one-way connections) for node.js server and client.
WebXR permissions and security - Web APIs
for example, if you have an "enter xr mode" button, and the user clicks it, calling requestsession() from the button's click event handler will permitted.
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.
Functions and classes available to Web Workers - Web APIs
48 (48) (yes) (yes) (yes) domrequest and domcursor respectively, these objects represents an ongoing operation (with listeners for reacting to the operation completely successfully, or failing, for example), and an ongoing operation over a list of results.
The structured clone algorithm - Web APIs
for example, if an object is marked readonly with a property descriptor, it will be read/write in the duplicate, since that's the default.
WheelEvent.deltaMode - Web APIs
syntax var unit = event.deltamode; example var syntheticevent = new wheelevent("syntheticwheel", {"deltax": 4, "deltamode": 0}); console.log(syntheticevent.deltamode); specifications specification status comment document object model (dom) level 3 events specificationthe definition of 'wheelevent.deltamode' in that specification.
WheelEvent.deltaX - Web APIs
WebAPIWheelEventdeltaX
syntax var dx = event.deltax; example var syntheticevent = new wheelevent("syntheticwheel", {"deltax": 4, "deltamode": 0}); console.log(syntheticevent.deltax); specifications specification status comment document object model (dom) level 3 events specificationthe definition of 'wheelevent.deltax' in that specification.
WheelEvent.deltaY - Web APIs
WebAPIWheelEventdeltaY
syntax var dy = event.deltay; example var syntheticevent = new wheelevent("syntheticwheel", {"deltay": 4, "deltamode": 0}); console.log(syntheticevent.deltay); specifications specification status comment document object model (dom) level 3 events specificationthe definition of 'wheelevent.deltay' in that specification.
WheelEvent.deltaZ - Web APIs
WebAPIWheelEventdeltaZ
syntax var dz = event.deltaz; example var syntheticevent = new wheelevent("syntheticwheel", {"deltaz": 4, "deltamode": 0}); console.log(syntheticevent.deltaz); specifications specification status comment document object model (dom) level 3 events specificationthe definition of 'wheelevent.deltaz' in that specification.
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.alert() - Web APIs
WebAPIWindowalert
example window.alert("hello world!"); alert("hello world!"); both produce: notes the alert dialog should be used for messages which do not require any response on the part of the user, other than the acknowledgement of the message.
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: 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.back() - Web APIs
WebAPIWindowback
example this simple example handles a click on a "back" button by calling back().
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: beforeunload event - Web APIs
examples the html specification states that authors should use the event.preventdefault() method instead of using event.returnvalue.
Window.blur() - Web APIs
WebAPIWindowblur
syntax window.blur() example window.blur(); notes the window.blur() method is the programmatic equivalent of the user shifting focus away from the current window.
Window: blur event - Web APIs
WebAPIWindowblur event
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.cancelIdleCallback() - Web APIs
example see our complete example in the article cooperative scheduling of background tasks api.
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
WebAPIWindowclose
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.confirm() - Web APIs
WebAPIWindowconfirm
example if (window.confirm("do you really want to leave?")) { window.open("exit.html", "thanks for visiting!"); } produces: notes the following text is shared between this article, dom:window.prompt and dom:window.alert dialog boxes are modal windows — they prevent the user from accessing the rest of the program's interface until the dialog box is closed.
Window: copy event - Web APIs
WebAPIWindowcopy event
examples window.addeventlistener('copy', (event) => { console.log('copy action initiated') }); specifications specification status clipboard api and events working draft ...
Window.crypto - Web APIs
WebAPIWindowcrypto
example this example uses the window.crypto property to access the getrandomvalues() method.
Window: cut event - Web APIs
WebAPIWindowcut event
examples window.addeventlistener('cut', (event) => { console.log('cut action initiated') }); specifications specification status clipboard api and events working draft ...
Window.defaultStatus - Web APIs
example <html> <body onload="window.defaultstatus='hello!';"/> <button onclick="window.confirm('are you sure you want to quit?');">confirm</button> </body> </html> notes to set the status once the window has been opened, use window.status.
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, rotatedeg...
Window.directories - Web APIs
example <script> function dirs() { alert(window.directories); } </script> specification not part of specification.
Window.document - Web APIs
WebAPIWindowdocument
example console.log(window.document.title); specifications specification status comment html living standardthe definition of 'window.document' in that specification.
Window.find() - Web APIs
WebAPIWindowfind
example javascript findstring = function findtext(text) { alert("string \x22" + text + "\x22 found?
Window.focus() - Web APIs
WebAPIWindowfocus
syntax window.focus() example if (clicked) { window.focus(); } specification specification status comment html living standardthe definition of 'window.focus()' in that specification.
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.forward() - Web APIs
WebAPIWindowforward
example function goforward() { if (cangoforward) { window.forward(); } } specification this is not part of any specification.
Window.frameElement - Web APIs
example const frameel = window.frameelement; // if we're embedded, change the containing element's url to 'http://mozilla.org/' if (frameel) { frameel.src = 'http://mozilla.org/'; } specifications specification status comment html living standardthe definition of 'window.frameelement' in that specification.
Window.frames - Web APIs
WebAPIWindowframes
example var frames = window.frames; // or // var frames = window.parent.frames; for (var i = 0; i < frames.length; i++) { // do something with each subframe as frames[i] frames[i].document.body.style.background = "red"; } specifications specification status comment html living standardthe definition of 'window.frames' in that specification.
Window.fullScreen - Web APIs
WebAPIWindowfullScreen
example if (window.fullscreen) { // it's fullscreen!
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: 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 'hashcha...
Window.home() - Web APIs
WebAPIWindowhome
syntax window.home(); example function gohome() { window.home(); } specification dom level 0.
Window.innerWidth - Web APIs
WebAPIWindowinnerWidth
example // this will return the width of the viewport var intframewidth = window.innerwidth; // this will return the width of the frame viewport within a frameset var intframewidth = self.innerwidth; // this will return the width of the viewport of the closest frameset var intframesetwidth = parent.innerwidth; // this will return the width of the viewport of the outermost frameset var intouterframese...
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.length - Web APIs
WebAPIWindowlength
example if (window.length) { // this is a document with subframes } specifications specification status comment html living standardthe definition of 'window.length' in that specification.
Window: load event - Web APIs
WebAPIWindowload event
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>e...
Window.locationbar - Web APIs
syntax objref = window.locationbar example the following complete html example shows how the visible property of the locationbar object is used.
Window.menubar - Web APIs
WebAPIWindowmenubar
syntax objref = window.menubar example the following complete html example demonstrates how the visible property of the menubar object is used.
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.moveBy() - Web APIs
WebAPIWindowmoveBy
example this example moves the window 10 pixels to the right and 10 pixels up.
Window.moveTo() - Web APIs
WebAPIWindowmoveTo
example this example moves the window to the top-left corner of the screen.
Window.mozAnimationStartTime - Web APIs
this value should be used instead of, for example, date.now(), because this value will be the same for all animations started in this window during this refresh interval, allowing them to remain in sync with one another.
Window.name - Web APIs
WebAPIWindowname
syntax string = window.name; window.name = string; example <script> // open a tab with a specific browsing context name const othertab = window.open("url1", "_blank"); if (othertab) othertab.name = "other-tab"; </script> <a href="url2" target="other-tab">this link will be opened in the other tab.</a> notes the name of the window is used primarily for setting targets for hyperlinks and forms.
Window.navigator - Web APIs
WebAPIWindownavigator
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.onappinstalled - Web APIs
}; example window.onappinstalled = function(ev) { console.log('the application was installed.'); }; ...
Window.onbeforeinstallprompt - Web APIs
}); window.onbeforeinstallprompt = function(event) { ...}; example the following example uses the beforeinstallprompt event to make an install button operable, by using the event inside a click handler.
Window.ondragdrop - Web APIs
WebAPIWindowondragdrop
example fire an alert on dragdrop in this example, an event listener is added to the window (the event target).
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.onmozbeforepaint - Web APIs
example see window.mozrequestanimationframe() for an example.
Window: orientationchange event - Web APIs
bubbles no cancelable no interface event event handler onorientationchange example you can use the orientationchange event in an addeventlistener method: window.addeventlistener("orientationchange", function(event) { console.log("the orientation of the device is now " + event.target.screen.orientation.angle); }); or use the onorientationchange event handler property: window.onorientationchange = function(event) { console.log("the orientation of the device is now " + event.target.screen.orientation.angle); }; specifications specification status compatibility standardthe definition of 'orientationchange' in that specificati...
Window.outerHeight - Web APIs
graphical example the following figure shows the difference between outerheight and innerheight.
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.parent - Web APIs
WebAPIWindowparent
syntax var parentwindow = window.parent; example if (window.parent != window.top) { // we're deeper than one down } specifications specification status comment html living standardthe definition of 'window.parent' in that specification.
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.pkcs11 - Web APIs
WebAPIWindowpkcs11
syntax objref = window.pkcs11 example window.pkcs11.addmodule(smod, secpath, 0, 0); notes see nsidompkcs11 for more information about how to manipulate pkcs11 objects.
Window: rejectionhandled event - Web APIs
bubbles no cancelable no interface promiserejectionevent event handler property onrejectionhandled example you can use the rejectionhandled event to log promises that get rejected to the console, along with the reasons why they were rejected: window.addeventlistener("rejectionhandled", event => { console.log("promise rejected; reason: " + event.reason); }, false); specifications specification status comment html living standardthe definition of 'rejectionhandled' in ...
Window.releaseEvents() - Web APIs
example window.releaseevents(event.keypress) notes note that you can pass a list of events to this method using the following syntax: window.releaseevents(event.keypress | event.keydown | event.keyup).
Window.requestFileSystem() - Web APIs
return value undefined example specifications specification status comment file and directory entries api draft draft of proposed api this api has no official w3c or whatwg specification.
window.requestIdleCallback() - Web APIs
example see our complete example in the article cooperative scheduling of background tasks api.
Window.resizeBy() - Web APIs
WebAPIWindowresizeBy
example // shrink the window window.resizeby(-200, -200); notes this method resizes the window relative to its current size.
Window.resizeTo() - Web APIs
WebAPIWindowresizeTo
example this function resizes the window so that it takes up one quarter of the available screen.
Window.screen - Web APIs
WebAPIWindowscreen
syntax let screenobj = window.screen; example if (screen.pixeldepth < 8) { // use low-color version of page } else { // use regular, colorful page } specifications specification status comment css object model (cssom) view modulethe definition of 'window.screen' in that specification.
Window.scroll() - Web APIs
WebAPIWindowscroll
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
WebAPIWindowscrollBy
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.scrollByLines() - Web APIs
example <!-- scroll up the document by 5 lines --> <button id="scroll-up" onclick="scrollbylines(-5);">up 5 lines</button> <!-- scroll down the document by 5 lines --> <button id="scroll-down" onclick="scrollbylines(5);">down 5 lines</button> specification this is not part of any specification.
Window.scrollByPages() - Web APIs
example // scroll down the document by 1 page window.scrollbypages(1); // scroll up the document by 1 page window.scrollbypages(-1); specification dom level 0.
Window.scrollMaxX - Web APIs
WebAPIWindowscrollMaxX
example // scroll to right edge of the page let maxx = window.scrollmaxx; window.scrollto(maxx, 0); notes do not use this property to get the total document width, which is not equivalent to window.innerwidth + window.scrollmaxx, because window.innerwidth includes the width of any visible vertical scrollbar, thus the result would exceed the total document width by the width of any visible vertical scrollbar.
Window.scrollMaxY - Web APIs
WebAPIWindowscrollMaxY
example // scroll to the bottom of the page let maxy = window.scrollmaxy; window.scrollto(0, maxy); notes do not use this property to get the total document height, which is not equivalent to window.innerheight + window.scrollmaxy, because window.innerheight includes the width of any visible horizontal scrollbar, thus the result would exceed the total document height by the width of any visible horizontal scrollbar.
Window.scrollTo() - Web APIs
WebAPIWindowscrollTo
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.scrollbars - Web APIs
WebAPIWindowscrollbars
syntax objref = window.scrollbars example the following complete html example shows how the visible property of the scrollbars object is used.
Window.self - Web APIs
WebAPIWindowself
example uses of window.self like the following could just as well be replaced by window.
Window.setCursor() - Web APIs
WebAPIWindowsetCursor
example function setbusycursor(enable) { window.setcursor(enable ?
Window.showModalDialog() - Web APIs
examples try out showmodaldialog().
Window.speechSynthesis - Web APIs
examples in our basic speech synthesiser demo, we first grab a reference to the speechsynthesis controller using window.speechsynthesis.
Window.stop() - Web APIs
WebAPIWindowstop
syntax window.stop() example window.stop(); specification specification status comment html living standardthe definition of 'window.stop()' in that specification.
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.
WindowClient.focus() - Web APIs
example 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]; i...
WindowClient.focused - Web APIs
example 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 == '/' && 'focus' in client) { if(!client.focused) return client.focus(); } } } if (clients.openwindow) return clients.openwi...
WindowClient.visibilityState - Web APIs
example event.waituntil(clients.matchall({ type: "window" }).then(function(clientlist) { for (let i = 0; i < clientlist.length; i++) { let client = clientlist[i]; if (client.url == '/' && 'focus' in client) { if (client.visibilitystate === 'hidden') return client.focus(); } } } if (clients.openwindow) { return clients.openwindow('/'); } })); }); specifications specification status comment service worke...
WindowClient - Web APIs
example 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 = cl...
WindowEventHandlers.onafterprint - Web APIs
the beforeprint and afterprint events allow pages to change their content before printing starts (perhaps to remove a banner, for example) and then revert those changes after printing has completed.
WindowEventHandlers.onbeforeprint - Web APIs
the beforeprint and afterprint events allow pages to change their content before printing starts (perhaps to remove a banner, for example) and then revert those changes after printing has completed.
WindowEventHandlers.onbeforeunload - Web APIs
example this example prompts the user before unloading.
WindowEventHandlers.onlanguagechange - Web APIs
example window.onlanguagechange = function(event) { console.log('languagechange event detected!'); }; specifications specification status comment html living standardthe definition of 'windoweventhandler.onlanguagechange' in that specification.
WindowEventHandlers.onrejectionhandled - Web APIs
}); window.onrejectionhandled = function(event) { ...}; example window.onrejectionhandled = function(e) { console.log(e.reason); } specifications specification status comment html living standardthe definition of 'onrejectionhandled' in that specification.
WindowEventHandlers.onstorage - Web APIs
example this example logs the value for a storage key whenever it changes in another document.
WindowEventHandlers.onunhandledrejection - Web APIs
examples this example simply logs unhandled rejections' reason values to the console.
WindowOrWorkerGlobalScope.caches - Web APIs
example the following example shows how you'd use a cache in a service worker context to store assets offline.
WindowOrWorkerGlobalScope.clearInterval() - Web APIs
return value undefined example see the setinterval() examples.
WindowOrWorkerGlobalScope.clearTimeout() - Web APIs
example run the script below in the context of a web page and click on the page once.
self.createImageBitmap() - Web APIs
example creating sprites from a sprite sheet this example loads a sprite sheet, extracts individual sprites, and then renders each sprite to the canvas.
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.indexedDB - Web APIs
example the following code creates a request for a database to be opened asychronously, after which the database is opened when the request's onsuccess handler is fired: var db; function opendb() { var dbopenrequest = window.indexeddb.open('todolist'); dbopenrequest.onsuccess = function(e) { db = dbopenrequest.result; } } specifications specification status comment indexed database api draftthe definition of 'indexeddb' 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
WebAPIWorkerWorker
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 w...
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"); wor...
Worker.terminate() - Web APIs
WebAPIWorkerterminate
example the following code snippet shows creation of a worker object using the worker() constructor, which is then immediately terminated.
WorkerGlobalScope.close() - Web APIs
syntax self.close(); example if you wanted to close your worker instance from inside the worker itself, you could call the following: close(); close() and self.close() are effectively equivalent — both represent close() being called from inside the worker's inner scope.
WorkerGlobalScope.importScripts() - Web APIs
example if you had some functionality written in a separate script called foo.js that you wanted to use inside worker.js, you could import it using the following line: importscripts('foo.js'); importscripts() and self.importscripts() are effectively equivalent — both represent importscripts() being called from inside the worker's inner scope.
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.
WorkerGlobalScope.location - Web APIs
example if you called the following in a document served at localhost:8000 console.log(location); inside a worker (which would basically be the equivalent of self.console.log(self.location);, as these are being called on the worker scope, which can be referenced with workerglobalscope.self), you will get a workerlocation object written to the console — something like the following: workerlocation {hash: "", search: "", pathname: "/worker.js", port: "8000", hostname: "localhost"…} ha...
WorkerGlobalScope.navigator - Web APIs
example if you call the following console.log(navigator); inside a worker (which would basically be the equivalent of self.console.log(self.navigator);, as these are being called on the worker scope, which can be referenced with workerglobalscope.self), you will get a workernavigator object written to the console — something like the following: object {online: true, useragent: "mozilla/5.0 (macintosh; intel mac os x 10_10_1) ap…ml, like gecko) chrome/40.0.2214.93 safari/537.36"...
WorkerGlobalScope.onclose - Web APIs
}; example the following code snippet shows an onclose handler set inside a worker: self.onclose = function() { console.log('your worker instance has been closed'); } specifications this feature is no longer defined in any specifications.
WorkerGlobalScope.onerror - Web APIs
}; example the following code snippet shows an onerror handler set inside a worker: self.onerror = function() { console.log('there is an error inside your worker!'); } specifications specification status comment html living standardthe definition of 'workerglobalscope.onerror' in that specification.
WorkerGlobalScope.onlanguagechange - Web APIs
}; example the following code snippet shows an onlanguagechange handler set inside a worker: self.onlanguagechange = function() { console.log('your preferred language settings have been changed'); } specifications specification status comment html living standardthe definition of 'workerglobalscope.onlanguagechange' in that specification.
WorkerGlobalScope.onoffline - Web APIs
}; example the following code snippet shows an onoffline handler set inside a worker: self.onoffline = function() { console.log('your worker is now offline'); } specifications specification status comment html living standardthe definition of 'workerglobalscope.onoffline' in that specification.
WorkerGlobalScope.ononline - Web APIs
}; example the following code snippet shows an ononline handler set inside a worker: self.ononline = function() { console.log('your worker is now online'); } specifications specification status comment html living standardthe definition of 'workerglobalscope.ononline' in that specification.
WorkerGlobalScope.performance - Web APIs
example if you called console.log(performance); inside a worker (which would basically be the equivalent of self.console.log(self.performance);, as these are being called on the worker scope, which can be referenced with workerglobalscope.self), you will get a workerperformance object written to the console — something like the following: workerperformance {now: function} __proto__: workerperformance constructor: function workerperformance() { [native code] } now: function ...
WorkerGlobalScope.self - Web APIs
example if you called console.log(self); inside a worker, you will get a worker global scope of the same type as that worker object written to the console — something like the following: dedicatedworkerglobalscope { undefined: undefined, infinity: infinity, math: mathconstructor, nan: nan, intl: object…} infinity: infinity array: function array() { [native code] } arguments: null caller:...
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
WebAPIWorkletaddModule
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...
WritableStream.abort() - Web APIs
examples const writablestream = new writablestream({ write(chunk) { ...
WritableStream.locked - Web APIs
examples const writablestream = new writablestream({ write(chunk) { ...
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) { ...
WritableStreamDefaultWriter.abort() - Web APIs
examples const writablestream = new writablestream({ write(chunk) { ...
WritableStreamDefaultWriter.closed - Web APIs
examples const writablestream = new writablestream({ start(controller) { }, write(chunk, controller) { ...
WritableStreamDefaultWriter.desiredSize - Web APIs
examples const writablestream = new writablestream({ write(chunk) { ...
WritableStreamDefaultWriter.ready - Web APIs
example the following example shows two uses of the ready property.
WritableStreamDefaultWriter.releaseLock() - Web APIs
examples const writablestream = new writablestream({ write(chunk) { ...
XDomainRequest.abort() - Web APIs
syntax xdr.abort(); example var xdr = new xdomainrequest(); xdr.open("get", "http://example.com/api/method"); xdr.send(); xdr.abort(); specification not part of any specification.
XDomainRequest.onerror - Web APIs
example var xdr = new xdomainrequest(); xdr.open("post", "http://example.com/api/method"); xdr.onerror = function(){ //handle error } xdr.onload = function(){ //handle response with xdr.responsetext } xdr.send("param1=value1&param2=value2"); specification not part of any specification.
XDomainRequest.onload - Web APIs
syntax xdr.onload = funcref; example var xdr = new xdomainrequest(); xdr.open("post", "http://example.com/api/method"); xdr.onload = function(){ //handle response with xdr.responsetext } xdr.send("param1=value1&param2=value2"); specification not part of any specification.
XDomainRequest.onprogress - Web APIs
example var xdr = new xdomainrequest(); xdr.open("post", "http://example.com/api/method"); xdr.onprogress = function(){ //handle partial response with xdr.responsetext } xdr.onload = function(){ //handle response with xdr.responsetext } xdr.send("param1=value1&param2=value2"); specification not part of any specification.
XDomainRequest.ontimeout - Web APIs
example var xdr = new xdomainrequest(); xdr.open("post", "http://example.com/api/method"); xdr.ontimeout = function(){ //handle timeout } xdr.onload = function(){ //handle response with xdr.responsetext } xdr.send("param1=value1&param2=value2"); specification not part of any specification.
XDomainRequest.open() - Web APIs
example var xdr = new xdomainrequest(); xdr.open("get", "http://example.com/api/method"); specification not part of any specification.
XDomainRequest.responseText - Web APIs
example var response = xdr.responsetext; specification not part of any specification.
XDomainRequest.send() - Web APIs
example var xdr = new xdomainrequest(); xdr.open("post", "http://example.com/api/method"); xdr.onload = function(){ //handle response with xdr.responsetext } xdr.send("param1=value1&param2=value2"); specification not part of any specification.
XDomainRequest.timeout - Web APIs
example xdr.timeout = 10000; specification not part of any specification.
XDomainRequest - Web APIs
example if(window.xdomainrequest){ var xdr = new xdomainrequest(); xdr.open("get", "http://example.com/api/method"); xdr.onprogress = function () { //progress }; xdr.ontimeout = function () { //timeout }; xdr.onerror = function () { //error occurred }; xdr.onload = function() { //success(xdr.responsetext); } settimeout(function () { xdr.send(); }, 0); } ...
XMLDocument.async - Web APIs
WebAPIXMLDocumentasync
(it has been possible to load documents synchronously since 1.4 alpha.) example function loadxmldata(e) { alert(new xmlserializer().serializetostring(e.target)); // gives querydata.xml contents as string } var xmldoc = document.implementation.createdocument("", "test", null); xmldoc.async = false; xmldoc.onload = loadxmldata; xmldoc.load('querydata.xml'); ...
XMLDocument.load() - Web APIs
WebAPIXMLDocumentload
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.
HTML in XMLHttpRequest - Web APIs
for older browsers, you can even use the xmlhttprequest.responsetext property in association with regular expressions in order to get, for example, the source code of an html element given its id: function gethtml (oxhr, stargetid) { var ropen = new regexp("<(?!\!)\\s*([^\\s>]+)[^>]*\\s+id\\=[\"\']" + stargetid + "[\"\'][^>]*>" ,"i"), ssrc = oxhr.responsetext, aexec = ropen.exec(ssrc); return aexec ?
XMLHttpRequest.abort() - Web APIs
return value undefined example this example begins loading content from the mdn home page, then due to some condition, aborts the transfer by calling abort().
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.q...
XMLHttpRequest.getResponseHeader() - Web APIs
example in this example, a request is created and sent, and a readystatechange handler is established to look for the readystate to indicate that the headers have been received; when that is the case, the value of the content-type header is fetched.
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 xhrbuttonsu...
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 = ...
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 ...
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 xhrbuttonsucce...
XMLHttpRequest.readyState - Web APIs
example var xhr = new xmlhttprequest(); console.log('unsent', xhr.readystate); // readystate will be 0 xhr.open('get', '/api', true); console.log('opened', xhr.readystate); // readystate will be 1 xhr.onprogress = function () { console.log('loading', xhr.readystate); // readystate will be 3 }; xhr.onload = function () { console.log('done', xhr.readystate); // readystate will be 4 }; xhr.send...
XMLHttpRequest.response - Web APIs
example this example presents a function, load(), which loads and processes a page from the server.
XMLHttpRequest.responseText - Web APIs
example var xhr = new xmlhttprequest(); xhr.open('get', '/server', true); // if specified, responsetype must be empty string or "text" xhr.responsetype = 'text'; xhr.onload = function () { if (xhr.readystate === xhr.done) { if (xhr.status === 200) { console.log(xhr.response); console.log(xhr.responsetext); } } }; xhr.send(null); specifications ...
XMLHttpRequest.responseURL - Web APIs
example var xhr = new xmlhttprequest(); xhr.open('get', 'http://example.com/test', true); xhr.onload = function () { console.log(xhr.responseurl); // http://example.com/test }; xhr.send(null); specifications specification status comment xmlhttprequest living standard whatwg living standard ...
XMLHttpRequest.responseXML - Web APIs
example var xhr = new xmlhttprequest; xhr.open('get', '/server'); // if specified, responsetype must be empty string or "document" xhr.responsetype = 'document'; // force the response to be parsed as xml xhr.overridemimetype('text/xml'); xhr.onload = function () { if (xhr.readystate === xhr.done && xhr.status === 200) { console.log(xhr.response, xhr.responsexml); } }; xhr.send(); specificat...
XMLHttpRequest.status - Web APIs
example var xhr = new xmlhttprequest(); console.log('unsent: ', xhr.status); xhr.open('get', '/server'); console.log('opened: ', xhr.status); xhr.onprogress = function () { console.log('loading: ', xhr.status); }; xhr.onload = function () { console.log('done: ', xhr.status); }; xhr.send(); /** * outputs the following: * * unsent: 0 * opened: 0 * loading: 200 * done: 200 */ specifications specification status comment xmlhttprequest living standard whatwg living standard ...
XMLHttpRequest.statusText - Web APIs
example var xhr = new xmlhttprequest(); console.log('0 unsent', xhr.statustext); xhr.open('get', '/server', true); console.log('1 opened', xhr.statustext); xhr.onprogress = function () { console.log('3 loading', xhr.statustext); }; xhr.onload = function () { console.log('4 done', xhr.statustext); }; xhr.send(null); /** * outputs the following: * * 0 unsent * 1 opened * 3 loading ok * 4 do...
XMLHttpRequest.timeout - Web APIs
example var xhr = new xmlhttprequest(); xhr.open('get', '/server', true); xhr.timeout = 2000; // time in milliseconds xhr.onload = function () { // request finished.
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.
XMLHttpRequest.withCredentials - Web APIs
example var xhr = new xmlhttprequest(); xhr.open('get', 'http://example.com/', true); xhr.withcredentials = true; xhr.send(null); specifications specification status comment xmlhttprequest living standard whatwg living standard ...
XMLHttpRequestEventTarget.onabort - Web APIs
example var xmlhttp = new xmlhttprequest(), method = 'get', url = 'https://developer.mozilla.org/'; xmlhttp.open(method, url, true); xmlhttp.onabort = function () { console.log('** the request was aborted'); }; xmlhttp.send(); //..
XMLHttpRequestEventTarget.onerror - Web APIs
example var xmlhttp = new xmlhttprequest(), method = 'get', url = 'https://developer.mozilla.org/'; xmlhttp.open(method, url, true); xmlhttp.onerror = function () { console.log("** an error occurred during the transaction"); }; xmlhttp.send(); specifications specification status comment xmlhttprequest living standard whatwg living standard ...
XMLHttpRequestEventTarget.onload - Web APIs
example var xmlhttp = new xmlhttprequest(), method = 'get', url = 'https://developer.mozilla.org/'; xmlhttp.open(method, url, true); xmlhttp.onload = function () { // do something with the retrieved data ( found in xmlhttp.response ) }; xmlhttp.send(); specifications specification status comment xmlhttprequest living standard whatwg living standard ...
XMLHttpRequestEventTarget.onloadstart - Web APIs
example var xmlhttp = new xmlhttprequest(), method = 'get', url = 'https://developer.mozilla.org/'; xmlhttp.open(method, url, true); xmlhttp.onloadstart = function () { console.log("download underway"); }; xmlhttp.send(); specifications specification status comment xmlhttprequest living standard whatwg living standard ...
XMLHttpRequestEventTarget.onprogress - Web APIs
xmlhttprequest.onprogress = function (event) { event.loaded; event.total; }; example var xmlhttp = new xmlhttprequest(), method = 'get', url = 'https://developer.mozilla.org/'; xmlhttp.open(method, url, true); xmlhttp.onprogress = function () { //do something }; xmlhttp.send(); specifications specification status comment xmlhttprequest living standard whatwg living standard ...
XRFrame.getPose() - Web APIs
WebAPIXRFramegetPose
for example, to get the position of a controller relative to the viewer's head, you would compare the controller's gripspace to the xrreferencespace of type viewer.
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.
XRInputSourceArray.entries() - Web APIs
examples this example snippet gets the list of inputs for a session and tries to handle each type of input device it supports using.
XRInputSourceArray.forEach() - Web APIs
examples this example snippet gets the list of inputs for a session and tries to handle each type of input device it supports using.
XRInputSourceArray.keys() - Web APIs
examples this example snippet gets the list of inputs for a session and tries to handle each type of input device it supports using.
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.values() - Web APIs
examples this example snippet walks through each input and calls the function checkinput() with each returned value.
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.
XRInputSourceEvent.inputSource - Web APIs
example the snippet below shows a handler for the select event which looks specifically for events which happen on gaze input devices.
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.
XRInputSourceEventInit.frame - Web APIs
examples this example creates a new select event and sends it to the xrsession.
XRInputSourceEventInit.inputSource - Web APIs
examples this example creates a new select event and sends it to the xrsession.
XRInputSourcesChangeEvent() - Web APIs
example the following snippet of code creates a new xrinputsourceschangeevent object indicating that a single new input source, described by an xrinputsource object named newinputsource, has been added to the system.
XRInputSourcesChangeEvent.added - Web APIs
examples the example below creates a handler for the inputsourceschange event that processes the lists of added and removed from the webxr system.
XRInputSourcesChangeEvent.removed - Web APIs
examples the example below creates a handler for the inputsourceschange event that processes the lists of added and removed from the webxr system.
XRInputSourcesChangeEvent - Web APIs
examples the following example shows how to set up an event handler which uses inputsourceschange events to detect newly-available pointing devices and to load their models in preparation to display them in the next animation frame.
XRInputSourcesChangeEventInit - Web APIs
examples <tbd> specifications specification status comment webxr device apithe definition of 'xrinputsourceschangeeventinit' in that specification.
XRPermissionDescriptor.mode - Web APIs
usage notes examples the example below checks to ensure that permission has been granted to allow the user to use webxr for an immersive virtual reality experience.
XRPermissionDescriptor.optionalFeatures - Web APIs
xrreferencespace usage notes examples let xrpermissiondesc = { name: "xr", mode: "immersive-vr", optionalfeatures: [ "bounded-floor" ] }; if (navigator.permissions) { navigator.permissions.query(xrpermissiondesc).then(({state}) => { switch(state) { case "granted": setupxr(); break; case "prompt": promptandsetupxr(); break; default: /* do nothing otherwise */ ...
XRPermissionDescriptor.requiredFeatures - Web APIs
xrreferencespace usage notes examples in this example, permissions are checked to ensure that the user has granted permission for the site or app to use immersive augmented reality mode with the local-floor reference space (presumably since the user is unlikely to start to fly).
XRPermissionStatus.granted - Web APIs
xrreferencespace usage notes examples specifications specification status comment webxr device apithe definition of 'xrpermissionstatus.granted' in that specification.
XRPermissionStatus - Web APIs
usage notes examples specifications specification status comment webxr device apithe definition of 'xrpermissionstatus' in that specification.
XRPose.transform - Web APIs
WebAPIXRPosetransform
example this handler for the xrsession event select handles events for tracked pointers.
XRReferenceSpace: reset event - Web APIs
examples to add a handler for the reset event, you can use either of two approaches.
XRReferenceSpaceEvent.referenceSpace - Web APIs
examples specifications specification status comment webxr device apithe definition of 'xrreferencespaceevent.referencespace' in that specification.
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.
XRReferenceSpaceEventInit.referenceSpace - Web APIs
examples this simple snippet calls the constructor to create a new reference space event of type reset.
XRReferenceSpaceEventInit.transform - Web APIs
examples this simple snippet calls the constructor to create a new reference space event of type reset.
XRReferenceSpaceEventInit - Web APIs
examples this simple snippet calls the constructor to create a new reference space event of type reset.
XRRenderStateInit - Web APIs
all distances are specified as floating-point values in meters; you can specify a value of 50 centimeters using a value of 0.5, for example.
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.
XRRigidTransform.position - Web APIs
example to create a reference space which can be used to place an object at eye level (assuming eye level is 1.5 meters): function onsessionstarted(xrsession) { xrsession.addeventlistener("end", onsessionended); gl = initgraphics(xrsession); let gllayer = new xrwebgllayer(xrsession, gl); xrsession.updaterenderstate({ baselayer: gllayer }); if (immersivesession) { xrsession.requestrefer...
XRRigidTransform - Web APIs
example this code snippet creates an xrrigidtransform to specify the offset and orientation in relation to the current reference space to use when creating a new reference space.
XRSession.cancelAnimationFrame() - Web APIs
example in the example below we see code which starts up a webxr session if immersive vr mode is supported.
XRSession.end() - Web APIs
WebAPIXRSessionend
example specifications specification status comment webxr device apithe definition of 'xrsession.end' in that specification.
XRSession: end event - Web APIs
bubbles no cancelable no interface xrsessionevent event handler xrsession.onend example to be informed when a webxr session comes to an end, you can add a handler to your xrsession instance using addeventlistener(), like this: xrsession.addeventlistener("end", function(event) { /* the session has shut down */ }); alternatively, you can use the xrsession.onend event handler property to establish a handler for the end event: xrsession.onend = function(event) { /* the session has shut down */ } specifications specification status...
XRSession: inputsourceschange event - Web APIs
examples specifications specification status comment webxr device apithe definition of 'inputsourceschange event' in that specification.
XRSession.onend - Web APIs
WebAPIXRSessiononend
}; example xrsession.onend = function(event) { console.log("the xr session has ended") } specifications specification status comment webxr device apithe definition of 'xrsession.onend' in that specification.
XRSession.oninputsourceschange - Web APIs
} example xrsession.oninputsourceschange = function(event) { console.log("the list of active xr input sources has changed.") } specifications specification status comment webxr device apithe definition of 'xrsession.oninputsourceschange' in that specification.
XRSession.onselect - Web APIs
example this example handles select event which occur on the user's main hand (as given by a user object's handedness property); if that value matches the value of the xrinputsource property handedness, we know that the device is held in the user's main 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.
XRSession.onvisibilitychange - Web APIs
} example xrsession.onvisibilitychange = function(event) { console.log("the visibility the xr session changed.") } specifications specification status comment webxr device apithe definition of 'xrsession.onvisibilitychange' in that specification.
XRSession: selectend event - Web APIs
examples the following example uses addeventlistener() to establish handlers for the selection events: selectstart, selectend, and select.
XRSession: selectstart event - Web APIs
examples the following example uses addeventlistener() to establish handlers for the selection events: selectstart, selectend, and select.
XRSession: squeezeend event - Web APIs
examples the following example uses addeventlistener() to establish handlers for the squeezeion events: squeezestart, squeezeend, and squeeze.
XRSession: squeezestart event - Web APIs
examples the following example uses addeventlistener() to establish handlers for the squeezeion events: squeezestart, squeezeend, and squeeze.
XRSession.updateRenderState() - Web APIs
examples this example creates a webgl context that is compatible with an immersive xr device and then uses it to create an xrwebgllayer.
XRSession: visibilitychange event - Web APIs
examples this example demonstrates how to listen for a visibilitychange event on a webxr session, using addeventlistener() to begin listening for the event: navigator.xr.requestsession("inline").then((xrsession) => { xrsession.addeventlistener("visibilitychange", e => { switch(e.session.visiblitystate) { case "visible": case "visible-blurred": mysessionvisible(true); b...
XRSessionEvent() - Web APIs
examples this example creates a listiener that watches for the visibility state of the session to change.
XRSessionEvent.session - Web APIs
examples in this example, the session property is used to obtain the session object to manage when an event is received.
XRSessionEventInit - Web APIs
examples <tbd> specifications specification status comment webxr device apithe definition of 'xrsessioneventinit' in that specification.
XRSystem: isSessionSupported() - Web APIs
examples in this example, we see issessionsupported() used to detect whether or not the device supports vr mode by checking to see if an immersive-vr session is supported.
XRSystem: ondevicechange - Web APIs
}; value undefined example navigator.xr.ondevicechange = function(ev) { console.log("the availability of immersive xr devices has changed.") }; specifications specification status comment webxr device apithe definition of 'ondevicechange ' in that specification.
XRSystem - Web APIs
WebAPIXRSystem
examples the following example shows how to use both issessionsupported() and requestsession().
XRView.eye - Web APIs
WebAPIXRVieweye
examples this code, from the viewer pose's renderer, iterates over the pose's views and renders them.
XRView.projectionMatrix - Web APIs
examples specifications specification status comment webxr device apithe definition of 'xrview.projectionmatrix' in that specification.
XRViewport.height - Web APIs
WebAPIXRViewportheight
examples see the main xrviewport page for examples.
XRViewport.width - Web APIs
WebAPIXRViewportwidth
examples see the main xrviewport page for examples.
XRViewport.x - Web APIs
WebAPIXRViewportx
examples see the main xrviewport page for examples.
XRViewport.y - Web APIs
WebAPIXRViewporty
examples see the main xrviewport page for examples.
XRViewport - Web APIs
these values may be passed directly into the webglrenderingcontext.viewport() method: let xrviewport = xrwebgllayer.getviewport(xrview); gl.viewport(xrviewport.x, xrviewport.y, xrviewport.width, xrviewport.height); example this example sets up an animation frame callback using requestanimationframe().
XRWebGLLayer.antialias - Web APIs
examples this snippet checks the value of antialias to see if it should perform additional work to attempt to compensate for the lack of antialiasing on the webgl layer.
XRWebGLLayer.framebuffer - Web APIs
examples this example gets the xrwebgllayer for a session and then passes its framebuffer into the webgl context's bindframebuffer() function.
XRWebGLLayer.getViewport() - Web APIs
example this example demonstrates in part what the callback for the requestanimationframe() function might look like, using getviewport() to get the viewport so that drawing can be constrained to the area set aside for the eye whose viewpoint is currently being rendered.
XRWebGLLayer.ignoreDepthValues - Web APIs
examples if the web application which is using wexr is rendering its content without using a depth buffer—or if the depth buffer's contents are invalid—you should disable the use of the depth buffer for webxr rendering by setting ignoredepthvalues to true when creating the xrwebgllayer.
XRWebGLLayerInit.alpha - Web APIs
example in this example, a new xrwebgllayer is created for a webxr session, xrsession, without an alpha channel.
XRWebGLLayerInit.antialias - Web APIs
example in this example, before creating a new xrwebgllayer to use for rendering, the value of a user preference from a configuration interface is obtained using a function called getpreferencevalue() to determine whether the user has enabled or disabled anti-aliasing support; this is passed into the constructor.
XRWebGLLayerInit.depth - Web APIs
if (gllayer.ignoredepthvalues) { /* not using the depth buffer */ } example in this example, a new xrwebgllayer is created for a webxr session, xrsession, without a depth buffer.
XRWebGLLayerInit.ignoreDepthValues - Web APIs
example in this example, a new xrwebgllayer is created for a webxr session, xrsession.
XRWebGLLayerInit.stencil - Web APIs
example in this example, a new xrwebgllayer is created for a webxr session, xrsession, without a stencil buffer.
XRWebGLLayerInit - Web APIs
examples given an xrsession, xrsession, and a webgl rendering context, gl, this snippet sets the rendering layer for the session, specifying the ignoredepthvalues option, indicating that the depth buffer should not be used (or should not exist at all), and that the only source for distance information of any given point is its position relative to the viewer.
XSLTProcessor - Web APIs
<xsl:import> and document()) examples basic example advanced example additional example specifications not part of any specification.
msCapsLockWarningOff - Web APIs
example fiddle: http://jsfiddle.net/jonathansampson/mqcha/1/ example 2 <html> <head> <title>mscapslockwarningoff example</title> <script type="text/javascript"> function capsoff() { if (document.mscapslockwarningoff == false) { document.mscapslockwarningoff = true; document.getelementbyid("caps").innerhtml = "warning off"; ...
msRegionOverflow - Web APIs
in particular, in this last case, that means the region may have received no content from the named flow (for example if the region is too small to accommodate any content).
msWriteProfilerMark - Web APIs
example if (mswriteprofilermark) { mswriteprofilermark("mark1"); } see also microsoft api extensions ...
msthumbnailclick - Web APIs
example function thumbnailclickhandler(evt) { alert ("clicked button: " + evt.buttonid); } document.addeventlistener('msthumbnailclick', thumbnailclickhandler); example 2 // adds an overlay icon on your app pinned to the taskbar window.external.mssitemodeseticonoverlay(iconuri, tooltip); // removes an overlay icon window.external.mssitemodecleariconoverlay(); // pinned icons on your taskbar can...
ARIA Screen Reader Implementors Guide - Accessibility
for example, automatically speak changes that are caused by the user's own input, as part of the context of that input.
ARIA Technique Template - Accessibility
examples example 1: code 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 aria-activedescendant attribute - Accessibility
examples example 1: code 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 aria-hidden attribute - Accessibility
examples in the example below, the paragraph is not exposed to the accessibility api (e.g.
Using the aria-label attribute - Accessibility
examples example 1: multiple labels in the example below, a button is styled to look like a typical "close" button, with an x in the middle.
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 ...
x-ms-aria-flowfrom - Accessibility
example <div tabindex="0" class="foo" id="element2" role="option" aria-posinset="1" aria-setsize="15" aria-flowto="element8" x-ms-aria-flowfrom="element5"> see also aria relationship attributes microsoft api extensions ...
How to file ARIA-related bugs - Accessibility
here's where to file bugs: when finding a bug, please also update the relevant compatibility tables in the examples page.
ARIA: tabpanel role - Accessibility
examples fill in a simple example that nicely shows a typical usage of the property, then perhaps some more complex examples.
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: 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: Comment role - Accessibility
examples in the following example we have a document section that has been commented.
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: Main role - Accessibility
example <body> <!-- primary navigation --> <div role="main"> <h1>the the first indochina war</h1> <!-- article content --> </div> <!-- sidebar and footer --> </body> accessibility concerns use only one main role per document the main landmark role should only be used once per document.
ARIA: Mark role - Accessibility
examples in the following example we have a document section that has been commented.
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</spa...
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: tab role - Accessibility
example this example combines the role tab with tablist and elements with tabpanel to create an interactive group of tabbed content.
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</spa...
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.
HTML To MSAA - Accessibility
for example, if name column has n/a value then it means specific elements doesn't provide own rules to calculate name but name can be computed from aria markup or @title attribute.
-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 sta...
-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-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-security - CSS: Cascading Style Sheets
examples obscuring a text input try typing in the field below.
-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 s...
-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-broken - CSS: Cascading Style Sheets
syntax :-moz-broken examples html <img src="broken.jpg" alt="this image is broken.
:-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-first-node - CSS: Cascading Style Sheets
syntax :-moz-first-node examples css span:-moz-first-node { background-color: lime; } html <p> <span>this matches!</span> <span>this doesn't match.</span> </p> <p> blahblah.
:-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-locale-dir(ltr) - CSS: Cascading Style Sheets
syntax :-moz-locale-dir(ltr) examples this example doesn't work if you're not using firefox, and may not work even in firefox due to an issue with the selector not working propertly with html content.
:-moz-locale-dir(rtl) - CSS: Cascading Style Sheets
syntax :-moz-locale-dir(rtl) examples this example will not work if you're not using firefox, and might not work properly even in firefox due to an issue with using this selector in html.
:-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-suppressed - CSS: Cascading Style Sheets
syntax :-moz-suppressed examples styling elements that have been blocked :-moz-suppressed { background: yellow; padding: 8px; } specifications not part of any standard.
:-moz-ui-invalid - CSS: Cascading Style Sheets
see the :invalid pseudo-class for an example that shows how to override the default style.
:-moz-user-disabled - CSS: Cascading Style Sheets
syntax :-moz-user-disabled examples styling user-disabled elements :-moz-user-disabled { background-color: lightgray; padding: 8px; } specifications not part of any standard.
:-moz-window-inactive - CSS: Cascading Style Sheets
syntax :-moz-window-inactive examples this example alters the appearance of a box's background depending on whether its window is active or not.
::-moz-color-swatch - CSS: Cascading Style Sheets
examples html <input type="color" value="#de2020" /> css input[type=color]::-moz-color-swatch { border-radius: 10px; border-style: none; } result specifications not part of any standard.
::-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; } re...
::-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-meter-even-less-good-value - CSS: Cascading Style Sheets
examples html <meter min="0" max="10" value="6">score out of 10</meter> css meter::-webkit-meter-even-less-good-value { background: linear-gradient(to bottom, #f77, #d44 45%, #d44 55%, #f77); height: 100%; box-sizing: border-box; } result ...
::-webkit-meter-inner-element - CSS: Cascading Style Sheets
examples this will only work in webkit and blink-based browsers, such as safari, chrome, and chromium-based versions of edge.
::-webkit-meter-optimum-value - CSS: Cascading Style Sheets
examples this example will only work in browsers based on webkit or blink.
::-webkit-meter-suboptimum-value - CSS: Cascading Style Sheets
syntax ::-webkit-meter-suboptimum-value examples this example will only work in browsers based on webkit or blink.
::-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-progress-value - CSS: Cascading Style Sheets
syntax ::-webkit-progress-value examples this example will only work in browsers based on blink or webkit.
::-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; b...
::cue - CSS: Cascading Style Sheets
WebCSS::cue
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-line (:first-line) - CSS: Cascading Style Sheets
syntax /* css3 syntax */ ::first-line /* css2 syntax */ :first-line examples html <p>styles will only be applied to the first line of this paragraph.
::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
WebCSS::marker
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
WebCSS::part
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 { bac...
::selection - CSS: Cascading Style Sheets
syntax /* legacy firefox syntax (version 61 and below) */ ::-moz-selection ::selection examples html this text has special styles when you highlight it.
::slotted() - CSS: Cascading Style Sheets
WebCSS::slotted
'='<attr-modifier> = i | s examples highlighting slotted elements the following snippets are taken from our slotted-pseudo-element demo (see it live also).
::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
WebCSS:active
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
WebCSS:any-link
/* 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 4...
:blank - CSS: Cascading Style Sheets
WebCSS:blank
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.
:default - CSS: Cascading Style Sheets
WebCSS:default
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</la...
:dir() - CSS: Cascading Style Sheets
WebCSS:dir
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.
:disabled - CSS: Cascading Style Sheets
WebCSS:disabled
/* selects any disabled <input> */ input:disabled { background: #ccc; } syntax :disabled examples this example shows a basic shipping form.
:empty - CSS: Cascading Style Sheets
WebCSS:empty
/* 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
WebCSS:enabled
/* 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
WebCSS:first
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-visible - CSS: Cascading Style Sheets
syntax :focus-visible examples basic example in this example, the :focus-visible selector uses the ua's behavior to determine when to match.
:focus - CSS: Cascading Style Sheets
WebCSS:focus
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.
:fullscreen - CSS: Cascading Style Sheets
examples in this example, the color of a button is changed depending on whether or not the document is in full-screen mode.
:has() - CSS: Cascading Style Sheets
WebCSS:has
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 ...
:hover - CSS: Cascading Style Sheets
WebCSS:hover
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
WebCSS:in-range
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.
:invalid - CSS: Cascading Style Sheets
WebCSS:invalid
syntax :invalid examples this example presents a simple form that colors elements green when they validate and red when they don't.
:lang() - CSS: Cascading Style Sheets
WebCSS:lang
examples in this example, the :lang() pseudo-class is used to match the parents of quote elements (<q>) using child combinators.
: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.
: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) { fo...
: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.
:optional - CSS: Cascading Style Sheets
WebCSS:optional
syntax :optional examples see :invalid for an example.
: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-...
:required - CSS: Cascading Style Sheets
WebCSS:required
syntax :required examples see :invalid for an example.
:root - CSS: Cascading Style Sheets
WebCSS:root
/* 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
WebCSS:scope
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.
:state() - CSS: Cascading Style Sheets
WebCSS:state
examples fill in a simple example that nicely shows a typical usage of the selector, then perhaps some more complex examples.
:valid - CSS: Cascading Style Sheets
WebCSS:valid
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 + sp...
:visited - CSS: Cascading Style Sheets
WebCSS:visited
syntax :visited examples properties that would otherwise have no color or be transparent cannot be modified with :visited.
@charset - CSS: Cascading Style Sheets
WebCSS@charset
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 charse...
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 ...
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 ...
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 ...
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 ...
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 displa...
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 'suff...
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 'symb...
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 ...
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.
@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
WebCSS@import
<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 ...
-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.
-webkit-animation - CSS: Cascading Style Sheets
examples @media (-webkit-animation) { /* css to use if animations are supported */ } specifications not part of any standard.
-webkit-device-pixel-ratio - CSS: Cascading Style Sheets
} examples html <p>this is a test of your device's pixel density.</p> css /* exact resolution */ @media (-webkit-device-pixel-ratio: 1) { p { color: red; } } /* minimum resolution */ @media (-webkit-min-device-pixel-ratio: 1.1) { p { font-size: 1.5em; } } /* maximum resolution */ @media (-webkit-max-device-pixel-ratio: 3) { p { background: yellow; } } result specification...
-webkit-transform-2d - CSS: Cascading Style Sheets
examples basic example @media (-webkit-transform-2d) { div { -webkit-transform: translate(100px, 100px); } } this media feature is only supported by webkit.
-webkit-transform-3d - CSS: Cascading Style Sheets
examples @media (-webkit-transform-3d) { .foo { transform-style: preserve-3d; } } @media (-webkit-transform-3d: 1) { .foo { transform-style: preserve-3d; } } specifications specification status comment compatibility standardthe definition of '-webkit-transform-3d' in that specification.
any-hover - CSS: Cascading Style Sheets
WebCSS@mediaany-hover
examples testing whether input methods can hover html <a href="#">try hovering over me!</a> css @media (any-hover: hover) { a:hover { background: yellow; } } result specifications specification status comment media queries level 4the definition of 'any-hover' in that specification.
any-pointer - CSS: Cascading Style Sheets
examples this example creates a small checkbox for users with at least one fine pointer and a large checkbox for users with at least one coarse pointer.
aural - CSS: Cascading Style Sheets
WebCSS@mediaaural
examples basic example @media aural { body { voice-family: paul } } specifications specification status comment css level 2 (revision 2)the definition of 'aural' in that specification.
color-gamut - CSS: Cascading Style Sheets
examples html <p>this is a test.</p> css @media (color-gamut: srgb) { p { background: #f4ae8a; } } result specifications specification status comment media queries level 4the definition of 'color-gamut' in that specification.
color-index - CSS: Cascading Style Sheets
examples basic example html <p>this is a test.</p> css p { color: black; } @media (color-index) { p { color: red; } } @media (min-color-index: 15000) { p { color: #1475ef; } } result custom stylesheet this html will apply a special stylesheet for devices that have at least 256 colors.
device-aspect-ratio - CSS: Cascading Style Sheets
examples article { padding: 1rem; } @media screen and (min-device-aspect-ratio: 16/9) { article { padding: 1rem 5vw; } } specifications specification status comment media queries level 4the definition of 'device-aspect-ratio' in that specification.
device-height - CSS: Cascading Style Sheets
examples this html applies a special stylesheet for devices that are shorter than 800 pixels.
device-width - CSS: Cascading Style Sheets
examples this html applies a special stylesheet for devices that are narrower than 800 pixels.
display-mode - CSS: Cascading Style Sheets
(none) examples @media all and (display-mode: fullscreen) { body { margin: 0; border: 5px solid black; } } specifications specification status comment web app manifestthe definition of 'display-mode' in that specification.
height - CSS: Cascading Style Sheets
WebCSS@mediaheight
examples html <div>watch this element as you resize your viewport's height.</div> css /* exact height */ @media (height: 360px) { div { color: red; } } /* minimum height */ @media (min-height: 25rem) { div { background: yellow; } } /* maximum height */ @media (max-height: 40rem) { div { border: 2px solid blue; } } result specifications specification status comment ...
hover - CSS: Cascading Style Sheets
WebCSS@mediahover
examples html <a href="#">try hovering over me!</a> css @media (hover: hover) { a:hover { background: yellow; } } result specifications specification status comment media queries level 4the definition of 'hover' in that specification.
inverted-colors - CSS: Cascading Style Sheets
examples html <p>if you're using inverted colors, this text should be blue on white (the inverse of yellow on black).
monochrome - CSS: Cascading Style Sheets
WebCSS@mediamonochrome
examples html <p class="mono">your device supports monochrome pixels!</p> <p class="no-mono">your device doesn't support monochrome pixels.</p> css p { display: none; } /* any monochrome device */ @media (monochrome) { p.mono { display: block; color: #333; } } /* any non-monochrome device */ @media (monochrome: 0) { p.no-mono { display: block; color: #ee3636; } } result ...
orientation - CSS: Cascading Style Sheets
examples html <div>box 1</div> <div>box 2</div> <div>box 3</div> css body { display: flex; } div { background: yellow; } @media (orientation: landscape) { body { flex-direction: row; } } @media (orientation: portrait) { body { flex-direction: column; } } result specifications specification status comment media queries level 4the definition of '...
overflow-block - CSS: Cascading Style Sheets
examples html <p>lorem ipsum dolor sit amet, consectetur adipiscing elit.
overflow-inline - CSS: Cascading Style Sheets
examples html <p>lorem ipsum dolor sit amet, consectetur adipiscing elit.
pointer - CSS: Cascading Style Sheets
WebCSS@mediapointer
examples this example creates a small checkbox for users with fine primary pointers and a large checkbox for users with coarse primary pointers.
prefers-color-scheme - CSS: Cascading Style Sheets
examples the elements below have an initial color theme.
prefers-contrast - CSS: Cascading Style Sheets
examples this example has an annoying low contrast by default.
resolution - CSS: Cascading Style Sheets
WebCSS@mediaresolution
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 ...
scan - CSS: Cascading Style Sheets
WebCSS@mediascan
examples html <p>if your screen uses interlaced rendering, this text should be in a sans-serif font.
scripting - CSS: Cascading Style Sheets
WebCSS@mediascripting
examples html <p class="script-none">you do not have scripting available.
shape - CSS: Cascading Style Sheets
WebCSS@mediashape
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
WebCSS@mediawidth
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 def...
@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 com...
bleed - CSS: Cascading Style Sheets
WebCSS@pagebleed
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
WebCSS@pagemarks
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
WebCSS@pagesize
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
WebCSS@page
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
WebCSS@viewportheight
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.
zoom - CSS: Cascading Style Sheets
WebCSS@viewportzoom
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
WebCSS@viewport
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.
At-rules - CSS: Cascading Style Sheets
WebCSSAt-rule
/* general structure */ @identifier (rule); /* example: tells browser to use utf-8 character set */ @charset "utf-8"; there are several at-rules, designated by their identifiers, each with a different syntax: @charset — defines the character set used by the style sheet.
Using multiple backgrounds - CSS: Cascading Style Sheets
example in this example, three backgrounds are stacked: the firefox logo, an image of bubbles, and a linear gradient: html <div class="multi-bg-example"></div> css .multi-bg-example { width: 100%; height: 400px; background-image: url(https://mdn.mozillademos.org/files/11305/firefox.png), url(https://mdn.mozillademos.org/files/11307/bubbles.png), linear-gradient(to right, rgba(30, 7...
Box alignment for block, absolutely positioned and table layout - CSS: Cascading Style Sheets
in the example below, a container with a single item inside has been turned into a flex container for the purpose of being able to use the alignment properties.
Box alignment in Flexbox - CSS: Cascading Style Sheets
basic example in this example, three flex items are aligned on the main axis using justify-content and on the cross axis using align-items.
Mastering margin collapsing - CSS: Cascading Style Sheets
examples html <p>the bottom margin of this paragraph is collapsed …</p> <p>… with the top margin of this paragraph, yielding a margin of <code>1.2rem</code> in between.</p> <div>this parent element contains two paragraphs!
CSS Multi-column Layout - CSS: Cascading Style Sheets
basic example in the following example the column-count property has been applied to the element with a class of container.
CSS Flexible Box Layout - CSS: Cascading Style Sheets
basic example in the following example a container has been set to display: flex, which means that the three child items become flex items.
CSS Flow Layout - CSS: Cascading Style Sheets
basic example the following example demonstrates block and inline level boxes.
Implementing image sprites in CSS - CSS: Cascading Style Sheets
for example: #btn1 { background-position: -20px 0px; } #btn2 { background-position: -40px 0px; } this would move the element with the id 'btn1' 20 pixels to the left and the element with the id 'btn2' 40 pixels to the left (assuming they have the class toolbtn assigned and are affected by the image rule above).
CSS Motion Path - CSS: Cascading Style Sheets
basic example <div id="motion-demo"></div> #motion-demo { offset-path: path('m20,20 c20,100 200,0 200,100'); animation: move 3000ms infinite alternate ease-in-out; width: 40px; height: 40px; background: cyan; } @keyframes move { 0% { offset-distance: 0%; } 100% { offset-distance: 100%; } } reference properties offset offset-anchor offset-distance offset-path offset-pos...
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 Properties Reference - CSS: Cascading Style Sheets
the reference articles also include examples on how to use all the properties.
CSS Scrollbars - CSS: Cascading Style Sheets
basic example in this example we have chosen to use a thin scrollbar, with a green track and purple thumb.
CSS Shapes - CSS: Cascading Style Sheets
basic example the example below shows an image that has been floated left, and the shape-outside property applied with a value of circle(50%).
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 ...
Introducing the CSS Cascade - CSS: Cascading Style Sheets
WebCSSCascade
example let's look at an example involving multiple sources of css across the various origins; here we have a user agent style sheet, two author style sheets, a user stylesheet, and inline styles within the html: user-agent css: li { margin-left: 10px } author css 1: li { margin-left: 0 } /* this is a reset */ author css 2: @media screen { li { margin-left: 3px } } @media print { li { margin-...
Child combinator - CSS: Cascading Style Sheets
syntax selector1 > selector2 { style properties } examples css span { background-color: white; } div > span { background-color: dodgerblue; } html <div> <span>span #1, in the div.
Class selectors - CSS: Cascading Style Sheets
/* all elements with class="spacious" */ .spacious { margin: 2em; } /* all <li> elements with class="spacious" */ li.spacious { margin: 2em; } /* all <li> elements with a class list that includes both "spacious" and "elegant" */ /* for example, class="elegant retro spacious" */ li.spacious.elegant { margin: 2em; } syntax .class_name { style properties } note that this is equivalent to the following attribute selector: [class~=class_name] { style properties } examples css .red { color: #f33; } .yellow-bg { background: #ffa; } .fancy { font-weight: bold; text-shadow: 4px 4px 3px #77f; } html <p class="red">this paragraph has red text.</p> <p class="red yellow-bg">this paragraph has...
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 ...
Comments - CSS: Cascading Style Sheets
WebCSSComments
/* 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 select...
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.
Breadcrumb Navigation - CSS: Cascading Style Sheets
recipe download this example note: the example above uses two selectors to insert content before every li except the first one.
Card - CSS: Cascading Style Sheets
recipe download this example choices made the card is laid out using css grid layout despite being a single dimensional layout, as it enables the use of content sizing for the grid tracks.
Center an element - CSS: Cascading Style Sheets
recipe download this example choices made to center one box inside another we make the containing box a flex container.
Grid wrapper - CSS: Cascading Style Sheets
recipe download this example choices made this recipe uses the css grid minmax() function to define the grid track sizes in the grid-template-columns property.
Pagination - CSS: Cascading Style Sheets
recipe download this example choices made this pattern is laid out using flexbox — one flex container nested inside another.
Split Navigation - CSS: Cascading Style Sheets
recipe download this example choices made this pattern combines auto margins with flexbox to split the items.
CSS Layout cookbook - CSS: Cascading Style Sheets
see this page for a template and guidelines for writing your own example.
Testing media queries programmatically - CSS: Cascading Style Sheets
for example, to set up a query list that determines if the device is in landscape or portrait orientation: const mediaquerylist = window.matchmedia("(orientation: portrait)"); checking the result of a query once you've created your media query list, you can check the result of the query by looking at the value of its matches property: if (mediaquerylist.matches) { /* the viewport is currently in portr...
Media queries - CSS: Cascading Style Sheets
for example, a media query can shrink the font size on small devices, increase the padding between paragraphs when a page is viewed in portrait mode, or bump up the size of buttons on touchscreens.
Pseudo-elements - CSS: Cascading Style Sheets
for example, ::first-line can be used to change the font of the first line of a paragraph.
CSS reference - CSS: Cascading Style Sheets
WebCSSReference
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.
Selector list - CSS: Cascading Style Sheets
syntax element, element, element { style properties } examples single line grouping grouping selectors in a single line using a comma-separated lists.
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; specification...
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
WebCSSattr
)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-backg...
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),...
<blend-mode> - CSS: Cascading Style Sheets
examples blend mode comparison in the following example, we have a <div> with two background images set on it — a firefox logo on top of a linear gradient.
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 de...
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 leve...
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 1t...
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-b...
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 ...
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 comm...
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 ...
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 'bord...
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-widt...
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-...
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 comm...
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 ...
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 functiona...
box-lines - CSS: Cascading Style Sheets
WebCSSbox-lines
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 f...
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
WebCSSclip
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...
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.
Computed value - CSS: Cascading Style Sheets
for example, if an element has specified values font-size: 16px and padding-top: 2em, then the computed value of padding-top is 32px (double the font size).
contain - CSS: Cascading Style Sheets
WebCSScontain
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 { ...
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
WebCSScounter
)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...
<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 escape...
<display-internal> - CSS: Cascading Style Sheets
examples css tables example the following example demonstrates laying out a simple form using css table layout.
<display-legacy> - CSS: Cascading Style Sheets
examples in the below example, we are creating an inline flex container with the legacy keyword inline-flex.
<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-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-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 leve...
<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 n...
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
WebCSSident
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-set() - CSS: Cascading Style Sheets
WebCSSimage-set
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
WebCSSimage
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 ...
ime-mode - CSS: Cascading Style Sheets
WebCSSime-mode
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.
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-alig...
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: ...
initial - CSS: Cascading Style Sheets
WebCSSinitial
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 spe...
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 ...
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 valu...
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 pro...
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 an...
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 propertie...
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 p...
inset - CSS: Cascading Style Sheets
WebCSSinset
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
WebCSSinteger
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.
<length> - CSS: Cascading Style Sheets
WebCSSlength
examples length unit comparison the following demo provides you with an input field in which you can enter a <length> value (e.g.
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 le...
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 ...
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; } articl...
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 - 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
WebCSSmask-clip
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"> <opt...
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="composi...
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 lev...
mask-mode - CSS: Cascading Style Sheets
WebCSSmask-mode
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> <op...
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">c...
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-size - CSS: Cascading Style Sheets
WebCSSmask-size
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 <di...
mask-type - CSS: Cascading Style Sheets
WebCSSmask-type
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> ...
mask - CSS: Cascading Style Sheets
WebCSSmask
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.
<number> - CSS: Cascading Style Sheets
WebCSSnumber
examples valid numbers 12 a raw <integer> is also a <number>.
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 spe...
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
WebCSSoffset
examples animating an element along a path html <div id="offsetelement"></div> css @keyframes move { from { offset-distance: 0%; } to { offset-distance: 100%; } } #offsetelement { width: 50px; height: 50px; background-color: blue; offset: path("m 100 100 l 300 100 l 200 300 z") auto; animation: move 3s linear infinite; } result specifications specification...
orphans - CSS: Cascading Style Sheets
WebCSSorphans
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.
Guide to scroll anchoring - CSS: Cascading Style Sheets
for example, if you opt out for the entire document, you will not be able to set overflow-anchor: auto elsewhere in the document to turn it back on for a subsection.
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 valu...
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 va...
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 ...
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-ord...
<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.
<ratio> - CSS: Cascading Style Sheets
WebCSSratio
examples use in a media query @media screen and (min-aspect-ratio: 16/9) { ...
repeat() - CSS: Cascading Style Sheets
WebCSSrepeat
examples specifying grid columns using repeat() html <div id="container"> <div> this item is 50 pixels wide.
<resolution> - CSS: Cascading Style Sheets
examples use in a media query @media print and (min-resolution: 300dpi) { ...
rotate - CSS: Cascading Style Sheets
WebCSSrotate
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
WebCSSscale
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-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> <di...
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: ce...
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.
<shape> - CSS: Cascading Style Sheets
WebCSSshape
example img.clip04 { clip: rect(10px, 20px, 20px, 10px); } specifications specification status comment css level 2 (revision 1)the definition of '<shape>' in that specification.
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.
symbols() - CSS: Cascading Style Sheets
WebCSSsymbols
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
WebCSStab-size
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-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-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 definitio...
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.
<time-percentage> - CSS: Cascading Style Sheets
examples use in calc() where a <time-percentage> is specified as an allowable type, this means that the percentage resolves to a time and therefore can be used in a calc() expression.
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.
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.
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 sp...
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.
translate - CSS: Cascading Style Sheets
WebCSStranslate
]?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: 200...
unset - CSS: Cascading Style Sheets
WebCSSunset
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 cl...
<url> - CSS: Cascading Style Sheets
WebCSSurl
<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 mod...
Used value - CSS: Cascading Style Sheets
example this example computes and displays the used width value of three elements (updates on resize): html <div id="no-width"> <p>no explicit width.</p> <p class="show-used-width">..</p> <div id="width-50"> <p>explicit width: 50%.</p> <p class="show-used-width">..</p> <div id="width-inherit"> <p>explicit width: inherit.</p> <p class="show-used-width">..</p> </div> ...
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-se...
widows - CSS: Cascading Style Sheets
WebCSSwidows
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.
zoom - CSS: Cascading Style Sheets
WebCSSzoom
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 { ...
CSS: Cascading Style Sheets
WebCSS
css first steps css (cascading style sheets) is used to style and layout web pages — for example, to alter the font, color, size, and spacing of your content, split it into multiple columns, or add animations and other decorative features.
regexp:match() - EXSLT
WebEXSLTregexpmatch
for example: <xsl:for-each select="regexp:match('http://developer.mozilla.org/en/docs/firefox_3_for_developers', '(\w+):\/\/([^/:]+)(:\d*)?([^# ]*)')"> part <xsl:value-of select="position()" /> = <xsl:value-of select="." /> </xsl:for-each> this code generates the following output: part 1 = http://developer.mozilla.org/en/docs/firefox_3_for_developers part 2 = http pa...
str:split() - EXSLT
WebEXSLTstrsplit
example str:split('book, phone, computer, chair', ', ') returns a node set like: <token>book</token> <token>phone</token> <token>computer</token> <token>chair</token> specifications exslt - str:split ...
str:tokenize() - EXSLT
WebEXSLTstrtokenize
example: str:tokenize('2007-09-14-03t11:40:23', '-t:') returns a node set like this: <token>2007</token> <token>09</token> <token>14</token> <token>11</token> <token>40</token> <token>23</token> specifications exslt - str:tokenize ...
EXSLT
for example, to use the regular expressions package: <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/xsl/transform" xmlns:regexp="http://exslt.org/regular-expressions"> <xsl:template match="/"> ...
Mouse gesture events - Developer guides
this is typically used to zoom in and out on content (this is the default behavior in firefox, for example).
Content categories - Developer guides
for example, the <del> and <ins> elements are transparent: <p>we hold these truths to be <del><em>sacred &amp; undeniable</em></del> <ins>self-evident</ins>.</p> if those elements were removed, this fragment would still be valid html (if not correct english).
HTML5 - Developer guides
WebGuideHTMLHTML5
html5 reference guide quick-reference html5 sheet containing markup generators, code examples and web developer tools.
XHTML - Developer guides
WebGuideHTMLXHTML
the following example shows an html document and corresponding "xhtml" document, and the accompanying http content-type headers they should be served with.
Mobile Web Development - Developer guides
WebGuideMobile
for example, if you set a gradient as a background for some text using a vendor-prefixed property like -webkit-linear-gradient, it's best to include the other vendor-prefixed versions of the linear-gradient() property.
HTML attribute: capture - HTML: Hypertext Markup Language
examples when set on a file input type, operating systems with microphones and cameras will display a user interface allowing the selection from an existing file or the creating of a new one.
HTML attribute: maxlength - HTML: Hypertext Markup Language
examples <input type="password" maxlength="4"/> specifications specification status html living standardthe definition of 'maxlength attribute' in that specification.
HTML attribute: minlength - HTML: Hypertext Markup Language
examples by adding minlength="5", the value must either be empty or five characters or longer to be valid.
HTML attribute: required - HTML: Hypertext Markup Language
example html <form> <div class="group"> <input type="text"> <label>normal</label> </div> <div class="group"> <input type="text" required="required"> <label>required</label> </div> <input type="submit"> </form> result ...
HTML attribute: size - HTML: Hypertext Markup Language
WebHTMLAttributessize
examples by adding size on some input types, the width of the input can be controlled.
Block-level elements - HTML: Hypertext Markup Language
the following example demonstrates the block-level element's influence: block-level elements html <p>this paragraph is a block-level element; its background has been colored to display the paragraph's parent element.</p> css p { background-color: #8abb55; } usage block-level elements may appear only within a <body> element.
<acronym> - HTML: Hypertext Markup Language
WebHTMLElementacronym
example <p>the <acronym title="world wide web">www</acronym> is only a component of the internet.</p> default styling though the purpose of this tag is purely for the convenience of the author, its default styling varies from one browser to another: some browsers, like internet explorer, do not style it differently than a <span> element.
<applet>: The Embed Java Applet element - HTML: Hypertext Markup Language
WebHTMLElementapplet
example html <applet code="game.class" align="left" archive="game.zip" height="250" width="350"> <param name="difficulty" value="easy"> <b>sorry, you need java to play this game.</b> </applet> specifications specification status comment html 5.2the definition of '<applet>' in that specification.
<basefont> - HTML: Hypertext Markup Language
WebHTMLElementbasefont
example <basefont color="#ff0000" face="helvetica" size="+2" /> ...
<bgsound>: The Background Sound element (obsolete) - HTML: Hypertext Markup Language
WebHTMLElementbgsound
example <bgsound src="sound1.mid"> <bgsound src="sound2.au" loop="infinite"> usage notes historically, the <embed> element could be used with audio player plug-ins to play audio in the background in most browsers.
<blink>: The Blinking Text element (obsolete) - HTML: Hypertext Markup Language
WebHTMLElementblink
example <blink>why would somebody use this?</blink> result (toned down!) specification this element is non-standard and not part of any specification.
<body>: The Document Body element - HTML: Hypertext Markup Language
WebHTMLElementbody
example <html> <head> <title>document title</title> </head> <body> <p>this is a paragraph</p> </body> </html> specifications specification status comment html living standardthe definition of '<body>' in that specification.
<canvas>: The Graphics Canvas element - HTML: Hypertext Markup Language
WebHTMLElementcanvas
examples html this code snippet adds a canvas element to your html document.
<command>: The HTML Command element - HTML: Hypertext Markup Language
WebHTMLElementcommand
examples <command type="command" label="save" icon="icons/save.png" onclick="save()"> specifications specification status comment html5the definition of '<command>' in that specification.
<content>: The Shadow DOM Content Placeholder element (obsolete) - HTML: Hypertext Markup Language
WebHTMLElementcontent
example here is a simple example of using the <content> element.
<frame> - HTML: Hypertext Markup Language
WebHTMLElementframe
example <frameset cols="50%,50%"> <frame src="https://udn.realityripple.com/docs/web/html/element/iframe" /> <frame src="https://udn.realityripple.com/docs/web/html/element/frame" /> </frameset> ...
<frameset> - HTML: Hypertext Markup Language
WebHTMLElementframeset
example <frameset cols="50%,50%"> <frame src="https://udn.realityripple.com/docs/web/html/element/frameset" /> <frame src="https://udn.realityripple.com/docs/web/html/element/frame" /> </frameset> ...
<head>: The Document Metadata (Header) element - HTML: Hypertext Markup Language
WebHTMLElementhead
example <!doctype html> <html> <head> <title>document title</title> </head> </html> notes html5-compliant browsers automatically create a <head> element if its tags are omitted in the markup.
<html>: The HTML Document / Root element - HTML: Hypertext Markup Language
WebHTMLElementhtml
example <!doctype html> <html lang="en"> <head>...</head> <body>...</body> </html> accessibility concerns providing a lang attribute with a valid ietf identifying language tag on the <html> element will help screen reading technology determine the proper language to announce.
<isindex> - HTML: Hypertext Markup Language
WebHTMLElementisindex
example <head> <isindex prompt="search document..." action="/search"> </head> in past browsers, this would generate, at parse time, a dom tree equivalent to the following html: <form action="/search"> <hr> <label> search document...
<marquee>: The Marquee element (Obsolete) - HTML: Hypertext Markup Language
WebHTMLElementmarquee
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 li...
<menu> - HTML: Hypertext Markup Language
WebHTMLElementmenu
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; } ...
<menuitem> - HTML: Hypertext Markup Language
WebHTMLElementmenuitem
example html content <!-- 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 type="checkbox" checked>checkbox</menuitem> <hr> <menuitem type="command" label="this command does nothing" icon="https://developer.cdn.mozilla.net/static/img/favicon144.png"> commands don't rend...
theme-color - HTML: Hypertext Markup Language
WebHTMLElementmetanametheme-color
example <meta name="theme-color" content="#4285f4"> the following image shows the effect that the <meta> element above will have on a document displayed in chrome running on an android mobile device.
Standard metadata names - HTML: Hypertext Markup Language
WebHTMLElementmetaname
for example, to indicate that a document prefers dark mode but does render functionally in light mode as well: <meta name="color-scheme" content="dark light"> this works at the document level in the same way that the css color-scheme property lets individual elements specify their preferred and accepted color schemes.
<meta>: The Document-level Metadata element - HTML: Hypertext Markup Language
WebHTMLElementmeta
examples <meta charset="utf-8"> <!-- redirect page after 3 seconds --> <meta http-equiv="refresh" content="3;url=https://www.mozilla.org"> specifications specification status comment html living standardthe definition of '<meta>' in that specification.
<noframes>: The Frame Fallback element - HTML: Hypertext Markup Language
WebHTMLElementnoframes
example in this example, we see a frameset with two frames.
<noscript> - HTML: Hypertext Markup Language
WebHTMLElementnoscript
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!
<output>: The Output element - HTML: Hypertext Markup Language
WebHTMLElementoutput
examples in the following example, the form provides a slider whose value can range between 0 and 100, and an <input> element into which you can enter a second number.
<param>: The Object Parameter element - HTML: Hypertext Markup Language
WebHTMLElementparam
examples please see the <object> page for examples on <param>.
<shadow>: The obsolete Shadow Root element - HTML: Hypertext Markup Language
WebHTMLElementshadow
example here is a simple example of using the <shadow> element.
<spacer> - HTML: Hypertext Markup Language
WebHTMLElementspacer
example <span>just a text node</span> <spacer type="horizontal" size="10"></spacer> <span>just another text node</span> <spacer type="block" width="10" height="10"></spacer> specification not part of any specification.
<strike> - HTML: Hypertext Markup Language
WebHTMLElementstrike
example &lt;strike&gt;: <strike>today's special: salmon</strike> sold out<br /> &lt;s&gt;: <s>today's special: salmon</s> sold out the result of this code is: specifications specification status comment html5the definition of '<strike>' in that specification.
<template>: The Content Template element - HTML: Hypertext Markup Language
WebHTMLElementtemplate
examples first we start with the html portion of the example.
<xmp> - HTML: Hypertext Markup Language
WebHTMLElementxmp
summary the html example element (<xmp>) renders text between the start and end tags without interpreting the html in between and using a monospaced font.
draggable - HTML: Hypertext Markup Language
for other elements, the event ondragstart must be set for drag and drop to work, as shown in this comprehensive example.
inputmode - HTML: Hypertext Markup Language
this may have the / key more prominent, for example.
is - HTML: Hypertext Markup Language
examples the following code is taken from our word-count-web-component example (see it live also).
part - HTML: Hypertext Markup Language
see our shadow part example for a usage example.
slot - HTML: Hypertext Markup Language
for examples, see our using templates and slots guide.
translate - HTML: Hypertext Markup Language
examples in this example, the translate attribute is used to ask translation tools not to translate the company's brand name in the footer.
x-ms-acceleratorkey - HTML: Hypertext Markup Language
for example: "ctrl+b" for a combination of the ctrl and b keys.
Link types: prerender - HTML: Hypertext Markup Language
the prerender keyword for the rel attribute of the <link> element is a hint to browsers that the user might need the target resource for the next navigation, and therefore the browser can likely improve the user experience by preemptively fetching and processing the resource — for example, by fetching its subresources or performing some rendering in the background offscreen.
Quirks Mode and Standards Mode - HTML: Hypertext Markup Language
to ensure that your page uses full standards mode, make sure that your page has a doctype like in this example: <!doctype html> <html lang="en"> <head> <meta charset=utf-8> <title>hello world!</title> </head> <body> </body> </html> the doctype shown in the example, <!doctype html>, is the simplest possible, and the one recommended by html5.
Evolution of HTTP - HTTP
for example, http pipelining has emerged as a resource burden in web development.
Reason: CORS header 'Access-Control-Allow-Origin' does not match 'xyz' - HTTP
for example, in apache, add a line such as the following to the server's configuration (within the appropriate <directory>, <location>, <files>, or <virtualhost> section).
Reason: CORS request external redirect not allowed - HTTP
for example, if the page https://service.tld/fetchdata were requested, and the http response is "301 moved permanently", "307 temporary redirect", or "308 permanent redirect" with a location of https://anotherservice.net/getdata, the cors request will fail in this manner.
Reason: Did not find method in CORS header ‘Access-Control-Allow-Methods’ - HTTP
for example, if the response includes: access-control-allow-methods: get,head,post trying to use a put request will fail with this error.
Reason: CORS header ‘Origin’ cannot be added - HTTP
this can happen if the javascript code is running with enhanced privileges allowing it access to multiple domains' content, for example.
CORS errors - HTTP
WebHTTPCORSErrors
for example, if a site offers an embeddable service, it may be necessary to relax certain restrictions.
Configuring servers for Ogg media - HTTP
for example, if the video is 1 minute and 32.6 seconds long, this header would be: x-content-duration: 92.6 if your server provides the x-content-duration header when serving ogg media, gecko doesn't have to do any extra http requests to seek to the end of the file to calculate its duration.
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
WebHTTPHeadersAccept
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-...
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.
Age - HTTP
WebHTTPHeadersAge
examples age: 24 specifications specification title rfc 7234, section 5.1: age hypertext transfer protocol (http/1.1): caching ...
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.
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-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: 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: 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.
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.
Cookie2 - HTTP
WebHTTPHeadersCookie2
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-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
WebHTTPHeadersDNT
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
WebHTTPHeadersDPR
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
WebHTTPHeadersDate
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.
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 ...
Expires - HTTP
WebHTTPHeadersExpires
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 ...
Feature-Policy: accelerometer - HTTP
<origin(s)>: the feature is allowed for specific origins (for example, https://example.com).
Feature-Policy: ambient-light-sensor - HTTP
<origin(s)>: the feature is allowed for specific origins (for example, https://example.com).
Feature-Policy: autoplay - HTTP
<origin(s)>: the feature is allowed for specific origins (for example, https://example.com).
Feature-Policy: battery - HTTP
<origin(s)>: the feature is allowed for specific origins (for example, https://example.com).
Feature-Policy: camera - HTTP
<origin(s)>: the feature is allowed for specific origins (for example, https://example.com).
Feature-Policy: display-capture - HTTP
<origin(s)>: the feature is allowed for specific origins (for example, https://example.com).
Feature-Policy: document-domain - HTTP
<origin(s)>: the feature is allowed for specific origins (for example, https://example.com).
Feature-Policy: encrypted-media - HTTP
<origin(s)>: the feature is allowed for specific origins (for example, https://example.com).
Feature-Policy: gyroscope - HTTP
<origin(s)>: the feature is allowed for specific origins (for example, https://example.com).
Feature-Policy: layout-animations - HTTP
<origin(s)>: the feature is allowed for specific origins (for example, https://example.com).
Feature-Policy: legacy-image-formats - HTTP
<origin(s)>: the feature is allowed for specific origins (for example, https://example.com).
Feature-Policy: magnetometer - HTTP
<origin(s)>: the feature is allowed for specific origins (for example, https://example.com).
Feature-Policy: microphone - HTTP
<origin(s)>: the feature is allowed for specific origins (for example, https://example.com).
Feature-Policy: midi - HTTP
<origin(s)>: the feature is allowed for specific origins (for example, https://example.com).
Feature-Policy: oversized-images - HTTP
<origin(s)>: the feature is allowed for specific origins (for example, https://example.com).
Feature-Policy: payment - HTTP
<origin(s)>: the feature is allowed for specific origins (for example, https://example.com).
Feature-Policy: picture-in-picture - HTTP
<origin(s)>: the feature is allowed for specific origins (for example, https://example.com).
Feature-Policy: publickey-credentials-get - HTTP
<origin(s)>: the feature is allowed for specific origins (for example, https://example.com).
Feature-Policy: screen-wake-lock - HTTP
<origin(s)>: the feature is allowed for specific origins (for example, https://example.com).
Feature-Policy: sync-xhr - HTTP
<origin(s)>: the feature is allowed for specific origins (for example, https://example.com).
Feature-Policy: unoptimized-images - HTTP
<origin(s)>: the feature is allowed for specific origins (for example, https://example.com).
Feature-Policy: unsized-media - HTTP
<origin(s)>: the feature is allowed for specific origins (for example, https://example.com).
Feature-Policy: usb - HTTP
<origin(s)>: the feature is allowed for specific origins (for example, https://example.com).
Feature-Policy: vibrate - HTTP
<origin(s)>: the feature is allowed for specific origins (for example, https://example.com).
Feature-Policy: wake-lock - HTTP
<origin(s)>: the feature is allowed for specific origins (for example, https://example.com).
web-share - HTTP
<origin(s)>: the feature is allowed for specific origins (for example, https://example.com).
Feature-Policy: xr-spatial-tracking - HTTP
<origin(s)>: the feature is allowed for specific origins (for example, https://example.com).
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 standardiz...
From - HTTP
WebHTTPHeadersFrom
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
WebHTTPHeadersHost
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
WebHTTPHeadersIf-Match
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-Range - HTTP
WebHTTPHeadersIf-Range
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 inte...
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
WebHTTPHeadersLink
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" spe...
Location - HTTP
WebHTTPHeadersLocation
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
WebHTTPHeadersOrigin
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
WebHTTPHeadersPragma
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
WebHTTPHeadersRange
examples requesting three ranges from the file.
Retry-After - HTTP
examples dealing with scheduled downtime support for the retry-after header on both clients and servers is still inconsistent.
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-Timing - HTTP
for example, you could only show metrics to authenticated users and nothing to the public.
Server - HTTP
WebHTTPHeadersServer
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-Cookie2 - HTTP
name>=<cookie-value>; domain=<domain-value> set-cookie2: <cookie-name>=<cookie-value>; max-age=<non-zero-digit> set-cookie2: <cookie-name>=<cookie-value>; path=<path-value> set-cookie2: <cookie-name>=<cookie-value>; port=<port-number> set-cookie2: <cookie-name>=<cookie-value>; secure set-cookie2: <cookie-name>=<cookie-value>; version=<version-number> // multiple directives are also possible, for example: set-cookie2: <cookie-name>=<cookie-value>; domain=<domain-value>; secure // multiple cookies are seperated by a comma set-cookie2: <cookie-name>=<cookie-value>, <cookie-name>=<cookie-value>, ...
SourceMap - HTTP
examples sourcemap: /path/to/file.js.map specifications specification title draft document source map revision 3 proposal ...
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
WebHTTPHeadersTk
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
WebHTTPHeadersTrailer
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.
Via - HTTP
WebHTTPHeadersVia
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 an...
Warning - HTTP
WebHTTPHeadersWarning
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-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.
X-XSS-Protection - HTTP
example block pages from loading when they detect reflected xss attacks: x-xss-protection: 1; mode=block php header("x-xss-protection: 1; mode=block"); apache (.htaccess) <ifmodule mod_headers.c> header set x-xss-protection "1; mode=block" </ifmodule> nginx add_header "x-xss-protection" "1; mode=block"; specifications not part of any specifications or drafts.
HTTP headers - HTTP
WebHTTPHeaders
for example, this header standard allows a client to change from http 1.1 to http 2.0, assuming the server decides to acknowledge and implement the upgrade header field.
HTTP Messages - HTTP
WebHTTPMessages
for example, get indicates that a resource should be fetched or post means that data is pushed to the server (creating or modifying a resource, or generating a temporary document to send back).
DELETE - HTTP
WebHTTPMethodsDELETE
request has body may successful response has body may safe no idempotent yes cacheable no allowed in html forms no syntax delete /file.html http/1.1 example request delete /file.html http/1.1 responses if a delete method is successfully applied, there are several response status codes possible: a 202 (accepted) status code if the action will likely succeed but has not yet been enacted.
HEAD - HTTP
WebHTTPMethodsHEAD
for example, if a url might produce a large download, a head request could read its content-length header to check the filesize without actually downloading the file.
PUT - HTTP
WebHTTPMethodsPUT
request has body yes successful response has body no safe no idempotent yes cacheable no allowed in html forms no syntax put /new.html http/1.1 example request put /new.html http/1.1 host: example.com content-type: text/html content-length: 16 <p>new file</p> responses if the target resource does not have a current representation and the put request successfully creates one, then the origin server must inform the user agent by sending a 201 (created) response.
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.
101 Switching Protocols - HTTP
WebHTTPStatus101
status 101 switching protocols examples switching protocols might be used with websockets.
205 Reset Content - HTTP
WebHTTPStatus205
the http 205 reset content response status tells the client to reset the document view, so for example to clear the content of a form, reset a canvas state, or to refresh the ui.
206 Partial Content - HTTP
WebHTTPStatus206
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 ...
301 Moved Permanently - HTTP
WebHTTPStatus301
status 301 moved permanently example client request get /index.php http/1.1 host: www.example.org server response http/1.1 301 moved permanently location: http://www.example.org/index.asp specifications specification title rfc 7231, section 6.4.2: 301 moved permanently hypertext transfer protocol (http/1.1): semantics and content ...
308 Permanent Redirect - HTTP
WebHTTPStatus308
for example, google drive uses a 308 resume incomplete response to indicate to the client when an incomplete upload stalled.[1] status 308 permanent redirect specifications specification title rfc 7538, section 3: 308 permanent redirect the hypertext transfer protocol status code 308 (permanent redirect) ...
401 Unauthorized - HTTP
WebHTTPStatus401
status 401 unauthorized example response http/1.1 401 unauthorized date: wed, 21 oct 2015 07:28:00 gmt www-authenticate: basic realm="access to staging site" specifications specification title rfc 7235, section 3.1: 401 unauthorized http/1.1: authentication ...
402 Payment Required - HTTP
WebHTTPStatus402
status 402 payment required example response http/1.1 402 payment required date: wed, 21 oct 2015 07:28:00 gmt specifications specification title rfc 7231, section 6.5.2: 402 payment required http/1.1: semantics and content ...
403 Forbidden - HTTP
WebHTTPStatus403
status 403 forbidden example response http/1.1 403 forbidden date: wed, 21 oct 2015 07:28:00 gmt specifications specification title rfc 7231, section 6.5.3: 403 forbidden http/1.1: semantics and content ...
407 Proxy Authentication Required - HTTP
WebHTTPStatus407
status 407 proxy authentication required example response http/1.1 407 proxy authentication required date: wed, 21 oct 2015 07:28:00 gmt proxy-authenticate: basic realm="access to internal site" specifications specification title rfc 7235, section 3.2: 407 proxy authentication required http/1.1: authentication ...
409 Conflict - HTTP
WebHTTPStatus409
for example, you may get a 409 response when uploading a file which is older than the one already on the server resulting in a version control conflict.
414 URI Too Long - HTTP
WebHTTPStatus414
there are a few rare conditions when this might occur: when a client has improperly converted a post request to a get request with long query information, when the client has descended into a loop of redirection (for example, a redirected uri prefix that points to a suffix of itself), or when the server is under attack by a client attempting to exploit potential security holes.
416 Range Not Satisfiable - HTTP
WebHTTPStatus416
content-range: bytes */12777 faced with this error, browsers usually either abort the operation (for example, a download will be considered as non-resumable) or ask for the whole document again.
426 Upgrade Required - HTTP
WebHTTPStatus426
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 ...
429 Too Many Requests - HTTP
WebHTTPStatus429
status 429 too many requests example http/1.1 429 too many requests content-type: text/html retry-after: 3600 specifications specification title rfc 6585, section 4: 429 too many requests additional http status codes ...
511 Network Authentication Required - HTTP
WebHTTPStatus511
network operators sometimes require some authentication, acceptance of terms, or other user interaction before granting access (for example in an internet café or at an airport).
HTTP response status codes - HTTP
WebHTTPStatus
for example, an api may forbid delete-ing a resource.
HTTP
WebHTTP
for instance, an html page from domain a (http://domaina.example/) makes a request for an image on domain b (http://domainb.foo/image.jpg) via the img element.
About JavaScript - JavaScript
node.js is a popular example of this.
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.
The legacy Iterator protocol - JavaScript
simple example with the old protocol function makeiterator(array){ var nextindex = 0; return { next: function(){ if(nextindex < array.length){ return array[nextindex++]; else throw new stopiteration(); } } } var it = makeiterator(['yo', 'ya']); console.log(it.next()); // 'yo' console.log(it.next()); // 'ya' try{ console.log(it...
Warning: -file- is being assigned a //# sourceMappingURL, but already has one - JavaScript
examples setting source maps setting a source map by using a comment in the file: //# sourcemappingurl=http://example.com/path/to/your/sourcemap.map or, alternatively, you can set a header to your javascript file: x-sourcemap: /path/to/file.js.map ...
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; ...
SyntaxError: invalid regular expression flag "x" - JavaScript
see sticky examples there are only six valid regular expression flags.
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: X.prototype.y called on incompatible type - JavaScript
examples invalid cases var myset = new set; ['bar', 'baz'].foreach(myset.add); // myset.add is a function, but "myset" is not captured as this.
ReferenceError: can't access lexical declaration`X' before initialization - JavaScript
examples invalid cases in this case, the variable "foo" is redeclared in the block statement using let.
TypeError: can't assign to property "x" on "y": not an object - JavaScript
examples invalid cases 'use strict'; var foo = "my string"; // the following line does nothing if not in strict mode.
TypeError: can't define property "x": "obj" is not extensible - JavaScript
examples adding new properties to a non-extensible objects in strict mode, attempting to add new properties to a non-extensible object throws a typeerror.
TypeError: property "x" is non-configurable and can't be deleted - JavaScript
examples attempting to delete non-configurable properties non-configurable properties are not super common, but they can be created using object.defineproperty() or object.freeze().
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.
TypeError: can't access dead object - JavaScript
examples checking if an object is dead components.utils offers a isdeadwrapper() method, which privileged code might use.
SyntaxError: applying the 'delete' operator to an unqualified name is deprecated - JavaScript
examples freeing the contents of a variable attempting to delete a plain variable, doesn't work in javascript and it throws an error in strict mode: 'use strict'; var x; // ...
Warning: String.x is deprecated; use String.prototype.x instead - JavaScript
examples deprecated syntax var num = 15; string.replace(num, /5/, '2'); standard syntax var num = 15; string(num).replace(/5/, '2'); shim the following is a shim to provide support to non-supporting browsers: /*globals define*/ // assumes all supplied string instance methods already present // (one may use shims for these if not available) (function() { 'use strict'; var i, // we could a...
ReferenceError: deprecated caller or arguments usage - JavaScript
examples deprecated function.caller or arguments.callee.caller function.caller and arguments.callee.caller are deprecated (see the reference articles for more information).
Warning: expression closures are deprecated - JavaScript
examples deprecated syntax expression closures omit curly braces or return statements from function declarations or from method definitions in objects.
SyntaxError: "0"-prefixed octal literals and octal escape seq. are deprecated - JavaScript
examples "0"-prefixed octal literals "use strict"; 03; // syntaxerror: "0"-prefixed octal literals and octal escape sequences // are deprecated octal escape sequences "use strict"; "\251"; // syntaxerror: "0"-prefixed octal literals and octal escape sequences // are deprecated valid octal numbers use a leading zero followed by the letter "o" or "o": 0o3; for octal escape sequences, you can ...
Warning: Date.prototype.toLocaleFormat is deprecated - JavaScript
examples deprecated syntax the date.prototype.tolocaleformat method is deprecated and will be removed (no cross-browser support, available in firefox only).
Warning: JavaScript 1.6's for-each-in loops are deprecated - JavaScript
examples object iteration for each...in has been used to iterate over the specified object values.
SyntaxError: identifier starts immediately after numeric literal - JavaScript
examples variable names starting with numeric literals variable names can't start with numbers in javascript.
RangeError: invalid array length - JavaScript
examples invalid cases new array(math.pow(2, 40)) new array(-1) new arraybuffer(math.pow(2, 32)) new arraybuffer(-1) let a = []; a.length = a.length - 1; // set -1 to the length property let b = new array(math.pow(2, 32) - 1); b.length = b.length + 1; // set 2^32 to the length property valid cases [ math.pow(2, 40) ] // [ 1099511627776 ] [ -1 ] ...
RangeError: invalid date - JavaScript
examples invalid cases unrecognizable strings or dates containing illegal element values in iso formatted strings usually return nan.
SyntaxError: for-in loop head declarations may not have initializers - JavaScript
examples this example throws a syntaxerror: "use strict"; var obj = {a: 1, b: 2, c: 3 }; for (var i = 0 in obj) { console.log(obj[i]); } // syntaxerror: for-in loop head declarations may not have initializers valid for-in loop you can remove the initializer (i = 0) in the head of the for-in loop.
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 u...
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 ...
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 property id - JavaScript
var obj = { propertykey: 'value' }; examples colons vs.
SyntaxError: missing formal parameter - JavaScript
examples provide proper function parameters function parameters must be identifiers when setting up a function.
SyntaxError: missing = in const declaration - JavaScript
examples missing const initializer unlike var or let, you must specify a value for a const declaration.
RangeError: repeat count must be non-negative - JavaScript
examples invalid cases 'abc'.repeat(-1); // 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) ...
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.
TypeError: "x" has no properties - JavaScript
examples null and undefined have no properties null.foo; // typeerror: null has no properties undefined.bar; // typeerror: undefined has no properties ...
SyntaxError: missing variable name - JavaScript
examples missing a variable name var = "foo"; it's tough coming up with good variable names.
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.fromco...
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.
ReferenceError: "x" is not defined - JavaScript
examples variable not declared foo.substring(1); // referenceerror: foo is not defined the "foo" variable isn't defined anywhere.
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> ...
TypeError: "x" is read-only - JavaScript
examples invalid cases read-only properties are not super common, but they can be created using object.defineproperty() or object.freeze().
SyntaxError: redeclaration of formal parameter "x" - JavaScript
examples redeclared argument in this case, the variable "arg" redeclares the argument.
TypeError: Reduce of empty array with no initial value - JavaScript
examples invalid cases this problem appears frequently when combined with a filter (array.prototype.filter(), typedarray.prototype.filter()) which will remove all elements of the list.
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: ret...
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 outsi...
TypeError: invalid arguments - JavaScript
examples no strings in typed arrays typed arrays, for example a uint8array, can't be constructed from a string.
ReferenceError: reference to undefined property "x" - JavaScript
examples invalid cases in this case, the property bar is an undefined property, so a referenceerror will occur.
SyntaxError: Unexpected token - JavaScript
examples expression expected for example, when chaining expressions, trailing commas are not allowed.
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: variable "x" redeclares argument - JavaScript
examples invalid cases in this case, the variable "arg" redeclares the argument.
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 ...
TypeError: 'x' is not iterable - JavaScript
examples iterating over object properties in javascript, objects are not iterable unless they implement the iterable protocol.
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.length - JavaScript
examples using arguments.length in this example we define a function that can add two or more numbers together.
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 th...
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(u...
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.
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.
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.
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-- prim...
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 big...
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 big...
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.
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:0...
Date.prototype.getMinutes() - JavaScript
examples using getminutes() the second statement below assigns the value 15 to the variable minutes, based on the value of the date object xmas95.
Date.prototype.getUTCDate() - JavaScript
examples using getutcdate() the following example assigns the day portion of the current date to the variable day.
Date.prototype.getUTCMilliseconds() - JavaScript
examples using getutcmilliseconds() the following example assigns the milliseconds portion of the current time to the variable milliseconds.
Date.prototype.getUTCMinutes() - JavaScript
examples using getutcminutes() the following example assigns the minutes portion of the current time to the variable minutes.
Date.prototype.getUTCSeconds() - JavaScript
examples using getutcseconds() the following example assigns the seconds portion of the current time to the variable seconds.
Date.now() - JavaScript
engines which have not been updated to support this method can work around the absence of this method using the following shim: if (!date.now) { date.now = function now() { return new date().gettime(); }; } examples reduced time precision to offer protection against timing attacks and fingerprinting, the precision of date.now() might get rounded depending on browser settings.
Date.prototype.setYear() - JavaScript
examples using setyear() the first two lines set the year to 1996.
Date.prototype.toGMTString() - JavaScript
examples simple example in this example, the togmtstring() method converts the date to gmt (utc) using the operating system's time-zone offset and returns a string value that is similar to the following form.
Date.prototype.toSource() - JavaScript
examples native function for the built-in date object, tosource() returns the following string indicating that the source code is not available: function date() { [native code] } specifications not part of any standard.
Date.prototype.valueOf() - JavaScript
examples using valueof() var x = new date(56, 6, 17); var myvar = x.valueof(); // assigns -424713600000 to myvar specifications specification ecmascript (ecma-262)the definition of 'date.prototype.valueof' in that specification.
Error() constructor - JavaScript
examples function call or new construction when error is used like a function -- without new, it will return an error object.
Error.prototype.columnNumber - JavaScript
examples using columnnumber var e = new error('could not parse input'); throw e; console.log(e.columnnumber) // 0 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.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() constructor - JavaScript
examples creating a new registry you create the registry passing in the callback: const registry = new finalizationregistry(heldvalue => { // ....
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 ...
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); co...
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); co...
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); co...
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); co...
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.displayName - JavaScript
examples setting a displayname it is usually preferred by consoles and profilers over func.name to display the name of a function.
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.return() - JavaScript
examples using return() the following example shows a simple generator and the return method.
Generator.prototype.throw() - JavaScript
examples using throw() the following example shows a simple generator and an error that is thrown using the throw method.
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 // ...
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 // fr...
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 // fr...
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.displa...
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​.format() - JavaScript
examples using format the following example shows how to create a list formatter using the english language.
Intl​.List​Format​.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​.List​Format​.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 'resolvedopt...
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.prototype.calendar - JavaScript
islamicc civil (algorithmic) arabic calendar examples adding a calendar in the locale string calendar eras fall under the category of locale key "extension keys".
Intl.Locale.prototype.caseFirst - JavaScript
examples setting the casefirst value via the locale string in the unicode locale string spec, the values that casefirst represents correspond to the key kf.
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.hourCycle - JavaScript
examples these examples will show you how to add hour cycle data to your locale object.
Intl.Locale.prototype.language - JavaScript
examples setting the language in the locale identifer string argument in order to be a valid unicode locale identifier, a string must start with the language subtag.
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.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.PluralRules() constructor - JavaScript
examples basic usage in basic use without specifying a locale, a formatted string in the default locale and with default options is returned.
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" sp...
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.
Intl.PluralRules - JavaScript
examples using locales this example shows some of the variations in localized plural rules.
Intl.RelativeTimeFormat() constructor - JavaScript
examples basic format usage the following example shows how to create a relative time formatter using the english language.
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.
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.
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 tha...
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.l...
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 // u...
Object.prototype.__lookupGetter__() - JavaScript
examples standard-compliant and non-standard ways to get a property getter var obj = { get foo() { return math.random() > 0.5 ?
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.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 i...
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); ...
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.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(v...
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 ...
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.compile() - JavaScript
examples using compile() the following example shows how to recompile a regular expression with a new pattern and a new flag.
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 ...
RegExpInstance.lastIndex - JavaScript
examples using lastindex consider the following sequence of statements: var re = /(hi)?/g; matches the empty string.
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.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.
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.
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.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.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.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 specif...
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 specificat...
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.
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.
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 ...
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 ...
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 ecmascr...
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 d...
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 ecmascrip...
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(...
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(...
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(...
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(...
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]); // ...
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]); // ...
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 typedarra...
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 typedarra...
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() constructor - JavaScript
examples creating a new weakref object see the main weakref page for a complete example.
WeakRef.prototype.deref() - JavaScript
examples using deref see the examples section of the weakref page for the complete example.
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 th...
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.
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.
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.Memory.prototype.grow() - JavaScript
examples using grow the following example creates a new webassembly memory instance with an initial size of 1 page (64kib), and a maximum size of 10 pages (640kib).
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) .
WebAssembly.Module.exports() - JavaScript
examples using exports the following example (see our index-compile.html demo on github, and view it live also) compiles the loaded simple.wasm byte code using the webassembly.compilestreaming() method and then sends it to a worker using postmessage().
WebAssembly.Module.imports() - JavaScript
examples using imports the following example (see imports.html source code; see it live also) compiles the loaded simple.wasm module.
WebAssembly.Module - JavaScript
examples sending a compiled module to a worker the following example (see our index-compile.html demo on github, and view it live also) compiles the loaded simple.wasm byte code using the webassembly.compilestreaming() method and then sends the resulting module instance to a worker using postmessage().
WebAssembly.RuntimeError() constructor - JavaScript
examples creating a new runtimeerror instance the following snippet creates a new runtimeerror instance, and logs its details to the console: try { throw new webassembly.runtimeerror('hello', 'somefile', 10); } catch (e) { console.log(e instanceof runtimeerror); // true console.log(e.message); // "hello" console.log(e.name); // "runtimeerror" console.log(e.
WebAssembly.RuntimeError - JavaScript
examples creating a new runtimeerror instance the following snippet creates a new runtimeerror instance, and logs its details to the console: try { throw new webassembly.runtimeerror('hello', 'somefile', 10); } catch (e) { console.log(e instanceof runtimeerror); // true console.log(e.message); // "hello" console.log(e.name); // "runtimeerror" console.log(e.
WebAssembly.Table.prototype.get() - JavaScript
examples using get the following example (see table.html on github, and view it live also) compiles and instantiates the loaded table.wasm byte code using the webassembly.instantiatestreaming() method.
WebAssembly.Table.prototype.grow() - JavaScript
examples using grow the following example creates a new webassembly table instance with an initial size of 2 and a maximum size of 10.
WebAssembly.Table.prototype.length - JavaScript
syntax table.length; examples using length the following example creates a new webassembly table instance with an initial size of 2 and a maximum size of 10.
WebAssembly.compile() - JavaScript
examples using compile the following example compiles the loaded simple.wasm byte code using the compile() function and then sends it to a worker using postmessage().
WebAssembly.compileStreaming() - JavaScript
examples compile streaming the following example (see our compile-streaming.html demo on github, and view it live also) directly streams a .wasm module from an underlying source then compiles it to a webassembly.module object.
WebAssembly.instantiateStreaming() - JavaScript
examples instantiating streaming 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.
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.
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.
Standard built-in objects - JavaScript
arraybuffer sharedarraybuffer atomics dataview json control abstraction objects control abstractions can help to structure code, especially async code (without using deeply nested callbacks, for example).
Pipeline operator (|>) - JavaScript
examples chaining function calls the pipeline operator can improve readability when chaining several functions.
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 af...
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.
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.
Transitioning to strict mode - JavaScript
the only legitimate use case would be to reuse a function as in: // example taken from vanillajs: http://vanilla-js.com/ var s = document.getelementbyid('thing').style; s.opacity = 1; (function() { if ((s.opacity-=.1) < 0) s.display = 'none'; else settimeout(arguments.callee, 40); })(); which can be rewritten as: 'use strict'; var s = document.getelementbyid('thing').style; s.opacity = 1; (function fadeout() { // name the function if((s.opacity-=.1) < 0) ...
background_color - Web app manifests
examples "background_color": "red" specification specification status comment feedback web app manifestthe definition of 'background_color' in that specification.
categories - Web app manifests
example "categories": ["books", "education", "medical"] specification specification status comment feedback web app manifestthe definition of 'categories' 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.
dir - Web app manifests
WebManifestdir
example "dir": "rtl", "lang": "ar", "short_name": "!أنا من التطبيق" specification specification status comment feedback web app manifestthe definition of 'dir' in that specification.
display - Web app manifests
(none) example "display": "standalone" specification specification status comment feedback web app manifestthe definition of 'display' 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.
lang - Web app manifests
WebManifestlang
examples "lang": "en-us" specification specification status comment feedback web app manifestthe definition of 'lang' in that specification.
name - Web app manifests
WebManifestname
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.
prefer_related_applications - Web app manifests
examples "prefer_related_applications": true specification specification status comment feedback web app manifestthe definition of 'prefer_related_applications' in that specification.
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.
Web app manifests
click each one for more information about it: background_colorcategoriesdescriptiondirdisplayiarc_rating_idiconslangnameorientationprefer_related_applicationsrelated_applicationsscopescreenshotsserviceworkershort_nameshortcutsstart_urltheme_color example manifest { "name": "hackerweb", "short_name": "hackerweb", "start_url": ".", "display": "standalone", "background_color": "#fff", "description": "a simply readable hacker news app.", "icons": [{ "src": "images/touch/homescreen48.png", "sizes": "48x48", "type": "image/png" }, { "src": "images/touch/homescreen72.png", "sizes": "72x72", "type": "image/png" ...
<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>&sdot;</mo> <mn>2</mn> </mrow> <mrow> <mn>4</mn> <mo>&sdot;</mo> <mn>2</mn> </mrow> </mfrac> <mfrac> <mn>3</mn> <mn>4</mn> </mfrac> </maction> </math> ...
<math> - MathML
WebMathMLElementmath
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
WebMathMLElementmerror
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
WebMathMLElementmfrac
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
WebMathMLElementmglyph
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.
<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 ...
<mover> - MathML
WebMathMLElementmover
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> &#x23de; <!--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
WebMathMLElementmroot
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
WebMathMLElementmrow
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.
<mspace> - MathML
WebMathMLElementmspace
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
WebMathMLElementmsqrt
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
WebMathMLElementmstyle
examples using displaystyle and mathcolor to effect style changes in the layout of the whole sum.
<msub> - MathML
WebMathMLElementmsub
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> &#x222b;<!--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
WebMathMLElementmsup
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
WebMathMLElementmtable
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> ...
<munder> - MathML
WebMathMLElementmunder
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> &#x23df; <!--bottom curly bracket--> </mo> </munder> </math> specifications specification status comment mathml 3.0the definition of 'mund...
<munderover> - MathML
examples sample rendering: rendering in your browser: ∫ 0 ∞ <math displaystyle="true"> <munderover > <mo> &#x222b; <!--integral--> </mo> <mn> 0 </mn> <mi> &#x221e; <!--infinity--> </mi> </munderover> </math> specifications specification status comment mathml 3.0the definition of 'munderover' in that specification.
<semantics> - MathML
example <math> <semantics> <!-- presentation mathml --> <mrow> <msup> <mi>x</mi> <mn>2</mn> </msup> <mo>+</mo> <mi>y</mi> </mrow> <!-- content mathml --> <annotation-xml encoding="mathml-content"> <apply> <plus/> <apply> <power/> <ci>x</ci> <cn type="integer">2</cn> </apply> ...
Handling media support issues in web content - Web media technologies
in the case of an action movie, for example, the poster frame might be an iconic exemplar image from one of the film's best-known scenes.
Web media technologies
<video> can also be used as a way to link media apis with other html and dom technologies, including <canvas> (for frame grabbing and manipulation), for example.
CSS and JavaScript animation performance - Web Performance
enabling fps tools before going through the example, please enable fps tools first to see the current frame rate: in the url bar, enter about:config; click the i’ll be careful, i promise!
Critical rendering path - Web Performance
for example, .foo {} is faster than .bar .foo {} because when the browser finds .foo, in the second scenario, it has to walk up the dom to check if .foo has an ancestor .bar.
Navigation and resource timings - Web Performance
for example, how long did the request take?
Performance budgets - Web Performance
for example, you may introduce a feature that increases overall load time but attempts to increase user engagement.
Understanding latency - Web Performance
latency can be measured one way, for example, the amount of time it takes to send a request for resources, or the length of the entire round-trip from the browser’s request for a resource to the moment when the requested resource arrives at the browser.
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.
Graphic design for responsive sites - Progressive web apps (PWAs)
for example, if your desktop layout includes a large header graphic and several programmatic graphics (e.g.
baseFrequency - SVG: Scalable Vector Graphics
example <svg width="200" height="200" viewbox="0 0 220 220" xmlns="http://www.w3.org/2000/svg"> <filter id="displacementfilter"> <feturbulence type="turbulence" basefrequency="0.05" numoctaves="2" result="turbulence"/> <fedisplacementmap in2="turbulence" in="sourcegraphic" scale="50" xchannelselector="r" ychannelselector="g"/> </filter> <circle cx="100" cy="100" r="10...
clip-rule - SVG: Scalable Vector Graphics
example <svg width="100" viewbox="0 0 100 90" xmlns="http://www.w3.org/2000/svg" version="1.1"> <!-- define star path --> <defs> <path d="m50,0 21,90 98,35 2,35 79,90z" id="star" /> </defs> <!-- left: evenodd --> <clippath id="emptystar"> <use xlink:href="#star" clip-rule="evenodd" /> </clippath> <rect clip-path="url(#emptystar)" width="50" height="90" fill="blue" /> <!-- right...
color-rendering - SVG: Scalable Vector Graphics
for example, assume color-rendering: optimizespeed and color-interpolation-filters: linearrgb.
color - SVG: Scalable Vector Graphics
WebSVGAttributecolor
usage notes value <color> | inherit default value depends on user agent animatable yes example html, body, svg { height: 100%; } <svg viewbox="0 0 100 100" xmlns="http://www.w3.org/2000/svg"> <g color="green"> <rect width="50" height="50" fill="currentcolor" /> <circle r="25" cx="70" cy="70" stroke="currentcolor" fill="none" stroke-width="5" /> </g> </svg> specifications specification status comment scalable vector graphics (svg) 2the defi...
cx - SVG: Scalable Vector Graphics
WebSVGAttributecx
value <length> default value 50% animatable yes example html,body,svg { height:100% } <svg viewbox="0 0 34 10" xmlns="http://www.w3.org/2000/svg"> <defs> <radialgradient cx="0" id="mygradient000"> <stop offset="0%" stop-color="gold" /> <stop offset="50%" stop-color="green" /> <stop offset="100%" stop-color="white" /> </radialgradient> <radialgradient cx="50%" id="mygradient050"> <stop offset="0%" stop-co...
cy - SVG: Scalable Vector Graphics
WebSVGAttributecy
value <length> default value 50% animatable yes example html,body,svg { height:100% } <svg viewbox="0 0 34 10" xmlns="http://www.w3.org/2000/svg"> <defs> <radialgradient cy="0" id="mygradient000"> <stop offset="0%" stop-color="gold" /> <stop offset="50%" stop-color="green" /> <stop offset="100%" stop-color="white" /> </radialgradient> <radialgradient cy="50%" id="mygradient050"> <stop offset="0%" stop-co...
display - SVG: Scalable Vector Graphics
WebSVGAttributedisplay
for example, setting it to none on a <path> element will prevent that element from getting rendered directly onto the canvas, but the <path> element can still be referenced by a <textpath> element; furthermore, its geometry will be used in text-on-a-path processing even if the <path> has a display value of none.
dominant-baseline - SVG: Scalable Vector Graphics
example svg <svg width="400" height="300" viewbox="0 0 300 300" xmlns="http://www.w3.org/2000/svg"> <!-- materialization of anchors --> <path d="m60,20 l60,270 m30,20 l400,20 m30,70 l400,70 m30,120 l400,120 m30,170 l400,170 m30,220 l400,220 m30,270 l400,270" stroke="grey" /> <!-- anchors in action --> <text dominant-bas...
dx - SVG: Scalable Vector Graphics
WebSVGAttributedx
value list of <length> default value none animatable yes example html,body,svg { height:100% } <svg viewbox="0 0 100 100" xmlns="http://www.w3.org/2000/svg"> <!-- lines materialized the position of the glyphs --> <line x1="0" x2="100%" y1="25%" y2="25%" /> <line x1="0" x2="100%" y1="50%" y2="50%" /> <line x1="0" x2="100%" y1="75%" y2="75%" /> <line x1="10%" x2="10%" y1="0" y2="100%" /> <line x1="30%" x2="30%" y1="0" y2="100%" /> <line...
dy - SVG: Scalable Vector Graphics
WebSVGAttributedy
value list of <length> default value none animatable yes example html,body,svg { height:100% } <svg viewbox="0 0 150 100" xmlns="http://www.w3.org/2000/svg"> <!-- horizontal lines --> <line x1="0" x2="100%" y1="30" y2="30" /> <line x1="0" x2="100%" y1="40" y2="40" /> <line x1="0" x2="100%" y1="50" y2="50" /> <line x1="0" x2="100%" y1="60" y2="60" /> <!-- vertical lines --> <line x1="10" x2="10" y1="0" y2="100%" /> <line x1="50" x2="50" y1=...
fr - SVG: Scalable Vector Graphics
WebSVGAttributefr
top offset="0%" stop-color="white"/> <stop offset="100%" stop-color="darkseagreen"/> </radialgradient> </defs> <circle cx="100" cy="100" r="100" fill="url(#gradient1)" /> <circle cx="100" cy="100" r="100" fill="url(#gradient2)" style="transform: translatex(240px);" /> </svg> usage notes value <length> default value 0 animatable none example <svg viewbox="0 0 120 120" width="200" height="200" xmlns="http://www.w3.org/2000/svg"> <defs> <radialgradient id="gradient" cx="0.5" cy="0.5" r="0.5" fx="0.35" fy="0.35" fr="5%"> <stop offset="0%" stop-color="red"/> <stop offset="100%" stop-color="blue"/> </radialgradient> </defs> <rect x="10" y="10" rx="15" ry="15" width="100" height="100" fill="url(#gr...
fx - SVG: Scalable Vector Graphics
WebSVGAttributefx
animatable none example <svg viewbox="0 0 120 120" width="200" height="200" xmlns="http://www.w3.org/2000/svg"> <defs> <radialgradient id="gradient" cx="0.5" cy="0.5" r="0.5" fx="0.35" fy="0.35" fr="5%"> <stop offset="0%" stop-color="red"/> <stop offset="100%" stop-color="blue"/> </radialgradient> </defs> <rect x="10" y="10" rx="15" ry="15" width="100" height="100" fill="url(#gr...
fy - SVG: Scalable Vector Graphics
WebSVGAttributefy
animatable none example <svg viewbox="0 0 120 120" width="200" height="200" xmlns="http://www.w3.org/2000/svg"> <defs> <radialgradient id="gradient" cx="0.5" cy="0.5" r="0.5" fx="0.35" fy="0.35" fr="5%"> <stop offset="0%" stop-color="red"/> <stop offset="100%" stop-color="blue"/> </radialgradient> </defs> <rect x="10" y="10" rx="15" ry="15" width="100" height="100" fill="url(#gr...
href - SVG: Scalable Vector Graphics
WebSVGAttributehref
value <url> default value none animatable yes example html, body, svg { height: 100%; } <svg viewbox="0 0 100 100" xmlns="http://www.w3.org/2000/svg"> <image href="/files/2917/fxlogo.png" x="0" y="0" height="100" width="100"/> </svg> lineargradient for <lineargradient>, href defines url referring to a template gradient element; to be valid, the reference must be to a different <lineargradient> or <radialgradient> element.
numOctaves - SVG: Scalable Vector Graphics
example <svg width="200" height="200" viewbox="0 0 220 220" xmlns="http://www.w3.org/2000/svg"> <filter id="displacementfilter"> <feturbulence basefrequency="0.05" numoctaves="3" result="turbulence"/> <fedisplacementmap in2="turbulence" in="sourcegraphic" scale="50" xchannelselector="r" ychannelselector="g"/> </filter> <circle cx="100" cy="100" r="100" style="fi...
orient - SVG: Scalable Vector Graphics
WebSVGAttributeorient
note: for example, if a value of 45 is given, then the marker's positive x-axis would be pointing down and right in the shape's coordinate system.
pathLength - SVG: Scalable Vector Graphics
stroke-dasharray, for example, will assume the start of the path being 0 and the end point the value defined in the pathlength attribute.
requiredExtensions - SVG: Scalable Vector Graphics
the iri names for the extension should include versioning information, such as "http://example.org/svgextensionxyz/1.0", so that script writers can distinguish between different versions of a given extension.
requiredFeatures - SVG: Scalable Vector Graphics
sing-glyph>, <hkern>, <vkern>, <font-face-src>, <font-face-uri>, <font-face-format> and <font-face-name> elements http://www.w3.org/tr/svg11/feature#basicfont the browser supports the <font>, <font-face>, <glyph>, <missing-glyph>, <hkern>, <font-face-src> and <font-face-name> elements http://www.w3.org/tr/svg11/feature#extensibility the browser supports the <foreignobject> element example svg <svg width="450" height="1170" xmlns="http://www.w3.org/2000/svg"> <!-- testing : http://www.w3.org/tr/svg11/feature#svg --> <rect class="ko" x="10" y="10" height="25" width="430" /> <rect class="ok" x="10" y="10" height="25" width="430" requiredfeatures="http://www.w3.org/tr/svg11/feature#svg" /> <text x="20" y="27">http://www.w3.org/tr/svg11/feature#svg</text> <!-- testing ...
rotate - SVG: Scalable Vector Graphics
WebSVGAttributerotate
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"> ...
seed - SVG: Scalable Vector Graphics
WebSVGAttributeseed
" y="0" width="100%" height="100%"> <feturbulence basefrequency="0.025" seed="100" /> </filter> <rect x="0" y="0" width="200" height="200" style="filter:url(#noise1);" /> <rect x="0" y="0" width="200" height="200" style="filter:url(#noise2); transform: translatex(220px);" /> </svg> usage notes value <number> default value 0 animatable yes example <svg width="200" height="200" viewbox="0 0 220 220" xmlns="http://www.w3.org/2000/svg"> <filter id="displacementfilter"> <feturbulence basefrequency="0.05" seed="1000" result="turbulence"/> <fedisplacementmap in2="turbulence" in="sourcegraphic" scale="50" xchannelselector="r" ychannelselector="g"/> </filter> <circle cx="100" cy="100" r="100" style="filte...
stemh - SVG: Scalable Vector Graphics
WebSVGAttributestemh
for example, the main vertical stems of roman characters will differ from the thin stems on serifed "m" and "n", plus there may be different widths for uppercase and lowercase characters in the same font.
stroke-dashoffset - SVG: Scalable Vector Graphics
stroke-dasharray="3 1" stroke-dashoffset="3" /> <!-- the start of the dash array computation is pushed by 3 user units --> <line x1="0" y1="7" x2="30" y2="7" stroke="black" stroke-dasharray="3 1" stroke-dashoffset="-3" /> <!-- the start of the dash array computation is pulled by 1 user units which ends up in the same rendering as the previous example --> <line x1="0" y1="9" x2="30" y2="9" stroke="black" stroke-dasharray="3 1" stroke-dashoffset="1" /> <!-- the following red lines highlight the offset of the dash array for each line --> <path d="m0,5 h-3 m0,7 h3 m0,9 h-1" stroke="rgba(255,0,0,.5)" /> </svg> usage notes value <percentage> | <length> default value 0 animatable...
stroke-miterlimit - SVG: Scalable Vector Graphics
the ratio of miter length (distance between the outer tip and the inner corner of the miter) to stroke-width is directly related to the angle (theta) between the segments in user space by the formula: stroke-miterlimit = miterlength stroke-width = 1 sin ( θ 2 ) for example, a miter limit of 1.414 converts miters to bevels for theta less than 90 degrees, a limit of 4.0 converts them for theta less than approximately 29 degrees, and a limit of 10.0 converts them for theta less than approximately 11.5 degrees.
type - SVG: Scalable Vector Graphics
WebSVGAttributetype
e> element categories none value fractalnoise | turbulence animatable yes normative document svg 1.1 (2nd edition) for the <style> and <script> elements categories none value <content-type> animatable no normative document svg 1.1 (2nd edition) : script svg 1.1 (2nd edition) : style example elements the following elements can use the values attribute <animatetransform> <fecolormatrix> <fefunca> <fefuncb> <fefuncg> <fefuncr> <feturbulence> <script> <style> ...
vector-effect - SVG: Scalable Vector Graphics
example example: vector-effect="non-scaling-stroke" <svg viewbox="0 0 500 240"> <!-- normal --> <path d="m10,20l40,100l39,200z" stroke="black" stroke-width="2px" fill="none"></path> <!-- scaled --> <path transform="translate(100,0)scale(4,1)" d="m10,20l40,100l39,200z" stroke="black" stroke-width="2px" fill="none"></path> <!-- fixed--> <path vector-effect="non-scaling-stroke" transfo...
visibility - SVG: Scalable Vector Graphics
example the following example toggles the css visibility of the svg image path.
xlink:arcrole - SVG: Scalable Vector Graphics
for example, a resource might generically represent a "person," but in the context of a particular arc it might have the role of "mother" and in the context of a different arc it might have the role of "daughter." twentytwo elements are using this attribute: <a>, <altglyph>, <animate>, <animatecolor>, <animatemotion>, <animatetransform>, <color-profile>, <cursor>, <feimage>, <filter>, <font-face-uri>, <glyphref>, <image>, <lineargradient>, <mpath>, <pattern>, <radialgradient>, <script>, <set>, <textpath>, <tref>, <use> usage notes value ...
xlink:title - SVG: Scalable Vector Graphics
it may be used, for example, to make titles available to applications used by visually impaired users, or to create a table of links, or to present help text that appears when a user lets a mouse pointer hover over a starting resource.
xml:space - SVG: Scalable Vector Graphics
for example, the string "a b" (three spaces between "a" and "b") separates "a" and "b" more than "a b" (one space between "a" and "b").
<altGlyphItem> - SVG: Scalable Vector Graphics
usage context categoriestext content elementpermitted contentone or more <glyphref> elements example attributes global attributes core attributes specific attributes none dom interface this element implements the svgaltglyphitemelement interface.
<animateColor> - SVG: Scalable Vector Graphics
example svg <svg width="120" height="120" xmlns="http://www.w3.org/2000/svg"> <circle cx="60" cy="60" r="50"> <animatecolor attributename="fill" attributetype="xml" from="black" to="red" dur="6s" repeatcount="indefinite"/> </circle> </svg> result specifications specification status comment scalable vector graphics (svg) 1.1 (second edition)the definitio...
<animateTransform> - SVG: Scalable Vector Graphics
usage context categoriesanimation elementpermitted contentany number of the following elements, in any order:descriptive elements example <svg width="120" height="120" viewbox="0 0 120 120" xmlns="http://www.w3.org/2000/svg"> <polygon points="60,30 90,90 30,90"> <animatetransform attributename="transform" attributetype="xml" type="rotate" from="0 60 70" to="360 60 70" dur="10s" repeatcount="indefinite"/> </polygon> </svg> live sample attribu...
<clipPath> - SVG: Scalable Vector Graphics
WebSVGElementclipPath
for example, a circle with a radius of 10 which is clipped to a circle with a radius of 5 will not receive "click" events outside the smaller radius.
<defs> - SVG: Scalable Vector Graphics
WebSVGElementdefs
to display them you have to reference them (with a <use> element for example).
<ellipse> - SVG: Scalable Vector Graphics
WebSVGElementellipse
note: ellipses are unable to specify the exact orientation of the ellipse (if, for example, you wanted to draw an ellipse tilted at a 45 degree angle), but it can be rotated by using the transform attribute.
<feBlend> - SVG: Scalable Vector Graphics
WebSVGElementfeBlend
example svg <svg width="200" height="200" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> <defs> <filter id="spotlight"> <feflood result="floodfill" x="0" y="0" width="100%" height="100%" flood-color="green" flood-opacity="1"/> <feblend in="sourcegraphic" in2="floodfill" mode="multiply"/> </filter> </defs> <image xlink:href="//deve...
<feColorMatrix> - SVG: Scalable Vector Graphics
example svg <svg width="100%" height="100%" viewbox="0 0 150 500" preserveaspectratio="xmidymid meet" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> <!-- ref --> <defs> <g id="circles"> <circle cx="30" cy="30" r="20" fill="blue" fill-opacity="0.5" /> <circle cx="20" cy="50" r="20" fill="green" fill-opacity="0.5" /> <circle cx="40" c...
<feComponentTransfer> - SVG: Scalable Vector Graphics
example svg <svg xmlns="http://www.w3.org/2000/svg" viewbox="0 0 600 300"> <defs> <lineargradient id="rainbow" gradientunits="userspaceonuse" x1="0" y1="0" x2="100%" y2="0"> <stop offset="0" stop-color="#ff0000"></stop> <stop offset="0.2" stop-color="#ffff00"></stop> <stop offset="0.4" stop-color="#00ff00"></stop> <stop offset="0.6" stop-color="#00ffff"></stop> <stop...
<feConvolveMatrix> - SVG: Scalable Vector Graphics
example svg <svg width="200" height="200" viewbox="0 0 200 200" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> <defs> <filter id="emboss"> <feconvolvematrix kernelmatrix="3 0 0 0 0 0 0 0 -3"/> </filter> </defs> <image xlink:href="/files/12668/mdn.svg" x="0" y="0" height="200" width="...
<feDiffuseLighting> - SVG: Scalable Vector Graphics
example the following example show the effect of the <fediffuselighting> element on a circle with each light source available.
<feDisplacementMap> - SVG: Scalable Vector Graphics
example <svg width="200" height="200" viewbox="0 0 220 220" xmlns="http://www.w3.org/2000/svg"> <filter id="displacementfilter"> <feturbulence type="turbulence" basefrequency="0.05" numoctaves="2" result="turbulence"/> <fedisplacementmap in2="turbulence" in="sourcegraphic" scale="50" xchannelselector="r" ychannelselector="g"/> </filter> <circle cx="100" cy="100" r="10...
<feFlood> - SVG: Scalable Vector Graphics
WebSVGElementfeFlood
example html content <svg xmlns="http://www.w3.org/2000/svg" width="200" height="200"> <defs> <filter id="floodfilter" filterunits="userspaceonuse"> <feflood x="50" y="50" width="100" height="100" flood-color="green" flood-opacity="0.5"/> </filter> </defs> <use style="filter: url(#floodfilter);"/> </svg> result specifications specification status comme...
<feImage> - SVG: Scalable Vector Graphics
WebSVGElementfeImage
example svg <svg viewbox="0 0 200 200" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> <defs> <filter id="image"> <feimage xlink:href="/files/6457/mdn_logo_only_color.png"/> </filter> </defs> <rect x="10%" y="10%" width="80%" height="80%" style="filter:url(#image);"/> </svg> result specifications specification status comm...
<feMerge> - SVG: Scalable Vector Graphics
WebSVGElementfeMerge
usage context categoriesfilter primitive elementpermitted contentany number of the following elements, in any order:<femergenode> example svg <svg width="200" height="200" xmlns="http://www.w3.org/2000/svg"> <filter id="feoffset" x="-40" y="-20" width="100" height="200"> <feoffset in="sourcegraphic" dx="60" dy="60" /> <fegaussianblur stddeviation="5" result="blur2" /> <femerge> <femergenode in="blur2" /> <femergenode in="sourcegraphic" /> </femerge> </filter> <rect x="40" y="40" width="100" height="100" style="stroke: #000000...
<feMergeNode> - SVG: Scalable Vector Graphics
usage context categoriesnonepermitted contentany number of the following elements, in any order:<animate>, <set> example <svg width="200" height="200" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> <filter id="feoffset" x="-40" y="-20" width="100" height="200"> <feoffset in="sourcegraphic" dx="60" dy="60" /> <fegaussianblur in="sourcegraphic" stddeviation="5" result="blur2" /> <femerge> <femergenode in="blur2" /> <femergenode in="sourcegraphic" /> </femerge> </filter> <rect x="40" y="40" width="100" height="100" style="stroke: #000000; fill: green; filter: url(#feoffset);" /> <rec...
<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> ...
<feOffset> - SVG: Scalable Vector Graphics
WebSVGElementfeOffset
example svg <svg width="200" height="200" xmlns="http://www.w3.org/2000/svg"> <defs> <filter id="offset" width="180" height="180"> <feoffset in="sourcegraphic" dx="60" dy="60" /> </filter> </defs> <rect x="0" y="0" width="100" height="100" stroke="black" fill="green"/> <rect x="0" y="0" width="100" height="100" stroke="black" fill="green" filter="url(#offset)"/> </svg> result ...
<fePointLight> - SVG: Scalable Vector Graphics
example svg <svg width="200" height="200" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> <defs> <filter id="spotlight"> <fespecularlighting result="spotlight" specularconstant="1.5" specularexponent="80" lighting-color="#fff"> <fepointlight x="50" y="50" z="220"/> </fespecularlighting> <fecomposite in="sourcegraphic" in2="spo...
<feSpecularLighting> - SVG: Scalable Vector Graphics
example <svg height="200" width="200" viewbox="0 0 220 220" xmlns="http://www.w3.org/2000/svg"> <filter id = "filter"> <fespecularlighting result="specout" specularexponent="20" lighting-color="#bbbbbb"> <fepointlight x="50" y="75" z="200"/> </fespecularlighting> <fecomposite in="sourcegraphic" in2="specout" operator="arithmetic" k1="0" k2="1" k3="1" k4="0"/> </...
<feSpotLight> - SVG: Scalable Vector Graphics
example html content <svg width="200" height="200" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> <defs> <filter id="spotlight"> <fespecularlighting result="spotlight" specularconstant="1.5" specularexponent="4" lighting-color="#fff"> <fespotlight x="600" y="600" z="400" limitingconeangle="5.5" /> </fespecularlighting> <fecom...
<feTile> - SVG: Scalable Vector Graphics
WebSVGElementfeTile
example svg <svg width="200" height="200" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> <defs> <filter id="tile" x="0" y="0" width="100%" height="100%"> <fetile in="sourcegraphic" x="50" y="50" width="100" height="100" /> <fetile/> </filter> </defs> <image xlink:href="/files/6457/mdn_logo_only_color.png" x="10%" y="10%" wid...
<feTurbulence> - SVG: Scalable Vector Graphics
example <svg width="200" height="200" viewbox="0 0 220 220" xmlns="http://www.w3.org/2000/svg"> <filter id="displacementfilter"> <feturbulence type="turbulence" basefrequency="0.05" numoctaves="2" result="turbulence"/> <fedisplacementmap in2="turbulence" in="sourcegraphic" scale="50" xchannelselector="r" ychannelselector="g"/> </filter> <circle cx="100" cy="100" r="10...
<filter> - SVG: Scalable Vector Graphics
WebSVGElementfilter
example svg <svg width="230" height="120" xmlns="http://www.w3.org/2000/svg"> <filter id="blurme"> <fegaussianblur stddeviation="5"/> </filter> <circle cx="60" cy="60" r="50" fill="green" /> <circle cx="170" cy="60" r="50" fill="green" filter="url(#blurme)" /> </svg> result screenshotlive sample specifications specification status comment filter effect...
<glyph> - SVG: Scalable Vector Graphics
WebSVGElementglyph
example svg <svg width="400px" height="300px" version="1.1" xmlns="http://www.w3.org/2000/svg"> <!-- example copied from https://www.w3.org/tr/svg/fonts.html#glyphelement --> <defs> <font id="font1" horiz-adv-x="1000"> <font-face font-family="super sans" font-weight="bold" font-style="normal" units-per-em="1000" cap-height="600" x-height="400" ascent="700" descent="...
<hatch> - SVG: Scalable Vector Graphics
WebSVGElementhatch
example svg <svg width="200" height="200" xmlns="http://www.w3.org/2000/svg"> <defs> <hatch id="hatch" hatchunits="userspaceonuse" pitch="5" rotate="135"> <hatchpath stroke="#a080ff" stroke-width="2"/> </hatch> </defs> <rect fill="url(#hatch)" stroke="black" stroke-width="2" x="10%" y="10%" width="80%" height="80%" /> </svg> result ...
<hatchpath> - SVG: Scalable Vector Graphics
WebSVGElementhatchpath
example svg <svg width="200" height="200" xmlns="http://www.w3.org/2000/svg"> <defs> <hatch id="hatch" hatchunits="userspaceonuse" pitch="5" rotate="135"> <hatchpath stroke="#a080ff" stroke-width="2"/> </hatch> </defs> <rect fill="url(#hatch)" stroke="black" stroke-width="2" x="10%" y="10%" width="80%" height="80%" /> </svg> result ...
<image> - SVG: Scalable Vector Graphics
WebSVGElementimage
example basic rendering of a png image in svg: svg <svg width="200" height="200" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> <image href="https://mdn.mozillademos.org/files/6457/mdn_logo_only_color.png" height="200" width="200"/> </svg> result specifications specification status comment scalable vector graphics (svg) 2the definit...
<mpath> - SVG: Scalable Vector Graphics
WebSVGElementmpath
example svg <svg width="100%" height="100%" viewbox="0 0 500 300" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" > <rect x="1" y="1" width="498" height="298" fill="none" stroke="blue" stroke-width="2" /> <!-- draw the outline of the motion path in blue, along with three small circles at the start, middle and end.
<polygon> - SVG: Scalable Vector Graphics
WebSVGElementpolygon
html,body,svg { height:100% } <svg viewbox="0 0 200 100" xmlns="http://www.w3.org/2000/svg"> <!-- example of a polygon with the default fill --> <polygon points="0,100 50,25 50,75 100,0" /> <!-- example of the same polygon shape with stroke and no fill --> <polygon points="100,100 150,25 150,75 200,0" fill="none" stroke="black" /> </svg> attributes points this attribute defines the list of points (pairs of x,y absolute coordinates) required to draw the polygon.
<polyline> - SVG: Scalable Vector Graphics
WebSVGElementpolyline
html,body,svg { height:100% } <svg viewbox="0 0 200 100" xmlns="http://www.w3.org/2000/svg"> <!-- example of a polyline with the default fill --> <polyline points="0,100 50,25 50,75 100,0" /> <!-- example of the same polyline shape with stroke and no fill --> <polyline points="100,100 150,25 150,75 200,0" fill="none" stroke="black" /> </svg> attributes points this attribute defines the list of points (pairs of x,y absolute coordinates) required to draw the polyline value type: <number>+ ; default va...
<solidcolor> - SVG: Scalable Vector Graphics
example svg <svg xmlns="http://www.w3.org/2000/svg" viewbox="0 0 300 200" height="150"> <defs> <!-- solidcolor is experimental.
<switch> - SVG: Scalable Vector Graphics
WebSVGElementswitch
svg <switch> example this example demonstrates showing different text content depending on the browser's language settings.
<tref> - SVG: Scalable Vector Graphics
WebSVGElementtref
example <svg width="100%" height="100%" viewbox="0 0 1000 300" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> <defs> <text id="referencedtext"> referenced character data </text> </defs> <text x="100" y="100" font-size="45" > inline character data </text> <text x="100" y="200" font-size="45" fill="red" > <tref xlink:href="#refere...
<view> - SVG: Scalable Vector Graphics
WebSVGElementview
usage context categoriesnonepermitted contentany number of the following elements, in any order:descriptive elements attributes global attributes aria attributes » core attributes » global event attributes » externalresourcesrequired specific attributes viewbox preserveaspectratio zoomandpan viewtarget example svg <svg width="600" height="200" viewbox="0 0 600 200" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> <defs> <radialgradient id="gradient"> <stop offset="0%" stop-color="#8cffa0" /> <stop offset="100%" stop-color="#8ca0ff" /> </radialgradient> </defs> <circle r="50" cx="180" cy="50" style="fill:url(#gradient)"/> <view id="ha...
Linking - SVG: Scalable Vector Graphics
WebSVGLinking
to get around this, requires a little ugly javascript hacking: button.svg: <?xml version="1.1" encoding="utf-8"?> <svg xmlns="http://www.w3.org/2000/svg"> <g onclick="top.document.href='page2.html'" cursor="pointer"> <!-- button graphical elements here --> </g> </svg> example for an example of this solution at work see www.codedread.com.
SVG 1.1 Support in Firefox - SVG: Scalable Vector Graphics
you can find some basic examples of svg syntax and usage in the w3c svg test suite.
Scripting - SVG: Scalable Vector Graphics
WebSVGScripting
more information and some examples can be found on the svg wiki inter-document scripting page.
Clipping and masking - SVG: Scalable Vector Graphics
the stroke, while on the other half the background will appear: <svg width="200" height="200" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> <rect x="0" y="0" width="200" height="200" fill="blue" /> <circle cx="100" cy="100" r="50" stroke="yellow" stroke-width="40" stroke-opacity=".5" fill="red" /> </svg> screenshotlive sample you see in this example the red circle on blue background.
Getting started - SVG: Scalable Vector Graphics
« previousnext » a simple example let us dive straight in with a simple example.
Positions - SVG: Scalable Vector Graphics
example: the element <rect x="0" y="0" width="100" height="100" /> defines a rectangle from the upper left corner, that spans from there 100px to the right and to the bottom.
SVG Filters Tutorial - SVG: Scalable Vector Graphics
svg filter example <defs> <filter id="drop-shadow"> <fegaussianblur in="sourcealpha" stddeviation="3"/> </filter> </defs> <g id="ghost" style="filter: url(#drop-shadow);"/> <!--ghost drawing in here--> </g> this above example will not produced the desired output.
SVG image element - SVG: Scalable Vector Graphics
in this basic example, a .jpg image referenced by an href attribute will be rendered inside an svg object: <?xml version="1.0" standalone="no"?> <!doctype svg public "-//w3c//dtd svg 1.1//en" "http://www.w3.org/graphics/svg/1.1/dtd/svg11.dtd"> <svg width="5cm" height="4cm" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> <image href="firefox.jpg" x="0" y="0" height="50px" width="50px"/> </svg> there are some important things to take note of (referenced from the w3 specs): if you do not set the x or y attributes, they will be set to 0.
SVG and CSS - SVG: Scalable Vector Graphics
example make a new svg document as a plain text file, doc8.svg.
Texts - SVG: Scalable Vector Graphics
WebSVGTutorialTexts
basics we have seen in the introducing example, that the text element can be used to put arbitrary text in svg documents: <text x="10" y="10">hello world!</text> the x and y attributes determine, where in the viewport the text will appear.
Insecure passwords - Web security
for example, a news site may save which news articles a user wants to go back to and read, but not save any other data about a user.
Secure contexts - Web security
for example, even for a document delivered over tls within an <iframe>, its context is not considered secure if it has an ancestor that was not also delivered over tls.
Securing your site - Web security
for example, .htaccess file is used for websites hosted on apache http server.
Web Components
examples we are building up a number of examples in our web-components-examples github repo.
ceiling - XPath
for example: ceiling (5.2) = 6 ceiling (-5.2) = -5 defined xpath 1.0 4.4 gecko support supported.
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.
Index - XPath
WebXPathIndex
57 xpath snippets example, snippets, xml, xpath, xslt this article provides some xpath code snippets.
XPath
there are some cases in which the whole content of an xml document must be read from the javascript interpreter (like for web-apps languages or settings xml documents, for example).
<xsl:text> - XSLT: Extensible Stylesheet Language Transformations
WebXSLTElementtext
if "yes" is set, for example, the character > is output as >, not as &gt;.
<xsl:value-of> - XSLT: Extensible Stylesheet Language Transformations
WebXSLTElementvalue-of
if "yes" is set, for example, the character > is output as >, not as "&gt".
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.
Introduction - XSLT: Extensible Stylesheet Language Transformations
for example, it permits the rearranging and sorting of elements; it also provides more fine-grained control of the resulting document's structure.
Setting Parameters - XSLT: Extensible Stylesheet Language Transformations
for example, javascript and xslt could be used to sort xml data and then display it.
The XSLT/JavaScript Interface in Gecko - XSLT: Extensible Stylesheet Language Transformations
introduction javascript/xslt bindings basic example setting parameters advanced example interface list resources ...
WebAssembly Concepts - WebAssembly
in a nutshell, the process works as follows: emscripten first feeds the c/c++ into clang+llvm — a mature open-source c/c++ compiler toolchain, shipped as part of xcode on osx for example.
WebAssembly
examples wasmsobel see our webassembly-examples repo for a number of other examples.